johntsi commited on
Commit
7656b04
1 Parent(s): a046824

Initial commit

Browse files
Files changed (3) hide show
  1. config.json +27 -0
  2. model.py +366 -0
  3. model.safetensors +3 -0
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "johntsi/ZeroSwot-Medium_asr-cv_en-to-200/model.safetensors",
3
+ "architectures": [
4
+ "ZeroSwotEncoderModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "model.ZeroSwotEncoderConfig",
8
+ "AutoModel": "model.ZeroSwotEncoderModel"
9
+ },
10
+ "compression_adapter": {
11
+ "blank_idx": 0,
12
+ "dropout": 0.1,
13
+ "embed_dim": 1024,
14
+ "sep_idx": 4,
15
+ "transformer_layers": 3
16
+ },
17
+ "embed_dim": 1024,
18
+ "model_type": "zero_swot_encoder",
19
+ "nllb_model_name_or_path": "facebook/nllb-200-distilled-600M",
20
+ "speech_embedder": {
21
+ "nllb_eng_id": 256047,
22
+ "nllb_eos_id": 2
23
+ },
24
+ "torch_dtype": "float32",
25
+ "transformers_version": "4.41.2",
26
+ "wav2vec2_model_name_or_path": "facebook/wav2vec2-large-960h-lv60-self"
27
+ }
model.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel, PretrainedConfig, Wav2Vec2ForCTC
2
+ import json
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn.utils.rnn import pad_sequence
6
+ import math
7
+ from typing import Optional
8
+
9
+ # x: torch.FloatTensor [T, B, D]
10
+ # mask: torch.BoolTensor [B, T], where True indicates padding
11
+ # returns: torch.LongTensor [B]
12
+ def get_lengths(x, mask=None):
13
+ if mask is not None:
14
+ return (~mask).long().sum(dim=1)
15
+ else:
16
+ return torch.LongTensor([x.size(0)] * x.size(1)).to(x.device)
17
+
18
+ # lens: torch.LongTensor [B]
19
+ # returns: torch.BoolTensor [B, max_lens], where True indicates padding
20
+ def lengths_to_padding_mask(lens):
21
+ bsz, max_lens = lens.size(0), torch.max(lens).item()
22
+ mask = torch.arange(max_lens).to(lens.device).view(1, max_lens)
23
+ mask = mask.expand(bsz, -1) >= lens.view(bsz, 1).expand(-1, max_lens)
24
+ return mask
25
+
26
+ # input_lengths: torch.LongTensor [B]
27
+ def get_output_lengths(input_lengths):
28
+ conv_feature_layers = "[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]"
29
+ conv_cfg_list = eval(conv_feature_layers)
30
+
31
+ def _conv_out_length(input_length, kernel_size, stride):
32
+ return torch.floor((input_length - kernel_size) / stride + 1)
33
+
34
+ for i in range(len(conv_cfg_list)):
35
+ input_lengths = _conv_out_length(
36
+ input_lengths, conv_cfg_list[i][1], conv_cfg_list[i][2]
37
+ )
38
+
39
+ return input_lengths.to(torch.long)
40
+
41
+ class ZeroSwotEncoderConfig(PretrainedConfig):
42
+ model_type = "zero_swot_encoder"
43
+ def __init__(
44
+ self,
45
+ wav2vec2_model_name_or_path="",
46
+ compression_adapter=None,
47
+ embed_dim=1024,
48
+ **kwargs
49
+ ):
50
+ super().__init__(**kwargs)
51
+ self.wav2vec2_model_name_or_path = wav2vec2_model_name_or_path
52
+ self.compression_adapter = compression_adapter
53
+ self.embed_dim = embed_dim
54
+
55
+ @classmethod
56
+ def from_json_file(cls, json_file):
57
+ with open(json_file, "r") as reader:
58
+ text = reader.read()
59
+ config_dict = json.loads(text)
60
+ return cls(**config_dict)
61
+
62
+ class ZeroSwotEncoderModel(PreTrainedModel):
63
+ config_class = ZeroSwotEncoderConfig
64
+ model_type = "zero_swot_encoder"
65
+
66
+ def __init__(self, config):
67
+ super().__init__(config)
68
+
69
+ self.wav2vec2 = Wav2Vec2ForCTC.from_pretrained(config.wav2vec2_model_name_or_path)
70
+ self.compression_adapter = CompressionAdapter(config.compression_adapter)
71
+ self.speech_embedder = SpeechEmbedder(config.embed_dim)
72
+
73
+ def forward(self, input_values, attention_mask=None):
74
+ input_lens = get_lengths(input_values, ~attention_mask)
75
+
76
+ # Forward pass through wav2vec2 encoder
77
+ x = self.wav2vec2.wav2vec2(input_values, attention_mask)[0] # [B, T, D]
78
+ # CTC predictions
79
+ preds = self.wav2vec2.lm_head(x).argmax(-1) # [B, T]
80
+ # Get output lengths for x
81
+ output_lens = get_output_lengths(input_lens)
82
+
83
+ # Compression
84
+ x, mask, _ = self.compression_adapter(x, preds, output_lens) # [B, N, D] with N << T
85
+
86
+ # BOS and EOS embeddings
87
+ x, mask = self.speech_embedder(x, mask) # [B, N+2, D]
88
+
89
+ return x, mask
90
+
91
+
92
+ class SpeechEmbedder(nn.Module):
93
+ def __init__(self, embed_dim):
94
+ super().__init__()
95
+
96
+ self.embed_dim = embed_dim
97
+ self.bos_emb = nn.Parameter(torch.empty(embed_dim))
98
+ self.eos_emb = nn.Parameter(torch.empty(embed_dim))
99
+
100
+ self.scale = self.embed_dim ** 0.5
101
+
102
+ def forward(self, x, padding_mask=None):
103
+ """Add special embedding and positional embedding.
104
+ Args:
105
+ x (FloatTensor): (B, T, C)
106
+ padding_mask (ByteTensor): (B, T)
107
+ Outputs:
108
+ x (FloatTensor): (B, T+2, C)
109
+ padding_mask (ByteTensor): (B, T+2)
110
+ """
111
+ B = x.size(0)
112
+ lengths = get_lengths(x.transpose(0, 1), padding_mask)
113
+ assert B == len(lengths)
114
+
115
+ if padding_mask is not None:
116
+ x = x * (1 - padding_mask.unsqueeze(-1).type_as(x))
117
+
118
+ # prepend bos
119
+ x = torch.cat([self.bos_emb.view(1, 1, -1).expand(B, 1, -1), x], dim=1)
120
+ lengths += 1
121
+
122
+ # append padding (zeros) and then convert first padding to eos
123
+ x = torch.cat([x, torch.zeros(B, 1, x.size(-1), device=x.device, dtype=x.dtype)], dim=1)
124
+ for i in range(B):
125
+ x[i, lengths[i], :] = self.eos_emb
126
+ lengths += 1
127
+
128
+ padding_mask = lengths_to_padding_mask(lengths)
129
+
130
+ x = x * self.scale
131
+
132
+ return x, padding_mask
133
+
134
+
135
+ class PositionalEmbedding(nn.Module):
136
+ def __init__(self, num_embeddings, embedding_dim, padding_idx):
137
+ super().__init__()
138
+ self.embedding_dim = embedding_dim
139
+ self.padding_idx = padding_idx if padding_idx is not None else 0
140
+ num_embeddings += padding_idx + 1
141
+ self.weights = PositionalEmbedding.get_embedding(
142
+ num_embeddings, embedding_dim, padding_idx
143
+ )
144
+ self.register_buffer("_float_tensor", torch.FloatTensor(1))
145
+ self.max_positions = int(1e5)
146
+
147
+ @staticmethod
148
+ def get_embedding(
149
+ num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None
150
+ ):
151
+ half_dim = embedding_dim // 2
152
+ emb = math.log(10000) / (half_dim - 1)
153
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
154
+ emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
155
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
156
+ if embedding_dim % 2 == 1:
157
+ # zero pad
158
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
159
+ if padding_idx is not None:
160
+ emb[padding_idx, :] = 0
161
+ return emb
162
+
163
+ def make_positions(self, x, padding_idx: int):
164
+ mask = x.ne(padding_idx).int()
165
+ return (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + padding_idx
166
+
167
+ def forward(self, input):
168
+ """Input is expected to be of size [bsz x seqlen]."""
169
+ bsz, seq_len = input.size()
170
+ max_pos = self.padding_idx + 1 + seq_len
171
+ if self.weights is None or max_pos > self.weights.size(0):
172
+ # recompute/expand embeddings if needed
173
+ self.weights = PositionalEmbedding.get_embedding(
174
+ max_pos, self.embedding_dim, self.padding_idx
175
+ )
176
+ self.weights = self.weights.to(self._float_tensor)
177
+ positions = self.make_positions(input, self.padding_idx)
178
+ return (
179
+ self.weights.index_select(0, positions.view(-1))
180
+ .view(bsz, seq_len, -1)
181
+ .detach()
182
+ )
183
+
184
+
185
+ class CLSPooling(nn.Module):
186
+ def __init__(self, embed_dim, num_transformer_layers, dropout_rate):
187
+ super().__init__()
188
+
189
+ self.cls_token = nn.Parameter(torch.empty(1, 1, embed_dim))
190
+ nn.init.normal_(self.cls_token, mean=0.0, std=0.25)
191
+
192
+ self.transformer = nn.TransformerEncoder(
193
+ nn.TransformerEncoderLayer(
194
+ embed_dim,
195
+ nhead=16 if embed_dim == 1024 else 8,
196
+ dim_feedforward=4*embed_dim,
197
+ dropout=dropout_rate,
198
+ activation="relu",
199
+ batch_first=True,
200
+ norm_first=True
201
+ ),
202
+ num_layers=num_transformer_layers,
203
+ )
204
+
205
+ self.pos_emb = PositionalEmbedding(512, embed_dim, 1)
206
+ self.scale = math.sqrt(embed_dim)
207
+
208
+ def forward(self, x, lens):
209
+ # x: [B, N, D]
210
+ # lens: [B]
211
+
212
+ # prepend cls token
213
+ x = torch.cat(
214
+ [
215
+ self.cls_token.to(dtype=x.dtype, device=x.device).repeat(x.size(0), 1, 1), # B x 1 x D
216
+ x
217
+ ],
218
+ dim=1) # [B, N+1, D]
219
+
220
+ mask = lengths_to_padding_mask(lens+1)
221
+
222
+ x = x + self.pos_emb(mask.long()) / self.scale
223
+
224
+ x = self.transformer(x, src_key_padding_mask=mask) # [B, N+1, D]
225
+ x = x[:, 0] # [B, D]
226
+ return x
227
+
228
+
229
+ class CompressionAdapter(nn.Module):
230
+ def __init__(self, cfg):
231
+ super().__init__()
232
+ self.embed_dim = cfg["embed_dim"]
233
+ self.transformer_layers = cfg["transformer_layers"]
234
+ self.dropout = cfg["dropout"]
235
+ self.blank_idx = cfg["blank_idx"]
236
+ self.sep_idx = cfg["sep_idx"]
237
+
238
+ self.token_pooling_module = CLSPooling(
239
+ self.embed_dim, self.transformer_layers, self.dropout
240
+ )
241
+
242
+ def char_compression(self, x, preds, lens):
243
+ # x: B x T x D
244
+ # preds: B x T
245
+ # lens: B
246
+
247
+ B, T, D = x.size()
248
+ device = x.device
249
+ dtype = x.dtype
250
+
251
+ # zero-out the padding
252
+ mask = lengths_to_padding_mask(lens) # B x T
253
+ x = x.masked_fill(mask.unsqueeze(-1), 0)
254
+ preds = preds.masked_fill(mask, self.blank_idx)
255
+
256
+ # add a vector of -1 to know where each example ends after flattening the batch
257
+ preds = torch.cat([-torch.ones(B, 1, device=device, dtype=torch.long), preds], dim=1).view(-1)
258
+ x = torch.cat([torch.zeros(B, 1, D, device=device, dtype=dtype), x], dim=1).view(-1, D)
259
+
260
+ # get points of consecutive preds
261
+ preds, counts = preds.unique_consecutive(return_counts=True)
262
+
263
+ # split in representations of same chars
264
+ x = torch.split(x, counts.tolist())
265
+
266
+ # remove blanks
267
+ valid_mask = preds != self.blank_idx
268
+ preds = preds[valid_mask]
269
+ counts = counts[valid_mask] # [N]
270
+ x = [x_i for x_i, v_i in zip(x, valid_mask) if v_i]
271
+
272
+ # pack into tensor
273
+ x = pad_sequence(x, batch_first=True, padding_value=0)
274
+
275
+ # char pooling
276
+ x = torch.sum(x, dim=1) / counts.to(dtype=x.dtype).unsqueeze(1) # [B, N, D] -> [B, D]
277
+
278
+ # find split points for retrieving the examples
279
+ split_points = (preds == -1).nonzero(as_tuple=True)[0]
280
+ split_points = torch.cat([split_points, torch.tensor([len(preds)], device=device)])
281
+ split_points = (split_points[1:] - split_points[:-1]).tolist()
282
+
283
+ # split into examples
284
+ x = torch.split(x, split_points)
285
+ preds = torch.split(preds, split_points)
286
+ lens = torch.tensor([len(x_i) for x_i in x], device=device)
287
+
288
+ # pack into tensors
289
+ x = pad_sequence(x, batch_first=True, padding_value=0)
290
+ preds = pad_sequence(preds, batch_first=True, padding_value=self.blank_idx)
291
+
292
+ # remove the parts we add to identify the bounds for each example
293
+ x = x[:, 1:]
294
+ preds = preds[:, 1:]
295
+ lens -= 1
296
+
297
+ mask = lengths_to_padding_mask(lens)
298
+
299
+ # account for empty examples (just a sep token)
300
+ empty_examples = lens == 0
301
+ num_empty_examples = empty_examples.sum()
302
+ if num_empty_examples > 0:
303
+ mask[empty_examples, 0] = True
304
+ lens[empty_examples] = 1
305
+ preds[empty_examples, 0] = self.sep_idx
306
+
307
+ return x, mask, lens, preds, num_empty_examples
308
+
309
+ def token_compression(self, x, preds, lens):
310
+ # x: B x T x D
311
+ # preds: B x T
312
+ # lens: B
313
+
314
+ B, T, D = x.size()
315
+ device = x.device
316
+ dtype = x.dtype
317
+
318
+ # new lengths after compression
319
+ new_lens = preds.eq(self.sep_idx).sum(dim=1)
320
+
321
+ # unpad and unpack to list of tensors
322
+ preds = [preds[i, :lens[i]] for i in range(B)]
323
+ x = [x[i, :lens[i]] for i in range(B)]
324
+
325
+ # make sure every example ends with a separator
326
+ num_examples_without_ending_sep = torch.tensor(0, device=device, dtype=torch.long)
327
+ for i in range(B):
328
+ if preds[i][-1] != self.sep_idx:
329
+ preds[i] = torch.cat([preds[i], torch.tensor([self.sep_idx], device=device, dtype=torch.long)])
330
+ x[i] = torch.cat([x[i], torch.zeros(1, D, device=device, dtype=dtype)])
331
+ new_lens[i] += 1
332
+ num_examples_without_ending_sep += 1
333
+
334
+ # flatten
335
+ preds = torch.cat(preds)
336
+ x = torch.cat(x)
337
+
338
+ # split points according to separators
339
+ split_points = preds.eq(self.sep_idx).nonzero(as_tuple=True)[0] + 1
340
+ split_points = torch.cat([torch.tensor([0], device=device, dtype=torch.long), split_points])
341
+ split_points = (split_points[1:] - split_points[:-1]).tolist()
342
+
343
+ # re-arrange in 3d [total_num_tokens x max(count) x D]
344
+ x = torch.split(x, split_points) # Tuple[2d tensor]
345
+
346
+ counts = torch.tensor([len(x_i) for x_i in x], device=device, dtype=torch.long)
347
+ x = pad_sequence(x, batch_first=True, padding_value=0)
348
+
349
+ # reduce dim 1
350
+ x = self.token_pooling_module(x, counts)
351
+
352
+ # reconstruct the batch
353
+ split_points = new_lens.cumsum(dim=0)
354
+ split_points = torch.cat([torch.tensor([0], device=device, dtype=torch.long), split_points])
355
+ split_points = (split_points[1:] - split_points[:-1]).tolist()
356
+ x = torch.split(x, split_points)
357
+ x = pad_sequence(x, batch_first=True, padding_value=0) # B x ? x D
358
+
359
+ mask = lengths_to_padding_mask(new_lens)
360
+
361
+ return x, mask, new_lens, num_examples_without_ending_sep
362
+
363
+ def forward(self, x, preds, lens):
364
+ x, mask, lens, preds, _ = self.char_compression(x, preds, lens)
365
+ x, mask, lens, _ = self.token_compression(x, preds, lens)
366
+ return x, mask, lens
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6792b4306ac0fd8b69d96937da34fb88c6543983768bc77d8954ca13dd71169a
3
+ size 1413115412