huzy0 commited on
Commit
b510e28
·
verified ·
1 Parent(s): f9f057c

Upload model

Browse files
Files changed (2) hide show
  1. model.safetensors +3 -0
  2. modeling_bestrq_conformer.py +1037 -0
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:042b79047d26f9d0a1136eb9d7215a1a67dff80c281c60caea0ab76c332c3836
3
+ size 2536954592
modeling_bestrq_conformer.py ADDED
@@ -0,0 +1,1037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import math
4
+ from torch import nn
5
+ from typing import Optional, Tuple, Union
6
+
7
+ from transformers.modeling_utils import PreTrainedModel
8
+ from transformers.activations import ACT2FN
9
+ from transformers.modeling_outputs import BaseModelOutput, Wav2Vec2BaseModelOutput, CausalLMOutput
10
+ from safetensors.torch import load_file
11
+
12
+ from .configuration_bestrq_conformer import MeralionBestRqConformerConfig
13
+
14
+
15
+ _HIDDEN_STATES_START_POSITION = 2
16
+
17
+
18
+ def lengths_to_padding_mask(lens: torch.LongTensor) -> torch.BoolTensor:
19
+ """
20
+ Create a boolean padding mask from a tensor of sequence lengths.
21
+
22
+ Args:
23
+ lens (`torch.LongTensor`):
24
+ A tensor of shape `(batch_size,)` containing the length of each sequence in the batch.
25
+
26
+ Returns:
27
+ `torch.BoolTensor`:
28
+ A boolean mask of shape `(batch_size, max_len)` where `True` indicates a padded position.
29
+ """
30
+ bsz, max_lens = lens.size(0), torch.max(lens).item()
31
+ mask = torch.arange(max_lens).to(lens.device).view(1, max_lens)
32
+ mask = mask.expand(bsz, -1) >= lens.view(bsz, 1).expand(-1, max_lens)
33
+ return mask
34
+
35
+
36
+ def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
37
+ """Make mask tensor containing indices of padded part.
38
+
39
+ See description of make_non_pad_mask.
40
+
41
+ Args:
42
+ lengths (torch.Tensor): Batch of lengths (B,).
43
+ Returns:
44
+ torch.Tensor: Mask tensor containing indices of padded part.
45
+
46
+ Examples:
47
+ >>> lengths = [5, 3, 2]
48
+ >>> make_pad_mask(lengths)
49
+ masks = [[0, 0, 0, 0 ,0],
50
+ [0, 0, 0, 1, 1],
51
+ [0, 0, 1, 1, 1]]
52
+ """
53
+ batch_size = lengths.size(0)
54
+ max_len = max_len if max_len > 0 else lengths.max().item()
55
+ seq_range = torch.arange(0,
56
+ max_len,
57
+ dtype=torch.int64,
58
+ device=lengths.device)
59
+ seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
60
+ seq_length_expand = lengths.unsqueeze(-1)
61
+ mask = seq_range_expand >= seq_length_expand
62
+ return mask
63
+
64
+
65
+ class Conv2dSubsampling(nn.Module):
66
+ """
67
+ Convolutional 2D subsampling (to 1/4 length)
68
+ For feature extraction/downsampling of input mel spectrogram
69
+
70
+ Args:
71
+ in_channels (int): Number of channels in the input image
72
+ out_channels (int): Number of channels produced by the convolution
73
+
74
+ Inputs:
75
+ inputs (batch, time, dim): Tensor containing sequence of inputs
76
+ input_lengths (batch): Tensor containing input_length for each item in batch
77
+
78
+ Returns:
79
+ outputs (batch, time, dim): Tensor produced by the convolution
80
+ output_lengths (batch): Tensor containing output_length for each item in batch
81
+ """
82
+ def __init__(self, config):
83
+ super().__init__()
84
+ self.sequential = nn.Sequential(
85
+ nn.Conv2d(config.input_channels, config.hidden_size, kernel_size=3, stride=2),
86
+ nn.ReLU(),
87
+ nn.Conv2d(config.hidden_size, config.hidden_size, kernel_size=3, stride=2),
88
+ nn.ReLU(),
89
+ )
90
+
91
+ def forward(self, inputs: torch.Tensor, input_lengths: torch.Tensor):
92
+ _, max_seq_len, _ = inputs.size()
93
+ outputs = self.sequential(inputs.unsqueeze(1))
94
+ batch_size, channels, subsampled_lengths, sumsampled_dim = outputs.size()
95
+
96
+ outputs = outputs.permute(0, 2, 1, 3)
97
+ outputs = outputs.contiguous().view(batch_size, subsampled_lengths, channels * sumsampled_dim)
98
+
99
+ subsampling_factor = int(max_seq_len * 1.0 / subsampled_lengths + 0.5)
100
+ input_len_0 = (input_lengths.float() / subsampling_factor).ceil().long()
101
+ input_len_1 = outputs.size(1) * torch.ones([input_lengths.size(0)]).long().to(
102
+ input_len_0.device
103
+ )
104
+ output_lengths = torch.min(input_len_0, input_len_1)
105
+
106
+ return outputs, output_lengths
107
+
108
+
109
+ class ConformerRelPositionalEmbedding(nn.Module):
110
+ """Relative positional encoding module (new implementation).
111
+
112
+ Args:
113
+ d_model: Embedding dimension.
114
+ dropout_rate: Dropout rate.
115
+ max_len: Maximum input length.
116
+ """
117
+ def __init__(self, config):
118
+ super().__init__()
119
+ self.max_len = config.max_source_positions
120
+ self.d_model = config.hidden_size
121
+ self.pe = None
122
+ self.extend_pe(torch.tensor(0.0).expand(1, self.max_len))
123
+
124
+ def extend_pe(self, x):
125
+ """Reset the positional encodings."""
126
+ if self.pe is not None:
127
+ # self.pe contains both positive and negative parts
128
+ # the length of self.pe is 2 * input_len - 1
129
+ if self.pe.size(1) >= x.size(1) * 2 - 1:
130
+ if self.pe.dtype != x.dtype or self.pe.device != x.device:
131
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
132
+ return
133
+ # Suppose `i` means to the position of query vector and `j` means the
134
+ # position of key vector. We use position relative positions when keys
135
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
136
+ pe_positive = torch.zeros(x.size(1), self.d_model)
137
+ pe_negative = torch.zeros(x.size(1), self.d_model)
138
+ position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
139
+ div_term = torch.exp(
140
+ torch.arange(0, self.d_model, 2, dtype=torch.float32)
141
+ * -(math.log(10000.0) / self.d_model)
142
+ )
143
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
144
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
145
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
146
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
147
+
148
+ # Reserve the order of positive indices and concat both positive and
149
+ # negative indices. This is used to support the shifting trick
150
+ # as in https://arxiv.org/abs/1901.02860
151
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
152
+ pe_negative = pe_negative[1:].unsqueeze(0)
153
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
154
+ self.pe = pe.to(device=x.device, dtype=x.dtype)
155
+
156
+ def forward(self, x: torch.Tensor):
157
+ """Add positional encoding.
158
+ Args:
159
+ x : Input tensor T X B X C.
160
+ Returns:
161
+ torch.Tensor: Encoded tensor T X B X C.
162
+
163
+ """
164
+ x = x.transpose(0, 1) # Change TBC to BTC
165
+ self.extend_pe(x)
166
+ pos_emb = self.pe[
167
+ :,
168
+ self.pe.size(1) // 2 - x.size(1) + 1 : self.pe.size(1) // 2 + x.size(1),
169
+ ]
170
+ pos_emb = pos_emb.transpose(0, 1) # change to TBC
171
+ return pos_emb
172
+
173
+
174
+ class ConformerRotaryPositionalEmbedding(nn.Module):
175
+ """Rotary positional embedding
176
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://arxiv.org/pdf/2104.09864.pdf
177
+ """
178
+
179
+ def __init__(self, config):
180
+ super().__init__()
181
+ dim = config.hidden_size // config.num_attention_heads
182
+ base = config.rotary_embedding_base
183
+
184
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
185
+ self.register_buffer("inv_freq", inv_freq)
186
+ self.cached_sequence_length = None
187
+ self.cached_rotary_positional_embedding = None
188
+
189
+ def forward(self, hidden_states):
190
+ sequence_length = hidden_states.shape[1]
191
+
192
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
193
+ return self.cached_rotary_positional_embedding
194
+
195
+ self.cached_sequence_length = sequence_length
196
+ # Embeddings are computed in the dtype of the inv_freq constant
197
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
198
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
199
+ embeddings = torch.cat((freqs, freqs), dim=-1)
200
+
201
+ cos_embeddings = embeddings.cos()[:, None, None, :]
202
+ sin_embeddings = embeddings.sin()[:, None, None, :]
203
+ # Computed embeddings are cast to the dtype of the hidden state inputs
204
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
205
+ return self.cached_rotary_positional_embedding
206
+
207
+
208
+ class ConformerInputFeatureProjection(nn.Module):
209
+ """
210
+ Projects the input features to the hidden size of the Conformer model. This layer is applied after the
211
+ convolutional subsampling.
212
+ """
213
+ def __init__(self, config):
214
+ super().__init__()
215
+ subsample_embed_dim = config.hidden_size * (((config.input_dim - 1) // 2 - 1) // 2)
216
+ #self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
217
+ self.projection = nn.Linear(subsample_embed_dim, config.hidden_size)
218
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
219
+
220
+ def forward(self, hidden_states):
221
+ """
222
+ Args:
223
+ hidden_states: Input Tensor of shape T X B X C
224
+ Returns:
225
+ Tensor of shape T X B X C
226
+ """
227
+ # non-projected hidden states are needed for quantization
228
+ #norm_hidden_states = self.layer_norm(hidden_states)
229
+ hidden_states = self.projection(hidden_states)
230
+ hidden_states = self.dropout(hidden_states)
231
+ return hidden_states
232
+
233
+
234
+ class ConformerFeedForward(nn.Module):
235
+ """Positionwise feed forward layer used in conformer"""
236
+ def __init__(self, config):
237
+ super().__init__()
238
+
239
+ #self.layer_norm = torch.nn.LayerNorm(config.hidden_size, eps=1e-5, elementwise_affine=True)
240
+
241
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
242
+
243
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.ffn_dim)
244
+ if isinstance(config.hidden_act, str):
245
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
246
+ else:
247
+ self.intermediate_act_fn = config.hidden_act
248
+
249
+ self.output_dense = nn.Linear(config.ffn_dim, config.hidden_size)
250
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
251
+
252
+ def forward(self, hidden_states):
253
+ """
254
+ Args:
255
+ x: Input Tensor of shape T X B X C
256
+ Returns:
257
+ Tensor of shape T X B X C
258
+ """
259
+ hidden_states = self.intermediate_dense(hidden_states)
260
+ hidden_states = self.intermediate_act_fn(hidden_states)
261
+ hidden_states = self.intermediate_dropout(hidden_states)
262
+ hidden_states = self.output_dense(hidden_states)
263
+ hidden_states = self.output_dropout(hidden_states)
264
+ return hidden_states
265
+
266
+
267
+ class ConformerConvolutionModule(nn.Module):
268
+ """Convolution block used in the conformer block"""
269
+
270
+ def __init__(self, config):
271
+ super().__init__()
272
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
273
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
274
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
275
+ self.pointwise_conv1 = nn.Conv1d(
276
+ config.hidden_size,
277
+ 2 * config.hidden_size,
278
+ kernel_size=1,
279
+ stride=1,
280
+ padding=0,
281
+ bias=False,
282
+ )
283
+ self.glu = nn.GLU(dim=1)
284
+ self.depthwise_conv = nn.Conv1d(
285
+ config.hidden_size,
286
+ config.hidden_size,
287
+ config.conv_depthwise_kernel_size,
288
+ stride=1,
289
+ padding=(config.conv_depthwise_kernel_size - 1) // 2,
290
+ groups=config.hidden_size,
291
+ bias=False,
292
+ )
293
+ self.batch_norm = nn.BatchNorm1d(config.hidden_size)
294
+ self.activation = ACT2FN[config.hidden_act]
295
+ self.pointwise_conv2 = nn.Conv1d(
296
+ config.hidden_size,
297
+ config.hidden_size,
298
+ kernel_size=1,
299
+ stride=1,
300
+ padding=0,
301
+ bias=False,
302
+ )
303
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
304
+
305
+ def forward(self, hidden_states):
306
+ """
307
+ Args:
308
+ hidden_states: Input of shape B X T X C
309
+ Returns:
310
+ Tensor of shape B X T X C
311
+ """
312
+ hidden_states = self.layer_norm(hidden_states)
313
+ hidden_states = hidden_states.transpose(1, 2)
314
+
315
+ # GLU mechanism
316
+ # => (batch, 2*channel, dim)
317
+ hidden_states = self.pointwise_conv1(hidden_states)
318
+ # => (batch, channel, dim)
319
+ hidden_states = self.glu(hidden_states)
320
+
321
+ # 1D Depthwise Conv
322
+ hidden_states = self.depthwise_conv(hidden_states)
323
+ hidden_states = self.batch_norm(hidden_states)
324
+ hidden_states = self.activation(hidden_states)
325
+
326
+ hidden_states = self.pointwise_conv2(hidden_states)
327
+ hidden_states = self.dropout(hidden_states)
328
+ hidden_states = hidden_states.transpose(1, 2)
329
+ return hidden_states
330
+
331
+
332
+ class ConformerSelfAttention(nn.Module):
333
+ """ConformerSelfAttention object.
334
+ Can be enhanced with rotary or relative position embeddings.
335
+ """
336
+
337
+ def __init__(self, config):
338
+ super().__init__()
339
+
340
+ self.head_size = config.hidden_size // config.num_attention_heads
341
+ self.num_heads = config.num_attention_heads
342
+ self.position_embeddings_type = config.position_embeddings_type
343
+
344
+ self.linear_q = nn.Linear(config.hidden_size, config.hidden_size)
345
+ self.linear_k = nn.Linear(config.hidden_size, config.hidden_size)
346
+ self.linear_v = nn.Linear(config.hidden_size, config.hidden_size)
347
+ self.linear_out = nn.Linear(config.hidden_size, config.hidden_size)
348
+
349
+ self.dropout = nn.Dropout(p=config.attention_dropout)
350
+
351
+ if self.position_embeddings_type == "relative":
352
+ # linear transformation for positional encoding
353
+ self.linear_pos = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
354
+ # these two learnable bias are used in matrix c and matrix d
355
+ # as described in https://arxiv.org/abs/1901.02860 Section 3.3
356
+ self.pos_bias_u = nn.Parameter(torch.Tensor(self.num_heads, self.head_size))
357
+ self.pos_bias_v = nn.Parameter(torch.Tensor(self.num_heads, self.head_size))
358
+ torch.nn.init.xavier_uniform_(self.pos_bias_u) ##
359
+ torch.nn.init.xavier_uniform_(self.pos_bias_v) ##
360
+
361
+ def forward(
362
+ self,
363
+ hidden_states: torch.Tensor, #[T, B, C]
364
+ attention_mask: Optional[torch.Tensor] = None,
365
+ relative_position_embeddings: Optional[torch.Tensor] = None, #[T, B, C]
366
+ output_attentions: bool = False,
367
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
368
+ # self-attention mechanism
369
+ hidden_states = hidden_states.transpose(0, 1) #[B, T, C]
370
+ relative_position_embeddings = relative_position_embeddings.transpose(0, 1) #[B, T, C]
371
+ batch_size, sequence_length, hidden_size = hidden_states.size()
372
+
373
+ # make sure query/key states can be != value states
374
+ query_key_states = hidden_states
375
+ value_states = hidden_states
376
+
377
+ if self.position_embeddings_type == "rotary":
378
+ if relative_position_embeddings is None:
379
+ raise ValueError(
380
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
381
+ )
382
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
383
+
384
+ # project query_key_states and value_states
385
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
386
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
387
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
388
+
389
+ # => (batch, head, time1, d_k)
390
+ query = query.transpose(1, 2)
391
+ key = key.transpose(1, 2)
392
+ value = value.transpose(1, 2)
393
+
394
+ if self.position_embeddings_type == "relative":
395
+ if relative_position_embeddings is None:
396
+ raise ValueError(
397
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
398
+ " 'relative'"
399
+ )
400
+ # apply relative_position_embeddings to qk scores
401
+ # as proposed in Transformer_XL: https://arxiv.org/abs/1901.02860
402
+ scores = self._apply_relative_embeddings(
403
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
404
+ )
405
+ else:
406
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
407
+
408
+ # apply attention_mask if necessary
409
+ if attention_mask is not None:
410
+ scores = scores.masked_fill(
411
+ attention_mask.unsqueeze(1).unsqueeze(2).to(bool),
412
+ float("-inf"), # (batch, head, time1, time2)
413
+ )
414
+
415
+ # => (batch, head, time1, time2)
416
+ probs = torch.softmax(scores, dim=-1)
417
+ probs = self.dropout(probs)
418
+
419
+ # => (batch, head, time1, d_k)
420
+ hidden_states = torch.matmul(probs, value)
421
+
422
+ # => (batch, time1, hidden_size)
423
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
424
+ hidden_states = self.linear_out(hidden_states)
425
+
426
+ # => (time1, batch, hidden_size)
427
+ hidden_states = hidden_states.transpose(0, 1)
428
+
429
+ return hidden_states, probs
430
+
431
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
432
+ batch_size, sequence_length, hidden_size = hidden_states.size()
433
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
434
+
435
+ cos = relative_position_embeddings[0, :sequence_length, ...]
436
+ sin = relative_position_embeddings[1, :sequence_length, ...]
437
+
438
+ # rotate hidden_states with rotary embeddings
439
+ hidden_states = hidden_states.transpose(0, 1)
440
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
441
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
442
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
443
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
444
+ hidden_states = hidden_states.transpose(0, 1)
445
+
446
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
447
+
448
+ return hidden_states
449
+
450
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
451
+ # 1. project positional embeddings
452
+ # => (batch, head, d_k, 2*time1-1)
453
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
454
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
455
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size # (batch, 2*time1-1, head, d_k)
456
+ )
457
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2) # (batch, head, 2*time1-1, d_k)
458
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3) # (batch, head, d_k, 2*time1-1)
459
+
460
+ # 2. Add bias to query
461
+ # => (batch, head, time1, d_k)
462
+ query = query.transpose(1, 2) # (batch, time1, head, d_k)
463
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
464
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
465
+
466
+ # 3. attention score: first compute matrix a and matrix c
467
+ # as described in https://arxiv.org/abs/1901.02860 Section 3.3
468
+ # => (batch, head, time1, time2)
469
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
470
+
471
+ # 4. then compute matrix b and matrix d
472
+ # => (batch, head, time1, 2*time1-1)
473
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
474
+
475
+ # 5. shift matrix b and matrix d
476
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
477
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
478
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
479
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
480
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
481
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
482
+
483
+ # 6. sum matrices
484
+ # => (batch, head, time1, time2)
485
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
486
+
487
+ return scores
488
+
489
+
490
+ class ConformerEncoderLayer(nn.Module):
491
+ """Conformer block based on https://arxiv.org/abs/2005.08100."""
492
+
493
+ def __init__(self, config):
494
+ super().__init__()
495
+ embed_dim = config.hidden_size
496
+ dropout = config.attention_dropout
497
+
498
+ # Feed-forward 1
499
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim)
500
+ self.ffn1 = ConformerFeedForward(config)
501
+
502
+ # Self-Attention
503
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim)
504
+ self.self_attn_dropout = nn.Dropout(dropout)
505
+ self.self_attn = ConformerSelfAttention(config)
506
+
507
+ # Conformer Convolution
508
+ self.conv_module = ConformerConvolutionModule(config)
509
+
510
+ # Feed-forward 2
511
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim)
512
+ self.ffn2 = ConformerFeedForward(config)
513
+ self.final_layer_norm = nn.LayerNorm(embed_dim)
514
+
515
+ def forward(
516
+ self,
517
+ hidden_states, # [T, B, C]
518
+ attention_mask: Optional[torch.Tensor] = None,
519
+ relative_position_embeddings: Optional[torch.Tensor] = None,
520
+ output_attentions: bool = False,
521
+ ):
522
+ hidden_states = hidden_states
523
+
524
+ # 1. Feed-Forward 1 layer
525
+ residual = hidden_states
526
+ hidden_states = self.ffn1_layer_norm(hidden_states)
527
+ hidden_states = self.ffn1(hidden_states)
528
+ hidden_states = hidden_states * 0.5 + residual
529
+ residual = hidden_states
530
+
531
+ # 2. Self-Attention layer
532
+ hidden_states = self.self_attn_layer_norm(hidden_states)
533
+ hidden_states, attn_weights = self.self_attn(
534
+ hidden_states=hidden_states,
535
+ attention_mask=attention_mask,
536
+ relative_position_embeddings=relative_position_embeddings,
537
+ output_attentions=output_attentions,
538
+ )
539
+ hidden_states = self.self_attn_dropout(hidden_states)
540
+ hidden_states = hidden_states + residual
541
+
542
+ # 3. Convolutional Layer
543
+ residual = hidden_states
544
+ hidden_states = hidden_states.transpose(0, 1) # [T,B,C] to [B,T,C]
545
+ hidden_states = self.conv_module(hidden_states)
546
+ hidden_states = hidden_states.transpose(0, 1) # [B,T,C] to [T,B,C]
547
+ hidden_states = residual + hidden_states
548
+
549
+ # 4. Feed-Forward 2 Layer
550
+ residual = hidden_states
551
+ hidden_states = self.ffn2_layer_norm(hidden_states)
552
+ hidden_states = self.ffn2(hidden_states)
553
+ hidden_states = hidden_states * 0.5 + residual
554
+ hidden_states = self.final_layer_norm(hidden_states)
555
+
556
+ return hidden_states, attn_weights
557
+
558
+
559
+ class ConformerEncoder(nn.Module):
560
+ """
561
+ The Conformer encoder module. This module is composed of a stack of Conformer layers and is responsible for
562
+ encoding the input features.
563
+
564
+ Args:
565
+ config ([`MeralionBestRqConformerConfig`]):
566
+ The configuration object for the model.
567
+ """
568
+ def __init__(self, config):
569
+ super().__init__()
570
+ self.config = config
571
+ self.embed_scale = math.sqrt(config.hidden_size)
572
+ if config.no_scale_embedding:
573
+ self.embed_scale = 1.0
574
+
575
+ if config.position_embeddings_type == "relative":
576
+ self.embed_positions = ConformerRelPositionalEmbedding(config)
577
+ elif config.position_embeddings_type == "rotary":
578
+ self.embed_positions = ConformerRotaryPositionalEmbedding(config)
579
+ else:
580
+ self.embed_positions = None
581
+
582
+ self.input_projection = ConformerInputFeatureProjection(config) # [T,B,C]
583
+
584
+ self.layers = nn.ModuleList([ConformerEncoderLayer(config) for _ in range(config.num_hidden_layers)])
585
+ self.gradient_checkpointing = False
586
+
587
+ self.self_condition_layers = self.config.self_condition_layers
588
+ self.conditioning_layer = None
589
+ self.conditioning_softmax = None
590
+ self.out_projection = None
591
+
592
+ if self.self_condition_layers:
593
+ # If self-conditioning is enabled, we need these layers
594
+ if self.config.vocab_size is None:
595
+ raise ValueError("output_size (i.e., vocab_size) must be provided for self-conditioning.")
596
+ self.conditioning_layer = nn.Linear(self.config.vocab_size, self.config.hidden_size)
597
+ self.conditioning_softmax = nn.Softmax(dim=-1)
598
+
599
+ def forward(
600
+ self,
601
+ hidden_states, # conv_out
602
+ attention_mask=None, # encoder_padding_mask
603
+ output_attentions=False,
604
+ output_hidden_states=False,
605
+ return_dict=True,
606
+ ctc_decoder=None,
607
+ ):
608
+ all_hidden_states = () if output_hidden_states else None
609
+ all_self_attentions = () if output_attentions else None
610
+ ctc_outputs = () if self.self_condition_layers else None
611
+
612
+ hidden_states = self.embed_scale * hidden_states
613
+
614
+ if self.embed_positions is not None:
615
+ relative_position_embeddings = self.embed_positions(hidden_states) # [T,B,C]
616
+ else:
617
+ relative_position_embeddings = None
618
+
619
+ hidden_states = self.input_projection(hidden_states) # [T,B,C]
620
+
621
+ if output_hidden_states:
622
+ all_hidden_states = all_hidden_states + (hidden_states.transpose(0, 1),)
623
+
624
+ for i, layer in enumerate(self.layers):
625
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
626
+ dropout_probability = torch.rand([])
627
+
628
+ skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False
629
+ if not skip_the_layer:
630
+ layer_outputs = layer(
631
+ hidden_states,
632
+ attention_mask=attention_mask,
633
+ relative_position_embeddings=relative_position_embeddings,
634
+ output_attentions=output_attentions,
635
+ )
636
+ hidden_states = layer_outputs[0]
637
+
638
+ if skip_the_layer:
639
+ layer_outputs = (None, None)
640
+
641
+ if output_hidden_states:
642
+ all_hidden_states = all_hidden_states + (hidden_states.transpose(0, 1),) # [T,B,C] -> [B,T,C]
643
+
644
+ if output_attentions:
645
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
646
+
647
+ if i in self.self_condition_layers:
648
+ assert isinstance(ctc_decoder, nn.Module), "A CTC decoder must be passed in for self conditioning"
649
+ # Apply CTC decoder to the output of this layer
650
+ ctc_logits = ctc_decoder(hidden_states.transpose(0, 1))
651
+ ctc_outputs = ctc_outputs + (ctc_logits,)
652
+
653
+ ctc_probs = self.conditioning_softmax(ctc_logits)
654
+ conditioning_embedding = self.conditioning_layer(ctc_probs).transpose(0, 1) #[T, B, C]
655
+
656
+ hidden_states = hidden_states + conditioning_embedding # Additive conditioning residual
657
+
658
+ hidden_states = hidden_states.transpose(0, 1) # [B,T,C]
659
+
660
+ if self.self_condition_layers:
661
+ all_hidden_states = all_hidden_states + ctc_outputs
662
+
663
+ if not return_dict:
664
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
665
+ return BaseModelOutput(
666
+ last_hidden_state=hidden_states,
667
+ hidden_states=all_hidden_states,
668
+ attentions=all_self_attentions,
669
+ )
670
+
671
+
672
+ class MeralionBestRqModel(PreTrainedModel):
673
+ """
674
+ The core BEST-RQ Conformer model. This model is a `PreTrainedModel` that takes the raw mel-spectrogram features
675
+ and outputs the final encoder hidden states.
676
+
677
+ This model inherits from [`PreTrainedModel`]. For the available methods and functionalities, see the
678
+ documentation in [`PreTrainedModel`].
679
+
680
+ Args:
681
+ config ([`MeralionBestRqConformerConfig`]):
682
+ Model configuration class with all the parameters of the model.
683
+ Initializing with a config file does not load the weights associated with the model, only the
684
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
685
+ """
686
+ config_class = MeralionBestRqConformerConfig
687
+ base_model_prefix = "bestrq_encoder"
688
+
689
+ def __init__(self, config: MeralionBestRqConformerConfig):
690
+ super().__init__(config)
691
+ self.config = config
692
+ self.conv_subsample = Conv2dSubsampling(config)
693
+
694
+ self.encoder = ConformerEncoder(config)
695
+
696
+ # Initialize weights and apply final processing
697
+ self.post_init()
698
+
699
+ def forward(
700
+ self,
701
+ input_values: Optional[torch.Tensor], # [B,C,T]
702
+ attention_mask: Optional[torch.Tensor] = None,
703
+ mask_time_indices: Optional[torch.FloatTensor] = None,
704
+ output_attentions: Optional[bool] = None,
705
+ output_hidden_states: Optional[bool] = None,
706
+ return_dict: Optional[bool] = None,
707
+ input_lengths: Optional[torch.Tensor] = None,
708
+ ctc_decoder: Optional[nn.Module] = None,
709
+ ) -> Union[Tuple, Wav2Vec2BaseModelOutput]:
710
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
711
+ output_hidden_states = (
712
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
713
+ )
714
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
715
+
716
+ input_values = input_values.transpose(2, 1) # [B,C,T] -> [B,T,C]
717
+ conv_outputs, output_lengths = self.conv_subsample(input_values, input_lengths) # returns [B,T,C]
718
+ x = conv_outputs.transpose(0, 1) # [T,B,C]
719
+
720
+ encoder_padding_mask = make_pad_mask(output_lengths, max_len=x.shape[0])
721
+
722
+ encoder_outputs = self.encoder(
723
+ x,
724
+ attention_mask=encoder_padding_mask,
725
+ output_attentions=output_attentions,
726
+ output_hidden_states=output_hidden_states,
727
+ return_dict=return_dict,
728
+ ctc_decoder=ctc_decoder,
729
+ )
730
+
731
+ hidden_states = encoder_outputs[0]
732
+
733
+ if not return_dict:
734
+ return (hidden_states, conv_outputs) + encoder_outputs[1:]
735
+
736
+ output = Wav2Vec2BaseModelOutput(
737
+ last_hidden_state=hidden_states,
738
+ extract_features=conv_outputs,
739
+ hidden_states=encoder_outputs.hidden_states,
740
+ attentions=encoder_outputs.attentions,
741
+ )
742
+ output["output_lengths"] = output_lengths
743
+ return output
744
+
745
+
746
+ class MeralionBestRqModelForCTC(PreTrainedModel):
747
+ """
748
+ BEST-RQ Conformer model with a CTC head on top for Connectionist Temporal Classification. This model can
749
+ also use a weighted sum of the encoder's hidden states.
750
+
751
+ This model inherits from [`PreTrainedModel`]. For the available methods and functionalities, see the
752
+ documentation in [`PreTrainedModel`].
753
+
754
+ Args:
755
+ config ([`MeralionBestRqConformerConfig`]):
756
+ Model configuration class with all the parameters of the model.
757
+ Initializing with a config file does not load the weights associated with the model, only the
758
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
759
+ """
760
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.__init__ with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer
761
+ config_class = MeralionBestRqConformerConfig
762
+ base_model_prefix = "bestrq_encoder"
763
+
764
+ def __init__(self, config, target_lang: Optional[str] = None, **kwargs):
765
+ super().__init__(config)
766
+
767
+ self.bestrq_encoder = MeralionBestRqModel(config)
768
+ self.dropout = nn.Dropout(config.final_dropout)
769
+
770
+ self.target_lang = target_lang
771
+
772
+ if self.config.use_weighted_sum:
773
+ self.weights = nn.Parameter(torch.zeros(self.config.num_hidden_layers))
774
+ self.softmax = nn.Softmax(dim=-1)
775
+
776
+ if config.vocab_size is None:
777
+ raise ValueError(
778
+ f"You are trying to instantiate {self.__class__} with a configuration that "
779
+ "does not define the vocabulary size of the language model head. Please "
780
+ "instantiate the model as follows: `MeralionBestRqModelForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
781
+ "or define `vocab_size` of your model's configuration."
782
+ )
783
+ output_hidden_size = (
784
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
785
+ )
786
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
787
+
788
+ # Initialize weights and apply final processing
789
+ self.post_init()
790
+
791
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.forward with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer
792
+ def forward(
793
+ self,
794
+ input_values: Optional[torch.Tensor],
795
+ attention_mask: Optional[torch.Tensor] = None,
796
+ output_attentions: Optional[bool] = None,
797
+ output_hidden_states: Optional[bool] = None,
798
+ return_dict: Optional[bool] = None,
799
+ input_lengths: Optional[torch.Tensor] = None,
800
+ labels: Optional[torch.Tensor] = None,
801
+ ) -> Union[Tuple, CausalLMOutput]:
802
+ r"""
803
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
804
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
805
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
806
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
807
+ config.vocab_size - 1]`.
808
+ """
809
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
810
+
811
+ if labels is not None and labels.max() >= self.config.vocab_size:
812
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
813
+
814
+ outputs = self.bestrq_encoder(
815
+ input_values,
816
+ output_attentions=output_attentions,
817
+ output_hidden_states=output_hidden_states,
818
+ return_dict=return_dict,
819
+ input_lengths=input_lengths
820
+ )
821
+
822
+ if self.config.use_weighted_sum:
823
+ assert output_hidden_states is True, "output_hidden_states must be True when using use_weighted_sum"
824
+ # Skip the first hidden state as that is collected before the first encoder layer forward
825
+ hidden_states = outputs.hidden_states[1:self.config.num_hidden_layers+1]
826
+ hidden_states = self._weighted_sum(hidden_states)
827
+ else:
828
+ hidden_states = outputs.last_hidden_state
829
+
830
+ hidden_states = self.dropout(hidden_states)
831
+
832
+ logits = self.lm_head(hidden_states)
833
+
834
+ loss = None
835
+ if labels is not None:
836
+ # assuming that padded tokens are filled with -100
837
+ # when not being attended to
838
+ labels_mask = labels >= 0
839
+ target_lengths = labels_mask.sum(-1)
840
+ flattened_targets = labels.masked_select(labels_mask)
841
+
842
+ # ctc_loss doesn't support fp16
843
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
844
+
845
+ with torch.backends.cudnn.flags(enabled=False):
846
+ loss = nn.functional.ctc_loss(
847
+ log_probs,
848
+ flattened_targets,
849
+ outputs.output_lengths, #lengths after initial CNN downsampling
850
+ target_lengths,
851
+ blank=self.config.pad_token_id,
852
+ reduction=self.config.ctc_loss_reduction,
853
+ zero_infinity=self.config.ctc_zero_infinity,
854
+ )
855
+
856
+ if not return_dict:
857
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
858
+ return ((loss,) + output) if loss is not None else output
859
+
860
+ return CausalLMOutput(
861
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
862
+ )
863
+
864
+ class LSTMCTCHead(nn.Module):
865
+ """
866
+ A CTC head that includes LSTM layers before the final projection. This is used for the
867
+ `MeralionBestRqModelForLSTMCTC` model.
868
+ """
869
+ def __init__(self, config):
870
+ super().__init__()
871
+ output_hidden_size = (
872
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
873
+ )
874
+ self.lstm = nn.LSTM(
875
+ output_hidden_size,
876
+ config.lstm_dim,
877
+ num_layers=config.lstm_num_layers,
878
+ dropout=config.lstm_dropout_prob,
879
+ batch_first=True,
880
+ bidirectional=True,
881
+ )
882
+ self.lm_head = nn.Linear(config.lstm_dim * 2, config.vocab_size)
883
+
884
+ def forward(self, hidden_states):
885
+ hidden_states, _ = self.lstm(hidden_states)
886
+ logits = self.lm_head(hidden_states)
887
+ return logits
888
+
889
+ def _weighted_sum(self, embeddings, normalize=False):
890
+ assert isinstance(embeddings, list) or isinstance(embeddings, tuple)
891
+ assert len(embeddings) == self.config.num_hidden_layers, f"Number of embeddings: {len(embeddings)} does not match number of layers: {self.config.num_hidden_layers}"
892
+ stacked_hs = torch.stack(embeddings, dim=0)
893
+
894
+ if normalize:
895
+ stacked_hs = nn.functional.layer_norm(stacked_hs, (stacked_hs.shape[-1],))
896
+
897
+ _, *origin_shape = stacked_hs.shape
898
+ stacked_hs = stacked_hs.view(self.config.num_hidden_layers, -1)
899
+ norm_weights = self.softmax(self.weights)
900
+ weighted_hs = (norm_weights.unsqueeze(-1) * stacked_hs).sum(dim=0)
901
+ weighted_hs = weighted_hs.view(*origin_shape)
902
+
903
+ return weighted_hs
904
+
905
+
906
+ class MeralionBestRqModelForLSTMCTC(PreTrainedModel):
907
+ """
908
+ BEST-RQ Conformer model with an LSTM-CTC head on top for Connectionist Temporal Classification. This model can
909
+ also use a weighted sum of the encoder's hidden states.
910
+
911
+ This model inherits from [`PreTrainedModel`]. For the available methods and functionalities, see the
912
+ documentation in [`PreTrainedModel`].
913
+
914
+ Args:
915
+ config ([`MeralionBestRqConformerConfig`]):
916
+ Model configuration class with all the parameters of the model.
917
+ Initializing with a config file does not load the weights associated with the model, only the
918
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
919
+ """
920
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.__init__ with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer
921
+ config_class = MeralionBestRqConformerConfig
922
+ base_model_prefix = "bestrq_encoder"
923
+
924
+ def __init__(self, config, target_lang: Optional[str] = None, **kwargs):
925
+ super().__init__(config)
926
+ self.config = config
927
+
928
+ self.bestrq_encoder = MeralionBestRqModel(config)
929
+ self.dropout = nn.Dropout(config.final_dropout)
930
+
931
+ self.target_lang = target_lang
932
+
933
+ if config.vocab_size is None:
934
+ raise ValueError(
935
+ f"You are trying to instantiate {self.__class__} with a configuration that "
936
+ "does not define the vocabulary size of the language model head. Please "
937
+ "instantiate the model as follows: `MeralionBestRqModelForLSTMCTC.from_pretrained(..., vocab_size=vocab_size)`. "
938
+ "or define `vocab_size` of your model's configuration."
939
+ )
940
+
941
+ if self.config.use_weighted_sum:
942
+ self.weights = nn.Parameter(torch.zeros(self.config.num_hidden_layers))
943
+ self.softmax = nn.Softmax(dim=-1)
944
+
945
+ self.lstm_ctc_decoder = LSTMCTCHead(config)
946
+
947
+ # Initialize weights and apply final processing
948
+ self.post_init()
949
+
950
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.forward with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer
951
+ def forward(
952
+ self,
953
+ input_values: Optional[torch.Tensor],
954
+ attention_mask: Optional[torch.Tensor] = None,
955
+ output_attentions: Optional[bool] = None,
956
+ output_hidden_states: Optional[bool] = True,
957
+ return_dict: Optional[bool] = None,
958
+ input_lengths: Optional[torch.Tensor] = None,
959
+ labels: Optional[torch.Tensor] = None,
960
+
961
+ ) -> Union[Tuple, CausalLMOutput]:
962
+ r"""
963
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
964
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
965
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
966
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
967
+ config.vocab_size - 1]`.
968
+ """
969
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
970
+
971
+ if labels is not None and labels.max() >= self.config.vocab_size:
972
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
973
+
974
+ outputs = self.bestrq_encoder(
975
+ input_values,
976
+ output_attentions=output_attentions,
977
+ output_hidden_states=output_hidden_states,
978
+ return_dict=return_dict,
979
+ input_lengths=input_lengths,
980
+ ctc_decoder=self.lstm_ctc_decoder,
981
+ )
982
+
983
+ if self.config.use_weighted_sum:
984
+ assert output_hidden_states is True, "output_hidden_states must be True when using use_weighted_sum"
985
+ # Skip the first hidden state as that is collected before the first encoder layer forward
986
+ hidden_states = outputs.hidden_states[1:self.config.num_hidden_layers+1]
987
+ hidden_states = self._weighted_sum(hidden_states)
988
+ else:
989
+ hidden_states = outputs.last_hidden_state
990
+
991
+ hidden_states = self.dropout(hidden_states)
992
+ logits = self.lstm_ctc_decoder(hidden_states)
993
+
994
+ loss = None
995
+ if labels is not None:
996
+ # assuming that padded tokens are filled with -100
997
+ # when not being attended to
998
+ labels_mask = labels >= 0
999
+ target_lengths = labels_mask.sum(-1)
1000
+ flattened_targets = labels.masked_select(labels_mask)
1001
+
1002
+ # ctc_loss doesn't support fp16
1003
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1004
+
1005
+ with torch.backends.cudnn.flags(enabled=False):
1006
+ loss = nn.functional.ctc_loss(
1007
+ log_probs,
1008
+ flattened_targets,
1009
+ outputs.output_lengths, #lengths after initial CNN downsampling
1010
+ target_lengths,
1011
+ reduction=self.config.ctc_loss_reduction,
1012
+ zero_infinity=self.config.ctc_zero_infinity,
1013
+ )
1014
+
1015
+ if not return_dict:
1016
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1017
+ return ((loss,) + output) if loss is not None else output
1018
+
1019
+ return CausalLMOutput(
1020
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1021
+ )
1022
+
1023
+ def _weighted_sum(self, embeddings, normalize=False):
1024
+ assert isinstance(embeddings, list) or isinstance(embeddings, tuple)
1025
+ assert len(embeddings) == self.config.num_hidden_layers, f"Number of embeddings: {len(embeddings)} does not match number of layers: {self.config.num_hidden_layers}"
1026
+ stacked_hs = torch.stack(embeddings, dim=0)
1027
+
1028
+ if normalize:
1029
+ stacked_hs = nn.functional.layer_norm(stacked_hs, (stacked_hs.shape[-1],))
1030
+
1031
+ _, *origin_shape = stacked_hs.shape
1032
+ stacked_hs = stacked_hs.view(self.config.num_hidden_layers, -1)
1033
+ norm_weights = self.softmax(self.weights)
1034
+ weighted_hs = (norm_weights.unsqueeze(-1) * stacked_hs).sum(dim=0)
1035
+ weighted_hs = weighted_hs.view(*origin_shape)
1036
+
1037
+ return weighted_hs