Automatic Speech Recognition
Transformers
Safetensors
English
msp
Generated from Trainer
custom_code
MahmoodAnaam commited on
Commit
8b7a132
·
verified ·
1 Parent(s): 031059a

Upload MSPForCTC

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MSPForCTC"
4
+ ],
5
+ "audio_config": {
6
+ "_name_or_path": "MahmoodAnaam/MSP-ASR",
7
+ "activation_dropout": 0.1,
8
+ "adapter_attn_dim": null,
9
+ "adapter_kernel_size": 3,
10
+ "adapter_stride": 2,
11
+ "add_adapter": false,
12
+ "apply_spec_augment": true,
13
+ "architectures": [
14
+ "MSPAudioForCTC"
15
+ ],
16
+ "attention_dropout": 0.1,
17
+ "auto_map": {
18
+ "AutoConfig": "configuration_msp_audio.MSPAudioConfig",
19
+ "AutoModelForCTC": "modeling_msp_audio.MSPAudioForCTC"
20
+ },
21
+ "bos_token_id": 1,
22
+ "classifier_proj_size": 256,
23
+ "codevector_dim": 768,
24
+ "contrastive_logits_temperature": 0.1,
25
+ "conv_bias": true,
26
+ "conv_dim": [
27
+ 512,
28
+ 512,
29
+ 512,
30
+ 512,
31
+ 512,
32
+ 512,
33
+ 512
34
+ ],
35
+ "conv_kernel": [
36
+ 10,
37
+ 3,
38
+ 3,
39
+ 3,
40
+ 3,
41
+ 2,
42
+ 2
43
+ ],
44
+ "conv_stride": [
45
+ 5,
46
+ 2,
47
+ 2,
48
+ 2,
49
+ 2,
50
+ 2,
51
+ 2
52
+ ],
53
+ "ctc_loss_reduction": "mean",
54
+ "ctc_zero_infinity": true,
55
+ "diversity_loss_weight": 0.1,
56
+ "do_stable_layer_norm": true,
57
+ "dtype": "float32",
58
+ "eos_token_id": 2,
59
+ "feat_extract_activation": "gelu",
60
+ "feat_extract_dropout": 0.0,
61
+ "feat_extract_norm": "layer",
62
+ "feat_proj_dropout": 0.1,
63
+ "feat_quantizer_dropout": 0.0,
64
+ "final_dropout": 0.1,
65
+ "gradient_checkpointing": false,
66
+ "hidden_act": "gelu",
67
+ "hidden_dropout": 0.1,
68
+ "hidden_dropout_prob": 0.1,
69
+ "hidden_size": 1024,
70
+ "initializer_range": 0.02,
71
+ "intermediate_size": 4096,
72
+ "layer_norm_eps": 1e-05,
73
+ "layerdrop": 0.1,
74
+ "mask_feature_length": 10,
75
+ "mask_feature_min_masks": 0,
76
+ "mask_feature_prob": 0.0,
77
+ "mask_time_length": 10,
78
+ "mask_time_min_masks": 2,
79
+ "mask_time_prob": 0.05,
80
+ "model_type": "msp_audio",
81
+ "num_adapter_layers": 3,
82
+ "num_attention_heads": 16,
83
+ "num_codevector_groups": 2,
84
+ "num_codevectors_per_group": 320,
85
+ "num_conv_pos_embedding_groups": 16,
86
+ "num_conv_pos_embeddings": 128,
87
+ "num_feat_extract_layers": 7,
88
+ "num_hidden_layers": 24,
89
+ "num_negatives": 100,
90
+ "output_hidden_size": 1024,
91
+ "pad_token_id": 0,
92
+ "proj_codevector_dim": 768,
93
+ "tdnn_dilation": [
94
+ 1,
95
+ 2,
96
+ 3,
97
+ 1,
98
+ 1
99
+ ],
100
+ "tdnn_dim": [
101
+ 512,
102
+ 512,
103
+ 512,
104
+ 512,
105
+ 1500
106
+ ],
107
+ "tdnn_kernel": [
108
+ 5,
109
+ 3,
110
+ 3,
111
+ 1,
112
+ 1
113
+ ],
114
+ "use_weighted_layer_sum": false,
115
+ "vocab_size": 32,
116
+ "xvector_output_dim": 512
117
+ },
118
+ "auto_map": {
119
+ "AutoConfig": "configuration_msp.MSPConfig",
120
+ "AutoModelForCTC": "modeling_msp.MSPForCTC"
121
+ },
122
+ "bos_token_id": 1,
123
+ "ctc_loss_audio_weight": 0.5,
124
+ "ctc_loss_msp_weight": 1.0,
125
+ "ctc_loss_reduction": "mean",
126
+ "ctc_loss_visual_weight": 0.5,
127
+ "ctc_zero_infinity": true,
128
+ "dtype": "float32",
129
+ "eos_token_id": 2,
130
+ "final_dropout": 0.1,
131
+ "fusion_activation_dropout": 0.1,
132
+ "fusion_attention_dropout": 0.1,
133
+ "fusion_hidden_act": "gelu",
134
+ "fusion_hidden_dropout": 0.1,
135
+ "fusion_hidden_size": 768,
136
+ "fusion_intermediate_size": 3072,
137
+ "fusion_layer_norm_eps": 1e-05,
138
+ "fusion_num_attention_heads": 12,
139
+ "initializer_range": 0.02,
140
+ "model_type": "msp",
141
+ "pad_token_id": 0,
142
+ "transformers_version": "5.13.1",
143
+ "visual_config": {
144
+ "_name_or_path": "MahmoodAnaam/MSP-VSR",
145
+ "architectures": [
146
+ "MSPVisualForCTC"
147
+ ],
148
+ "auto_map": {
149
+ "AutoConfig": "configuration_msp_visual.MSPVisualConfig",
150
+ "AutoModelForCTC": "modeling_msp_visual.MSPVisualForCTC"
151
+ },
152
+ "bos_token_id": 1,
153
+ "ctc_loss_reduction": "mean",
154
+ "ctc_zero_infinity": true,
155
+ "dtype": "float32",
156
+ "eos_token_id": 2,
157
+ "final_dropout": 0.1,
158
+ "model_type": "msp_visual",
159
+ "pad_token_id": 0,
160
+ "visual_config": {
161
+ "_name_or_path": "MahmoodAnaam/avhubert_encoder_large_noise_pt_noise_ft_433h",
162
+ "a_upsample_ratio": 1,
163
+ "activation_dropout": 0.0,
164
+ "activation_function": "relu",
165
+ "adapter_attn_dim": null,
166
+ "adapter_kernel_size": 3,
167
+ "adapter_stride": 2,
168
+ "add_adapter": false,
169
+ "adim": 1024,
170
+ "aheads": 12,
171
+ "apply_spec_augment": true,
172
+ "architectures": [
173
+ "AVHubertModel"
174
+ ],
175
+ "attention_dropout": 0.1,
176
+ "audio_dropout": 0.5,
177
+ "audio_feat_dim": 104,
178
+ "auto_map": {
179
+ "AutoConfig": "configuration_avhubert.AVHubertConfig",
180
+ "AutoModel": "modeling_avhubert.AVHubertModel"
181
+ },
182
+ "bos_token_id": 1,
183
+ "chunk_size_feed_forward": 0,
184
+ "classifier_proj_size": 256,
185
+ "cnn_module_kernel": 31,
186
+ "codevector_dim": 256,
187
+ "contrastive_logits_temperature": 0.1,
188
+ "conv_bias": false,
189
+ "conv_channels": 1024,
190
+ "conv_dim": [
191
+ 512,
192
+ 512,
193
+ 512,
194
+ 512,
195
+ 512,
196
+ 512,
197
+ 512
198
+ ],
199
+ "conv_kernel": [
200
+ 10,
201
+ 3,
202
+ 3,
203
+ 3,
204
+ 3,
205
+ 2,
206
+ 2
207
+ ],
208
+ "conv_kernel_sizes": [
209
+ 5,
210
+ 5
211
+ ],
212
+ "conv_stride": [
213
+ 5,
214
+ 2,
215
+ 2,
216
+ 2,
217
+ 2,
218
+ 2,
219
+ 2
220
+ ],
221
+ "ctc_loss_reduction": "sum",
222
+ "ctc_type": "builtin",
223
+ "ctc_zero_infinity": false,
224
+ "d_model": 1024,
225
+ "ddim": 1024,
226
+ "decoder_attention_heads": 8,
227
+ "decoder_ffn_dim": 4096,
228
+ "decoder_layerdrop": 0.0,
229
+ "decoder_layers": 9,
230
+ "decoder_start_token_id": 2,
231
+ "dheads": 16,
232
+ "diversity_loss_weight": 0.1,
233
+ "dlayers": 6,
234
+ "do_stable_layer_norm": false,
235
+ "dropout": 0.1,
236
+ "dropout_features": 0.1,
237
+ "dropout_input": 0.1,
238
+ "dropout_rate": 0.1,
239
+ "dtype": "float32",
240
+ "dunits": 3072,
241
+ "elayers": 12,
242
+ "encoder_attention_heads": 16,
243
+ "encoder_embed_dim": 1024,
244
+ "encoder_ffn_dim": 2048,
245
+ "encoder_layerdrop": 0.0,
246
+ "encoder_layers": 12,
247
+ "eos_token_id": 2,
248
+ "eunits": 3072,
249
+ "feat_extract_activation": "gelu",
250
+ "feat_extract_norm": "group",
251
+ "feat_proj_dropout": 0.1,
252
+ "feat_quantizer_dropout": 0.0,
253
+ "feature_grad_mult": 0.1,
254
+ "final_dim": 256,
255
+ "final_dropout": 0.0,
256
+ "freeze_feat_extract_train": true,
257
+ "fusion_hdim": 8192,
258
+ "fusion_norm": "batchnorm",
259
+ "hidden_act": "gelu",
260
+ "hidden_dropout": 0.1,
261
+ "hidden_size": 1024,
262
+ "id2label": {
263
+ "0": "LABEL_0",
264
+ "1": "LABEL_1"
265
+ },
266
+ "init_std": 0.02,
267
+ "initializer_range": 0.02,
268
+ "input_channels": 1,
269
+ "input_feat_per_channel": 80,
270
+ "intermediate_size": 4096,
271
+ "is_encoder_decoder": true,
272
+ "label2id": {
273
+ "LABEL_0": 0,
274
+ "LABEL_1": 1
275
+ },
276
+ "label_rate": 25,
277
+ "layer_norm_eps": 1e-05,
278
+ "layerdrop": 0.0,
279
+ "logit_temp": 0.1,
280
+ "lsm_weight": 0.1,
281
+ "macaron_style": true,
282
+ "mask_channel_length": 10,
283
+ "mask_channel_min_space": 1,
284
+ "mask_channel_other": 0.0,
285
+ "mask_channel_prob": 0.0,
286
+ "mask_channel_selection": "static",
287
+ "mask_feature_length": 10,
288
+ "mask_feature_min_masks": 0,
289
+ "mask_feature_prob": 0.0,
290
+ "mask_length_audio": 10,
291
+ "mask_length_image": 5,
292
+ "mask_min_space": 1,
293
+ "mask_other": 0.0,
294
+ "mask_prob_audio": 0.8,
295
+ "mask_prob_image": 0.3,
296
+ "mask_selection": "static",
297
+ "mask_time_length": 10,
298
+ "mask_time_min_masks": 2,
299
+ "mask_time_min_space": 1,
300
+ "mask_time_other": 0.0,
301
+ "mask_time_prob": 0.0,
302
+ "mask_time_selection": "static",
303
+ "masking_type": "input",
304
+ "max_source_positions": 6000,
305
+ "max_target_positions": 2048,
306
+ "modality": "av",
307
+ "modality_dropout": 0.5,
308
+ "modality_fuse": "concat",
309
+ "model_type": "avhubert",
310
+ "mtlalpha": 0.1,
311
+ "no_mask_channel_overlap": false,
312
+ "no_mask_overlap": false,
313
+ "no_mask_time_overlap": false,
314
+ "num_adapter_layers": 3,
315
+ "num_attention_heads": 16,
316
+ "num_classes": 2004,
317
+ "num_codevector_groups": 2,
318
+ "num_codevectors_per_group": 320,
319
+ "num_conv_layers": 2,
320
+ "num_conv_pos_embedding_groups": 16,
321
+ "num_conv_pos_embeddings": 128,
322
+ "num_dictionaries": 1,
323
+ "num_feat_extract_layers": 7,
324
+ "num_hidden_layers": 24,
325
+ "num_negatives": 100,
326
+ "odim": 5049,
327
+ "output_attentions": false,
328
+ "output_hidden_size": 1024,
329
+ "output_hidden_states": false,
330
+ "pad_token_id": 1,
331
+ "problem_type": null,
332
+ "proj_codevector_dim": 256,
333
+ "rel_pos_type": "latest",
334
+ "relu_type": "swish",
335
+ "resnet_relu_type": "prelu",
336
+ "resnet_weights": null,
337
+ "return_dict": true,
338
+ "sample_rate": 25,
339
+ "scale_embedding": null,
340
+ "selection_type": "same_seq",
341
+ "sim_type": "cosine",
342
+ "skip_masked": false,
343
+ "skip_nomask": false,
344
+ "sub_encoder_layers": 0,
345
+ "target_glu": false,
346
+ "tdnn_dilation": [
347
+ 1,
348
+ 2,
349
+ 3,
350
+ 1,
351
+ 1
352
+ ],
353
+ "tdnn_dim": [
354
+ 512,
355
+ 512,
356
+ 512,
357
+ 512,
358
+ 1500
359
+ ],
360
+ "tdnn_kernel": [
361
+ 5,
362
+ 3,
363
+ 3,
364
+ 1,
365
+ 1
366
+ ],
367
+ "transformer_attn_dropout_rate": 0.1,
368
+ "transformer_encoder_attn_layer_type": "rel_mha",
369
+ "transformer_input_layer": "conv3d",
370
+ "transformer_length_normalized_loss": false,
371
+ "untie_final_proj": true,
372
+ "use_cache": true,
373
+ "use_cnn_module": true,
374
+ "use_weighted_layer_sum": false,
375
+ "vocab_size": 1000,
376
+ "xvector_output_dim": 512,
377
+ "zero_triu": false
378
+ },
379
+ "vocab_size": 32
380
+ },
381
+ "vocab_size": 32
382
+ }
configuration_avhubert.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class AVHubertConfig(PretrainedConfig):
5
+ model_type = "avhubert"
6
+
7
+ def __init__(
8
+ self,
9
+ odim=5049,
10
+ adim=1024,
11
+ aheads=12,
12
+ eunits=3072,
13
+ elayers=12,
14
+ transformer_input_layer="conv3d",
15
+ dropout_rate=0.1,
16
+ transformer_attn_dropout_rate=0.1,
17
+ transformer_encoder_attn_layer_type="rel_mha",
18
+ macaron_style=True,
19
+ use_cnn_module=True,
20
+ cnn_module_kernel=31,
21
+ zero_triu=False,
22
+ a_upsample_ratio=1,
23
+ relu_type="swish",
24
+ ddim=1024,
25
+ dheads=16,
26
+ dunits=3072,
27
+ dlayers=6,
28
+ lsm_weight=0.1,
29
+ transformer_length_normalized_loss=False,
30
+ mtlalpha=0.1,
31
+ ctc_type="builtin",
32
+ rel_pos_type="latest",
33
+ fusion_hdim=8192,
34
+ fusion_norm="batchnorm",
35
+ hidden_size=1024,
36
+ num_attention_heads=16,
37
+ activation_dropout=0.0,
38
+ activation_function="relu",
39
+ adapter_attn_dim=None,
40
+ adapter_kernel_size=3,
41
+ adapter_stride=2,
42
+ add_adapter=False,
43
+ apply_spec_augment=True,
44
+ attention_dropout=0.1,
45
+ audio_dropout=0.5,
46
+ audio_feat_dim=104,
47
+ bos_token_id=1,
48
+ classifier_proj_size=256,
49
+ codevector_dim=256,
50
+ contrastive_logits_temperature=0.1,
51
+ conv_bias=False,
52
+ conv_channels=1024,
53
+ conv_dim=[512, 512, 512, 512, 512, 512, 512],
54
+ conv_kernel=[10, 3, 3, 3, 3, 2, 2],
55
+ conv_kernel_sizes=[5, 5],
56
+ conv_stride=[5, 2, 2, 2, 2, 2, 2],
57
+ ctc_loss_reduction="sum",
58
+ ctc_zero_infinity=False,
59
+ d_model=1024,
60
+ decoder_attention_heads=8,
61
+ decoder_ffn_dim=4096,
62
+ decoder_layerdrop=0.0,
63
+ decoder_layers=9,
64
+ decoder_start_token_id=2,
65
+ diversity_loss_weight=0.1,
66
+ do_stable_layer_norm=False,
67
+ dropout=0.1,
68
+ dropout_features=0.1,
69
+ dropout_input=0.1,
70
+ encoder_attention_heads=16,
71
+ encoder_embed_dim=1024,
72
+ encoder_ffn_dim=2048,
73
+ encoder_layerdrop=0.0,
74
+ encoder_layers=12,
75
+ eos_token_id=2,
76
+ feat_extract_activation="gelu",
77
+ feat_extract_norm="group",
78
+ feat_proj_dropout=0.1,
79
+ feat_quantizer_dropout=0.0,
80
+ feature_grad_mult=0.1,
81
+ final_dim=256,
82
+ final_dropout=0.0,
83
+ freeze_feat_extract_train=True,
84
+ hidden_act="gelu",
85
+ hidden_dropout=0.1,
86
+ init_std=0.02,
87
+ initializer_range=0.02,
88
+ input_channels=1,
89
+ input_feat_per_channel=80,
90
+ intermediate_size=4096,
91
+ is_encoder_decoder=True,
92
+ label_rate=25,
93
+ layer_norm_eps=1e-05,
94
+ layerdrop=0.0,
95
+ logit_temp=0.1,
96
+ mask_channel_length=10,
97
+ mask_channel_min_space=1,
98
+ mask_channel_other=0.0,
99
+ mask_channel_prob=0.0,
100
+ mask_channel_selection="static",
101
+ mask_feature_length=10,
102
+ mask_feature_min_masks=0,
103
+ mask_feature_prob=0.0,
104
+ mask_length_audio=10,
105
+ mask_length_image=5,
106
+ mask_min_space=1,
107
+ mask_other=0.0,
108
+ mask_prob_audio=0.8,
109
+ mask_prob_image=0.3,
110
+ mask_selection="static",
111
+ mask_time_length=10,
112
+ mask_time_min_masks=2,
113
+ mask_time_min_space=1,
114
+ mask_time_other=0.0,
115
+ mask_time_prob=0.0,
116
+ mask_time_selection="static",
117
+ masking_type="input",
118
+ max_source_positions=6000,
119
+ max_target_positions=2048,
120
+ modality_dropout=0.5,
121
+ modality_fuse="concat",
122
+ modality="av",
123
+ model_type="speech_to_text",
124
+ no_mask_channel_overlap=False,
125
+ no_mask_overlap=False,
126
+ no_mask_time_overlap=False,
127
+ num_adapter_layers=3,
128
+ num_classes=2004,
129
+ num_codevector_groups=2,
130
+ num_codevectors_per_group=320,
131
+ num_conv_layers=2,
132
+ num_conv_pos_embedding_groups=16,
133
+ num_conv_pos_embeddings=128,
134
+ num_dictionaries=1,
135
+ num_feat_extract_layers=7,
136
+ num_hidden_layers=24,
137
+ num_negatives=100,
138
+ output_hidden_size=1024,
139
+ pad_token_id=1,
140
+ proj_codevector_dim=256,
141
+ resnet_relu_type="prelu",
142
+ resnet_weights=None,
143
+ sample_rate=25,
144
+ scale_embedding=None,
145
+ selection_type="same_seq",
146
+ sim_type="cosine",
147
+ skip_masked=False,
148
+ skip_nomask=False,
149
+ sub_encoder_layers=0,
150
+ target_glu=False,
151
+ tdnn_dilation=[1, 2, 3, 1, 1],
152
+ tdnn_dim=[512, 512, 512, 512, 1500],
153
+ tdnn_kernel=[5, 3, 3, 1, 1],
154
+ untie_final_proj=True,
155
+ use_cache=True,
156
+ use_weighted_layer_sum=False,
157
+ vocab_size=1000,
158
+ xvector_output_dim=512,
159
+ **kwargs,
160
+ ):
161
+ super().__init__(**kwargs)
162
+ self.odim = odim
163
+ self.adim = adim
164
+ self.aheads = aheads
165
+ self.eunits = eunits
166
+ self.elayers = elayers
167
+ self.transformer_input_layer = transformer_input_layer
168
+ self.dropout_rate = dropout_rate
169
+ self.transformer_attn_dropout_rate = transformer_attn_dropout_rate
170
+ self.transformer_encoder_attn_layer_type = transformer_encoder_attn_layer_type
171
+ self.macaron_style = macaron_style
172
+ self.use_cnn_module = use_cnn_module
173
+ self.cnn_module_kernel = cnn_module_kernel
174
+ self.zero_triu = zero_triu
175
+ self.a_upsample_ratio = a_upsample_ratio
176
+ self.relu_type = relu_type
177
+ self.ddim = ddim
178
+ self.dheads = dheads
179
+ self.dunits = dunits
180
+ self.dlayers = dlayers
181
+ self.lsm_weight = lsm_weight
182
+ self.transformer_length_normalized_loss = transformer_length_normalized_loss
183
+ self.mtlalpha = mtlalpha
184
+ self.ctc_type = ctc_type
185
+ self.rel_pos_type = rel_pos_type
186
+ self.fusion_hdim = fusion_hdim
187
+ self.fusion_norm = fusion_norm
188
+
189
+ self.hidden_size = hidden_size
190
+ self.num_attention_heads = num_attention_heads
191
+ self.activation_dropout = activation_dropout
192
+ self.activation_function = activation_function
193
+ self.adapter_attn_dim = adapter_attn_dim
194
+ self.adapter_kernel_size = adapter_kernel_size
195
+ self.adapter_stride = adapter_stride
196
+ self.add_adapter = add_adapter
197
+ self.apply_spec_augment = apply_spec_augment
198
+ self.attention_dropout = attention_dropout
199
+ self.audio_dropout = audio_dropout
200
+ self.audio_feat_dim = audio_feat_dim
201
+ self.bos_token_id = bos_token_id
202
+ self.classifier_proj_size = classifier_proj_size
203
+ self.codevector_dim = codevector_dim
204
+ self.contrastive_logits_temperature = contrastive_logits_temperature
205
+ self.conv_bias = conv_bias
206
+ self.conv_channels = conv_channels
207
+ self.conv_dim = conv_dim
208
+ self.conv_kernel = conv_kernel
209
+ self.conv_kernel_sizes = conv_kernel_sizes
210
+ self.conv_stride = conv_stride
211
+ self.ctc_loss_reduction = ctc_loss_reduction
212
+ self.ctc_zero_infinity = ctc_zero_infinity
213
+ self.d_model = d_model
214
+ self.decoder_attention_heads = decoder_attention_heads
215
+ self.decoder_ffn_dim = decoder_ffn_dim
216
+ self.decoder_layerdrop = decoder_layerdrop
217
+ self.decoder_layers = decoder_layers
218
+ self.decoder_start_token_id = decoder_start_token_id
219
+ self.diversity_loss_weight = diversity_loss_weight
220
+ self.do_stable_layer_norm = do_stable_layer_norm
221
+ self.dropout = dropout
222
+ self.dropout_features = dropout_features
223
+ self.dropout_input = dropout_input
224
+ self.encoder_attention_heads = encoder_attention_heads
225
+ self.encoder_embed_dim = encoder_embed_dim
226
+ self.encoder_ffn_dim = encoder_ffn_dim
227
+ self.encoder_layerdrop = encoder_layerdrop
228
+ self.encoder_layers = encoder_layers
229
+ self.eos_token_id = eos_token_id
230
+ self.feat_extract_activation = feat_extract_activation
231
+ self.feat_extract_norm = feat_extract_norm
232
+ self.feat_proj_dropout = feat_proj_dropout
233
+ self.feat_quantizer_dropout = feat_quantizer_dropout
234
+ self.feature_grad_mult = feature_grad_mult
235
+ self.final_dim = final_dim
236
+ self.final_dropout = final_dropout
237
+ self.freeze_feat_extract_train = freeze_feat_extract_train
238
+ self.hidden_act = hidden_act
239
+ self.hidden_dropout = hidden_dropout
240
+ self.init_std = init_std
241
+ self.initializer_range = initializer_range
242
+ self.input_channels = input_channels
243
+ self.input_feat_per_channel = input_feat_per_channel
244
+ self.intermediate_size = intermediate_size
245
+ self.is_encoder_decoder = is_encoder_decoder
246
+ self.label_rate = label_rate
247
+ self.layer_norm_eps = layer_norm_eps
248
+ self.layerdrop = layerdrop
249
+ self.logit_temp = logit_temp
250
+ self.mask_channel_length = mask_channel_length
251
+ self.mask_channel_min_space = mask_channel_min_space
252
+ self.mask_channel_other = mask_channel_other
253
+ self.mask_channel_prob = mask_channel_prob
254
+ self.mask_channel_selection = mask_channel_selection
255
+ self.mask_feature_length = mask_feature_length
256
+ self.mask_feature_min_masks = mask_feature_min_masks
257
+ self.mask_feature_prob = mask_feature_prob
258
+ self.mask_length_audio = mask_length_audio
259
+ self.mask_length_image = mask_length_image
260
+ self.mask_min_space = mask_min_space
261
+ self.mask_other = mask_other
262
+ self.mask_prob_audio = mask_prob_audio
263
+ self.mask_prob_image = mask_prob_image
264
+ self.mask_selection = mask_selection
265
+ self.mask_time_length = mask_time_length
266
+ self.mask_time_min_masks = mask_time_min_masks
267
+ self.mask_time_min_space = mask_time_min_space
268
+ self.mask_time_other = mask_time_other
269
+ self.mask_time_prob = mask_time_prob
270
+ self.mask_time_selection = mask_time_selection
271
+ self.masking_type = masking_type
272
+ self.max_source_positions = max_source_positions
273
+ self.max_target_positions = max_target_positions
274
+ self.modality_dropout = modality_dropout
275
+ self.modality_fuse = modality_fuse
276
+ self.modality = modality
277
+ self.model_type = model_type
278
+ self.no_mask_channel_overlap = no_mask_channel_overlap
279
+ self.no_mask_overlap = no_mask_overlap
280
+ self.no_mask_time_overlap = no_mask_time_overlap
281
+ self.num_adapter_layers = num_adapter_layers
282
+ self.num_classes = num_classes
283
+ self.num_codevector_groups = num_codevector_groups
284
+ self.num_codevectors_per_group = num_codevectors_per_group
285
+ self.num_conv_layers = num_conv_layers
286
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
287
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
288
+ self.num_dictionaries = num_dictionaries
289
+ self.num_feat_extract_layers = num_feat_extract_layers
290
+ self.num_hidden_layers = num_hidden_layers
291
+ self.num_negatives = num_negatives
292
+ self.output_hidden_size = output_hidden_size
293
+ self.pad_token_id = pad_token_id
294
+ self.proj_codevector_dim = proj_codevector_dim
295
+ self.resnet_relu_type = resnet_relu_type
296
+ self.resnet_weights = resnet_weights
297
+ self.sample_rate = sample_rate
298
+ self.scale_embedding = scale_embedding
299
+ self.selection_type = selection_type
300
+ self.sim_type = sim_type
301
+ self.skip_masked = skip_masked
302
+ self.skip_nomask = skip_nomask
303
+ self.sub_encoder_layers = sub_encoder_layers
304
+ self.target_glu = target_glu
305
+ self.tdnn_dilation = tdnn_dilation
306
+ self.tdnn_dim = tdnn_dim
307
+ self.tdnn_kernel = tdnn_kernel
308
+ self.untie_final_proj = untie_final_proj
309
+ self.use_cache = use_cache
310
+ self.use_weighted_layer_sum = use_weighted_layer_sum
311
+ self.vocab_size = vocab_size
312
+ self.xvector_output_dim = xvector_output_dim
configuration_msp.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ from transformers import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ from .configuration_msp_audio import MSPAudioConfig
7
+ from .configuration_msp_visual import MSPVisualConfig
8
+
9
+ logger = logging.get_logger(__name__)
10
+
11
+
12
+ class MSPConfig(PretrainedConfig):
13
+ model_type = "msp"
14
+
15
+ sub_configs = {
16
+ "audio_config": MSPAudioConfig,
17
+ "visual_config": MSPVisualConfig,
18
+ }
19
+
20
+ def __init__(
21
+ self,
22
+ audio_config: MSPAudioConfig | dict | None = None,
23
+ visual_config: MSPVisualConfig | dict | None = None,
24
+ fusion_hidden_size: int = 768,
25
+ fusion_num_attention_heads: int = 12,
26
+ fusion_intermediate_size: int = 3072,
27
+ fusion_hidden_act: str = "gelu",
28
+ fusion_activation_dropout: float = 0.1,
29
+ fusion_attention_dropout: float = 0.1,
30
+ fusion_hidden_dropout: float = 0.1,
31
+ fusion_layer_norm_eps: float = 1e-5,
32
+ initializer_range: float = 0.02,
33
+ final_dropout: float = 0.1,
34
+ vocab_size: int = 32,
35
+ ctc_loss_reduction: Literal["mean", "sum", "none"] = "mean",
36
+ ctc_zero_infinity: bool = True,
37
+ ctc_loss_audio_weight: float = 0.2,
38
+ ctc_loss_visual_weight: float = 0.2,
39
+ ctc_loss_msp_weight: float = 0.6,
40
+ pad_token_id: int = 0,
41
+ bos_token_id: int = 1,
42
+ eos_token_id: int = 2,
43
+ **kwargs,
44
+ ):
45
+
46
+ super().__init__(**kwargs)
47
+
48
+ # encoders configs
49
+ if isinstance(audio_config, dict):
50
+ audio_config = MSPAudioConfig(**audio_config)
51
+ elif audio_config is None:
52
+ audio_config = MSPAudioConfig()
53
+
54
+ if isinstance(visual_config, dict):
55
+ visual_config = MSPVisualConfig(**visual_config)
56
+ elif visual_config is None:
57
+ visual_config = MSPVisualConfig()
58
+
59
+ self.audio_config = audio_config
60
+ self.visual_config = visual_config
61
+
62
+ # fusion configs
63
+ self.fusion_hidden_size = fusion_hidden_size
64
+ self.fusion_num_attention_heads = fusion_num_attention_heads
65
+ self.fusion_intermediate_size = fusion_intermediate_size
66
+ self.fusion_hidden_act = fusion_hidden_act
67
+ self.fusion_activation_dropout = fusion_activation_dropout
68
+ self.fusion_attention_dropout = fusion_attention_dropout
69
+ self.fusion_hidden_dropout = fusion_hidden_dropout
70
+ self.fusion_layer_norm_eps = fusion_layer_norm_eps
71
+ self.initializer_range = initializer_range
72
+
73
+ # lm heead configs
74
+ self.final_dropout = final_dropout
75
+ self.vocab_size = vocab_size
76
+ self.ctc_loss_reduction = ctc_loss_reduction
77
+ self.ctc_zero_infinity = ctc_zero_infinity
78
+ self.ctc_loss_audio_weight = ctc_loss_audio_weight
79
+ self.ctc_loss_visual_weight = ctc_loss_visual_weight
80
+ self.ctc_loss_msp_weight = ctc_loss_msp_weight
81
+ self.pad_token_id = pad_token_id
82
+ self.bos_token_id = bos_token_id
83
+ self.eos_token_id = eos_token_id
configuration_msp_audio.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import operator
3
+
4
+ from transformers import PretrainedConfig
5
+ from transformers.utils import logging
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+
10
+ class MSPAudioConfig(PretrainedConfig):
11
+ model_type = "msp_audio"
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=32,
16
+ hidden_size=768,
17
+ num_hidden_layers=12,
18
+ num_attention_heads=12,
19
+ intermediate_size=3072,
20
+ hidden_act="gelu",
21
+ hidden_dropout=0.1,
22
+ activation_dropout=0.1,
23
+ attention_dropout=0.1,
24
+ feat_proj_dropout=0.0,
25
+ feat_quantizer_dropout=0.0,
26
+ final_dropout=0.1,
27
+ layerdrop=0.1,
28
+ initializer_range=0.02,
29
+ layer_norm_eps=1e-5,
30
+ feat_extract_norm="group",
31
+ feat_extract_activation="gelu",
32
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
33
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
34
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
35
+ conv_bias=False,
36
+ num_conv_pos_embeddings=128,
37
+ num_conv_pos_embedding_groups=16,
38
+ do_stable_layer_norm=False,
39
+ apply_spec_augment=True,
40
+ mask_time_prob=0.05,
41
+ mask_time_length=10,
42
+ mask_time_min_masks=2,
43
+ mask_feature_prob=0.0,
44
+ mask_feature_length=10,
45
+ mask_feature_min_masks=0,
46
+ num_codevectors_per_group=320,
47
+ num_codevector_groups=2,
48
+ contrastive_logits_temperature=0.1,
49
+ num_negatives=100,
50
+ codevector_dim=256,
51
+ proj_codevector_dim=256,
52
+ diversity_loss_weight=0.1,
53
+ ctc_loss_reduction="mean",
54
+ ctc_zero_infinity=True,
55
+ use_weighted_layer_sum=False,
56
+ classifier_proj_size=256,
57
+ tdnn_dim=(512, 512, 512, 512, 1500),
58
+ tdnn_kernel=(5, 3, 3, 1, 1),
59
+ tdnn_dilation=(1, 2, 3, 1, 1),
60
+ xvector_output_dim=512,
61
+ pad_token_id=0,
62
+ bos_token_id=1,
63
+ eos_token_id=2,
64
+ add_adapter=False,
65
+ adapter_kernel_size=3,
66
+ adapter_stride=2,
67
+ num_adapter_layers=3,
68
+ output_hidden_size=None,
69
+ adapter_attn_dim=None,
70
+ **kwargs,
71
+ ):
72
+ super().__init__(**kwargs)
73
+ self.pad_token_id = pad_token_id
74
+ self.bos_token_id = bos_token_id
75
+ self.eos_token_id = eos_token_id
76
+ self.hidden_size = hidden_size
77
+ self.feat_extract_norm = feat_extract_norm
78
+ self.feat_extract_activation = feat_extract_activation
79
+ self.conv_dim = list(conv_dim)
80
+ self.conv_stride = list(conv_stride)
81
+ self.conv_kernel = list(conv_kernel)
82
+ self.conv_bias = conv_bias
83
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
84
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
85
+ self.num_feat_extract_layers = len(self.conv_dim)
86
+ self.num_hidden_layers = num_hidden_layers
87
+ self.intermediate_size = intermediate_size
88
+ self.hidden_act = hidden_act
89
+ self.num_attention_heads = num_attention_heads
90
+ self.hidden_dropout = hidden_dropout
91
+ self.attention_dropout = attention_dropout
92
+ self.activation_dropout = activation_dropout
93
+ self.feat_proj_dropout = feat_proj_dropout
94
+ self.final_dropout = final_dropout
95
+ self.layerdrop = layerdrop
96
+ self.layer_norm_eps = layer_norm_eps
97
+ self.initializer_range = initializer_range
98
+ self.vocab_size = vocab_size
99
+ self.do_stable_layer_norm = do_stable_layer_norm
100
+ self.use_weighted_layer_sum = use_weighted_layer_sum
101
+
102
+ if (
103
+ (len(self.conv_stride) != self.num_feat_extract_layers)
104
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
105
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
106
+ ):
107
+ raise ValueError(
108
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
109
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
110
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
111
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
112
+ )
113
+
114
+ # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
115
+ self.apply_spec_augment = apply_spec_augment
116
+ self.mask_time_prob = mask_time_prob
117
+ self.mask_time_length = mask_time_length
118
+ self.mask_time_min_masks = mask_time_min_masks
119
+ self.mask_feature_prob = mask_feature_prob
120
+ self.mask_feature_length = mask_feature_length
121
+ self.mask_feature_min_masks = mask_feature_min_masks
122
+
123
+ # parameters for pretraining with codevector quantized representations
124
+ self.num_codevectors_per_group = num_codevectors_per_group
125
+ self.num_codevector_groups = num_codevector_groups
126
+ self.contrastive_logits_temperature = contrastive_logits_temperature
127
+ self.feat_quantizer_dropout = feat_quantizer_dropout
128
+ self.num_negatives = num_negatives
129
+ self.codevector_dim = codevector_dim
130
+ self.proj_codevector_dim = proj_codevector_dim
131
+ self.diversity_loss_weight = diversity_loss_weight
132
+
133
+ # ctc loss
134
+ self.ctc_loss_reduction = ctc_loss_reduction
135
+ self.ctc_zero_infinity = ctc_zero_infinity
136
+
137
+ # adapter
138
+ self.add_adapter = add_adapter
139
+ self.adapter_kernel_size = adapter_kernel_size
140
+ self.adapter_stride = adapter_stride
141
+ self.num_adapter_layers = num_adapter_layers
142
+ self.output_hidden_size = output_hidden_size or hidden_size
143
+ self.adapter_attn_dim = adapter_attn_dim
144
+
145
+ # SequenceClassification-specific parameter. Feel free to ignore for other classes.
146
+ self.classifier_proj_size = classifier_proj_size
147
+
148
+ # XVector-specific parameters. Feel free to ignore for other classes.
149
+ self.tdnn_dim = list(tdnn_dim)
150
+ self.tdnn_kernel = list(tdnn_kernel)
151
+ self.tdnn_dilation = list(tdnn_dilation)
152
+ self.xvector_output_dim = xvector_output_dim
153
+
154
+ @property
155
+ def inputs_to_logits_ratio(self):
156
+ return functools.reduce(operator.mul, self.conv_stride, 1)
configuration_msp_visual.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ from .configuration_avhubert import AVHubertConfig
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ class MSPVisualConfig(PretrainedConfig):
10
+ model_type = "msp_visual"
11
+ sub_configs = {"visual_config": AVHubertConfig}
12
+
13
+ def __init__(
14
+ self,
15
+ visual_config: AVHubertConfig | None | dict = None,
16
+ final_dropout: float = 0.1,
17
+ vocab_size: int = 32,
18
+ ctc_loss_reduction: str = "mean",
19
+ ctc_zero_infinity: bool = True,
20
+ pad_token_id=0,
21
+ bos_token_id=1,
22
+ eos_token_id=2,
23
+ **kwargs,
24
+ ):
25
+ super().__init__(**kwargs)
26
+
27
+ if visual_config is not None:
28
+ if isinstance(visual_config, dict):
29
+ self.visual_config = AVHubertConfig(**visual_config)
30
+ elif isinstance(visual_config, AVHubertConfig):
31
+ self.visual_config = visual_config
32
+ else:
33
+ raise ValueError("visual_config must be a dict or AVHubertConfig.")
34
+
35
+ else:
36
+ self.visual_config = AVHubertConfig()
37
+
38
+ self.final_dropout = final_dropout
39
+ self.vocab_size = vocab_size
40
+ self.ctc_loss_reduction = ctc_loss_reduction
41
+ self.ctc_zero_infinity = ctc_zero_infinity
42
+ self.pad_token_id = pad_token_id
43
+ self.bos_token_id = bos_token_id
44
+ self.eos_token_id = eos_token_id
45
+
46
+ @property
47
+ def hidden_size(self):
48
+ return self.visual_config.adim
fusion.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from transformers.activations import ACT2FN
7
+ from transformers.utils import ModelOutput, logging
8
+
9
+ from .configuration_msp import MSPConfig
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+
14
+ @dataclass
15
+ class MSPFusionOutput(ModelOutput):
16
+ """Outputs produced by the modality-aware fusion network."""
17
+
18
+ last_hidden_state: torch.FloatTensor | None = None
19
+ padding_mask: torch.BoolTensor | None = None
20
+ cross_attentions: tuple | None = None
21
+
22
+
23
+ class FeedForward(nn.Module):
24
+ def __init__(self, config: MSPConfig):
25
+ super().__init__()
26
+ self.intermediate_dropout = nn.Dropout(config.fusion_activation_dropout)
27
+
28
+ self.intermediate_dense = nn.Linear(
29
+ config.fusion_hidden_size, config.fusion_intermediate_size
30
+ )
31
+ if isinstance(config.fusion_hidden_act, str):
32
+ self.intermediate_act_fn = ACT2FN[config.fusion_hidden_act]
33
+ else:
34
+ self.intermediate_act_fn = config.fusion_hidden_act
35
+
36
+ self.output_dense = nn.Linear(
37
+ config.fusion_intermediate_size, config.fusion_hidden_size
38
+ )
39
+ self.output_dropout = nn.Dropout(config.fusion_hidden_dropout)
40
+
41
+ def forward(self, hidden_states):
42
+ hidden_states = self.intermediate_dense(hidden_states)
43
+ hidden_states = self.intermediate_act_fn(hidden_states)
44
+ hidden_states = self.intermediate_dropout(hidden_states)
45
+
46
+ hidden_states = self.output_dense(hidden_states)
47
+ hidden_states = self.output_dropout(hidden_states)
48
+ return hidden_states
49
+
50
+
51
+ class MSPFusionModel(nn.Module):
52
+ def __init__(self, config: MSPConfig):
53
+ super().__init__()
54
+ self.config = config
55
+
56
+ self.audio_projection = nn.Sequential(
57
+ nn.Identity()
58
+ if config.audio_config.hidden_size == config.fusion_hidden_size
59
+ else nn.Linear(config.audio_config.hidden_size, config.fusion_hidden_size),
60
+ nn.LayerNorm(config.fusion_hidden_size, eps=config.fusion_layer_norm_eps),
61
+ )
62
+
63
+ self.visual_projection = nn.Sequential(
64
+ nn.Identity()
65
+ if config.visual_config.hidden_size == config.fusion_hidden_size
66
+ else nn.Linear(config.visual_config.hidden_size, config.fusion_hidden_size),
67
+ nn.LayerNorm(config.fusion_hidden_size, eps=config.fusion_layer_norm_eps),
68
+ )
69
+
70
+ self.av_attn = nn.MultiheadAttention(
71
+ embed_dim=config.fusion_hidden_size,
72
+ num_heads=config.fusion_num_attention_heads,
73
+ dropout=config.fusion_attention_dropout,
74
+ batch_first=True,
75
+ )
76
+ self.va_attn = nn.MultiheadAttention(
77
+ embed_dim=config.fusion_hidden_size,
78
+ num_heads=config.fusion_num_attention_heads,
79
+ dropout=config.fusion_attention_dropout,
80
+ batch_first=True,
81
+ )
82
+ self.av_layer_norm = nn.LayerNorm(
83
+ config.fusion_hidden_size, eps=config.fusion_layer_norm_eps
84
+ )
85
+ self.va_layer_norm = nn.LayerNorm(
86
+ config.fusion_hidden_size, eps=config.fusion_layer_norm_eps
87
+ )
88
+
89
+ self.fusion_layer = nn.Linear(
90
+ config.fusion_hidden_size * 2, config.fusion_hidden_size
91
+ )
92
+ self.feed_forward = FeedForward(config)
93
+ self.final_layer_norm = nn.LayerNorm(
94
+ config.fusion_hidden_size, eps=config.fusion_layer_norm_eps
95
+ )
96
+
97
+ def forward(
98
+ self,
99
+ audio_features: torch.Tensor,
100
+ video_features: torch.Tensor,
101
+ audio_mask: torch.Tensor | None = None,
102
+ video_mask: torch.Tensor | None = None,
103
+ **kwargs,
104
+ ) -> MSPFusionOutput:
105
+
106
+ if audio_features is None or video_features is None:
107
+ raise ValueError(
108
+ "MSP fusion requires both audio_features and video_features."
109
+ )
110
+
111
+ if audio_features.size(0) != video_features.size(0):
112
+ raise ValueError("Audio and video batch sizes must match.")
113
+
114
+ audio_only_encoder_out = self.audio_projection(audio_features)
115
+ video_only_encoder_out = self.visual_projection(video_features)
116
+
117
+ audio_mask = (
118
+ torch.ones(
119
+ audio_only_encoder_out.shape[:2],
120
+ device=audio_only_encoder_out.device,
121
+ dtype=torch.bool,
122
+ )
123
+ if audio_mask is None
124
+ else audio_mask.to(device=audio_only_encoder_out.device, dtype=torch.bool)
125
+ )
126
+ video_mask = (
127
+ torch.ones(
128
+ video_only_encoder_out.shape[:2],
129
+ device=video_only_encoder_out.device,
130
+ dtype=torch.bool,
131
+ )
132
+ if video_mask is None
133
+ else video_mask.to(device=video_only_encoder_out.device, dtype=torch.bool)
134
+ )
135
+
136
+ if (
137
+ audio_mask.shape != audio_only_encoder_out.shape[:2]
138
+ or video_mask.shape != video_only_encoder_out.shape[:2]
139
+ ):
140
+ raise ValueError(
141
+ "Each padding mask must match its encoded feature sequence."
142
+ )
143
+ if (~audio_mask.any(dim=1)).any() or (~video_mask.any(dim=1)).any():
144
+ raise ValueError(
145
+ "Every sample must contain valid audio and video features."
146
+ )
147
+
148
+ # Cross Attention 1: Audio attends to Video
149
+ av_attn_out, av_attn = self.av_attn.forward(
150
+ query=audio_only_encoder_out,
151
+ key=video_only_encoder_out,
152
+ value=video_only_encoder_out,
153
+ key_padding_mask=~video_mask,
154
+ need_weights=True,
155
+ average_attn_weights=False,
156
+ )
157
+
158
+ av_encoder_out = audio_only_encoder_out + av_attn_out
159
+ av_encoder_out = self.av_layer_norm(av_encoder_out)
160
+
161
+ # Cross Attention 2: Video attends to Audio
162
+ va_attn_out, va_attn = self.va_attn.forward(
163
+ query=video_only_encoder_out,
164
+ key=audio_only_encoder_out,
165
+ value=audio_only_encoder_out,
166
+ key_padding_mask=~audio_mask,
167
+ need_weights=True,
168
+ average_attn_weights=False,
169
+ )
170
+ va_encoder_out = video_only_encoder_out + va_attn_out
171
+ va_encoder_out = self.va_layer_norm(va_encoder_out)
172
+
173
+ # Upsampling video_encoder_out to audio_encoder_output's time resolution
174
+ # Correctly transposing before interpolating to operate on the time dimension
175
+ va_encoder_out_perm = va_encoder_out.permute(0, 2, 1)
176
+ va_encoder_out_upsampled = F.interpolate(
177
+ va_encoder_out_perm,
178
+ size=audio_only_encoder_out.shape[1],
179
+ mode="nearest",
180
+ )
181
+ va_encoder_out = va_encoder_out_upsampled.permute(0, 2, 1)
182
+
183
+ # Concatenate on feature dimension and project
184
+ fused = self.fusion_layer(torch.cat((av_encoder_out, va_encoder_out), dim=2))
185
+
186
+ # Feed-Forward Networks (FFN) for Fusion Encoder Output
187
+ fused = self.feed_forward(fused)
188
+ output = self.final_layer_norm(fused)
189
+
190
+ return MSPFusionOutput(
191
+ last_hidden_state=output,
192
+ padding_mask=audio_mask,
193
+ cross_attentions=((av_attn, va_attn),),
194
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4da4c9d3e4bb1e87dbdcbb4c3b27f7fe27ad3eba9f52356ac7fe8e4149a60db
3
+ size 2611680112
modeling_avhubert.py ADDED
@@ -0,0 +1,878 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from copy import deepcopy
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+ from transformers import PreTrainedModel
9
+ from transformers.modeling_outputs import BaseModelOutput
10
+ from transformers.models.wav2vec2.modeling_wav2vec2 import (
11
+ Wav2Vec2Encoder,
12
+ Wav2Vec2EncoderLayer,
13
+ is_deepspeed_zero3_enabled,
14
+ )
15
+
16
+ from .configuration_avhubert import AVHubertConfig
17
+ from .resnet import ResEncoder
18
+
19
+
20
+ def find_runs(x):
21
+ """Find runs of consecutive items in an array."""
22
+
23
+ # ensure array
24
+ x = np.asanyarray(x)
25
+ if x.ndim != 1:
26
+ raise ValueError("only 1D array supported")
27
+ n = x.shape[0]
28
+
29
+ # handle empty array
30
+ if n == 0:
31
+ return np.array([]), np.array([]), np.array([])
32
+
33
+ else:
34
+ # find run starts
35
+ loc_run_start = np.empty(n, dtype=bool)
36
+ loc_run_start[0] = True
37
+ np.not_equal(x[:-1], x[1:], out=loc_run_start[1:])
38
+ run_starts = np.nonzero(loc_run_start)[0]
39
+
40
+ # find run values
41
+ run_values = x[loc_run_start]
42
+
43
+ # find run lengths
44
+ run_lengths = np.diff(np.append(run_starts, n))
45
+
46
+ return run_values, run_starts, run_lengths
47
+
48
+
49
+ def compute_mask_indices(
50
+ shape: Tuple[int, int],
51
+ padding_mask: Optional[torch.Tensor],
52
+ mask_prob: float,
53
+ mask_length: int,
54
+ mask_type: str = "static",
55
+ mask_other: float = 0.0,
56
+ min_masks: int = 0,
57
+ no_overlap: bool = False,
58
+ min_space: int = 0,
59
+ ) -> np.ndarray:
60
+ """
61
+ Computes random mask spans for a given shape
62
+ Args:
63
+ shape: the the shape for which to compute masks.
64
+ should be of size 2 where first element is batch size and 2nd is timesteps
65
+ padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements
66
+ mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by
67
+ number of timesteps divided by length of mask span to mask approximately this percentage of all elements.
68
+ however due to overlaps, the actual number will be smaller (unless no_overlap is True)
69
+ mask_type: how to compute mask lengths
70
+ static = fixed size
71
+ uniform = sample from uniform distribution [mask_other, mask_length*2]
72
+ normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element
73
+ poisson = sample from possion distribution with lambda = mask length
74
+ min_masks: minimum number of masked spans
75
+ no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping
76
+ min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans
77
+ """
78
+
79
+ bsz, all_sz = shape
80
+ mask = np.full((bsz, all_sz), False)
81
+
82
+ all_num_mask = int(
83
+ # add a random number for probabilistic rounding
84
+ mask_prob * all_sz / float(mask_length) + np.random.rand()
85
+ )
86
+
87
+ all_num_mask = max(min_masks, all_num_mask)
88
+
89
+ mask_idcs = []
90
+ for i in range(bsz):
91
+ if padding_mask is not None:
92
+ sz = all_sz - padding_mask[i].long().sum().item()
93
+ num_mask = int(
94
+ # add a random number for probabilistic rounding
95
+ mask_prob * sz / float(mask_length) + np.random.rand()
96
+ )
97
+ num_mask = max(min_masks, num_mask)
98
+ else:
99
+ sz = all_sz
100
+ num_mask = all_num_mask
101
+
102
+ if mask_type == "static":
103
+ lengths = np.full(num_mask, mask_length)
104
+ elif mask_type == "uniform":
105
+ lengths = np.random.randint(mask_other, mask_length * 2 + 1, size=num_mask)
106
+ elif mask_type == "normal":
107
+ lengths = np.random.normal(mask_length, mask_other, size=num_mask)
108
+ lengths = [max(1, int(round(x))) for x in lengths]
109
+ elif mask_type == "poisson":
110
+ lengths = np.random.poisson(mask_length, size=num_mask)
111
+ lengths = [int(round(x)) for x in lengths]
112
+ else:
113
+ raise Exception("unknown mask selection " + mask_type)
114
+
115
+ if sum(lengths) == 0:
116
+ lengths[0] = min(mask_length, sz - 1)
117
+
118
+ if no_overlap:
119
+ mask_idc = []
120
+
121
+ def arrange(s, e, length, keep_length):
122
+ span_start = np.random.randint(s, e - length)
123
+ mask_idc.extend(span_start + i for i in range(length))
124
+
125
+ new_parts = []
126
+ if span_start - s - min_space >= keep_length:
127
+ new_parts.append((s, span_start - min_space + 1))
128
+ if e - span_start - keep_length - min_space > keep_length:
129
+ new_parts.append((span_start + length + min_space, e))
130
+ return new_parts
131
+
132
+ parts = [(0, sz)]
133
+ min_length = min(lengths)
134
+ for length in sorted(lengths, reverse=True):
135
+ lens = np.fromiter(
136
+ (e - s if e - s >= length + min_space else 0 for s, e in parts),
137
+ np.int,
138
+ )
139
+ l_sum = np.sum(lens)
140
+ if l_sum == 0:
141
+ break
142
+ probs = lens / np.sum(lens)
143
+ c = np.random.choice(len(parts), p=probs)
144
+ s, e = parts.pop(c)
145
+ parts.extend(arrange(s, e, length, min_length))
146
+ mask_idc = np.asarray(mask_idc)
147
+ else:
148
+ min_len = min(lengths)
149
+ if sz - min_len <= num_mask:
150
+ min_len = sz - num_mask - 1
151
+
152
+ mask_idc = np.random.choice(sz - min_len, num_mask, replace=False)
153
+
154
+ mask_idc = np.asarray(
155
+ [
156
+ mask_idc[j] + offset
157
+ for j in range(len(mask_idc))
158
+ for offset in range(lengths[j])
159
+ ]
160
+ )
161
+
162
+ mask_idcs.append(np.unique(mask_idc[mask_idc < sz]))
163
+
164
+ min_len = min([len(m) for m in mask_idcs])
165
+ batch_indexes, starts, ends = [], [], []
166
+ for i, mask_idc in enumerate(mask_idcs):
167
+ if len(mask_idc) > min_len:
168
+ mask_idc = np.random.choice(mask_idc, min_len, replace=False)
169
+ mask[i, mask_idc] = True
170
+ vals, run_starts, run_lengths = find_runs(mask[i])
171
+ start_indices, lengths = run_starts[vals], run_lengths[vals]
172
+ starts.append(start_indices)
173
+ ends.append(start_indices + lengths)
174
+ batch_indexes.append(np.zeros([len(start_indices)]) + i)
175
+ return (
176
+ mask,
177
+ np.concatenate(starts).astype(np.int64),
178
+ np.concatenate(ends).astype(np.int64),
179
+ np.concatenate(batch_indexes).astype(np.int64),
180
+ )
181
+
182
+
183
+ class GradMultiply(torch.autograd.Function):
184
+ @staticmethod
185
+ def forward(ctx, x, scale):
186
+ ctx.scale = scale
187
+ res = x.new(x)
188
+ return res
189
+
190
+ @staticmethod
191
+ def backward(ctx, grad):
192
+ return grad * ctx.scale, None
193
+
194
+
195
+ def LayerNorm(normalized_shape, eps=1e-5, elementwise_affine=True, export=False):
196
+ return torch.nn.LayerNorm(normalized_shape, eps, elementwise_affine)
197
+
198
+
199
+ class SubModel(nn.Module):
200
+ def __init__(self, resnet=None, input_dim=None, cfg=None):
201
+ super().__init__()
202
+ self.resnet = resnet
203
+ self.proj = nn.Linear(input_dim, cfg.encoder_embed_dim)
204
+
205
+ def forward(self, x):
206
+ if self.resnet is not None:
207
+ x = self.resnet(x)
208
+ x = self.proj(x.transpose(1, 2))
209
+ x = x.transpose(1, 2)
210
+ return x
211
+
212
+
213
+ class AVHubertModel(PreTrainedModel):
214
+ config_class = AVHubertConfig
215
+ base_model_prefix = "avhubert"
216
+ all_tied_weights_keys = OrderedDict()
217
+ # main_input_name = "input_values"
218
+ # supports_gradient_checkpointing = True
219
+ # _supports_flash_attn_2 = True
220
+ # _supports_sdpa = True
221
+
222
+ def __init__(
223
+ self,
224
+ cfg: AVHubertConfig,
225
+ ) -> None:
226
+ super().__init__(cfg)
227
+ # logger.info(f"HubertModel Config: {cfg}")
228
+
229
+ feature_ds_rate = 1
230
+ self.feat2tar_ratio = cfg.label_rate * feature_ds_rate / cfg.sample_rate
231
+ sub_cfg = deepcopy(cfg)
232
+ sub_cfg.encoder_layers = sub_cfg.sub_encoder_layers
233
+ resnet = ResEncoder(relu_type=cfg.resnet_relu_type, weights=cfg.resnet_weights)
234
+ self.feature_extractor_audio = SubModel(
235
+ resnet=None, input_dim=cfg.audio_feat_dim, cfg=sub_cfg
236
+ )
237
+ self.feature_extractor_video = SubModel(
238
+ resnet=resnet, input_dim=resnet.backend_out, cfg=sub_cfg
239
+ )
240
+ self.modality_dropout, self.audio_dropout = (
241
+ cfg.modality_dropout,
242
+ cfg.audio_dropout,
243
+ )
244
+ self.modality_fuse = cfg.modality_fuse
245
+ self.encoder_embed_dim = cfg.encoder_embed_dim
246
+ if self.modality_fuse == "concat":
247
+ self.embed = cfg.encoder_embed_dim * 2
248
+ elif self.modality_fuse == "add":
249
+ self.embed = cfg.encoder_embed_dim
250
+ self.post_extract_proj = (
251
+ nn.Linear(self.embed, cfg.encoder_embed_dim)
252
+ if self.embed != cfg.encoder_embed_dim
253
+ else None
254
+ )
255
+
256
+ self.mask_prob_image, self.mask_prob_audio = (
257
+ cfg.mask_prob_image,
258
+ cfg.mask_prob_audio,
259
+ )
260
+ self.mask_selection = cfg.mask_selection
261
+ self.mask_other = cfg.mask_other
262
+ self.mask_length_image, self.mask_length_audio = (
263
+ cfg.mask_length_image,
264
+ cfg.mask_length_audio,
265
+ )
266
+ self.no_mask_overlap = cfg.no_mask_overlap
267
+ self.mask_min_space = cfg.mask_min_space
268
+
269
+ self.mask_channel_prob = cfg.mask_channel_prob
270
+ self.mask_channel_selection = cfg.mask_channel_selection
271
+ self.mask_channel_other = cfg.mask_channel_other
272
+ self.mask_channel_length = cfg.mask_channel_length
273
+ self.no_mask_channel_overlap = cfg.no_mask_channel_overlap
274
+ self.mask_channel_min_space = cfg.mask_channel_min_space
275
+
276
+ self.dropout_input = nn.Dropout(cfg.dropout_input)
277
+ self.dropout_features = nn.Dropout(cfg.dropout_features)
278
+
279
+ self.feature_grad_mult = cfg.feature_grad_mult
280
+ self.logit_temp = cfg.logit_temp
281
+ self.skip_masked = cfg.skip_masked
282
+ self.skip_nomask = cfg.skip_nomask
283
+ self.sim_type = cfg.sim_type
284
+ self.selection_type = cfg.selection_type
285
+ self.masking_type = cfg.masking_type
286
+ self.modality = cfg.modality
287
+
288
+ final_dim = cfg.final_dim if cfg.final_dim > 0 else cfg.encoder_embed_dim
289
+
290
+ self.mask_emb = nn.Parameter(
291
+ torch.FloatTensor(cfg.audio_feat_dim).uniform_()
292
+ if self.masking_type == "input"
293
+ else torch.FloatTensor(cfg.encoder_embed_dim).uniform_()
294
+ )
295
+
296
+ self.encoder = AVHubertEncoder(cfg)
297
+
298
+ self.layer_norm = LayerNorm(self.embed)
299
+
300
+ self.target_glu = None
301
+ if cfg.target_glu:
302
+ self.target_glu = nn.Sequential(
303
+ nn.Linear(final_dim, final_dim * 2), nn.GLU()
304
+ )
305
+
306
+ self.untie_final_proj = cfg.untie_final_proj
307
+ # if self.untie_final_proj:
308
+ # self.final_proj = nn.Linear(
309
+ # cfg.encoder_embed_dim, final_dim * cfg.num_dictionaries
310
+ # )
311
+ # else:
312
+ # self.final_proj = nn.Linear(cfg.encoder_embed_dim, final_dim)
313
+
314
+ self.num_classes = [cfg.num_classes]
315
+ self.label_embs_concat = nn.Parameter(
316
+ torch.FloatTensor(sum(self.num_classes), final_dim)
317
+ )
318
+ nn.init.uniform_(self.label_embs_concat)
319
+
320
+ def upgrade_state_dict_named(self, state_dict, name):
321
+ """Upgrade a (possibly old) state dict for new versions of fairseq."""
322
+
323
+ super().upgrade_state_dict_named(state_dict, name)
324
+ return state_dict
325
+
326
+ def apply_input_mask(self, x, padding_mask, target_list):
327
+ B, C, T = x.shape[:3]
328
+ is_audio = True if len(x.shape) == 3 else False
329
+ if is_audio:
330
+ mask_prob, mask_length = self.mask_prob_audio, self.mask_length_audio
331
+ else:
332
+ mask_prob, mask_length = self.mask_prob_image, self.mask_length_image
333
+ if mask_prob > 0:
334
+ mask_indices, starts, ends, batch_indexes = compute_mask_indices(
335
+ (B, T),
336
+ padding_mask,
337
+ mask_prob,
338
+ mask_length,
339
+ self.mask_selection,
340
+ self.mask_other,
341
+ min_masks=2,
342
+ no_overlap=self.no_mask_overlap,
343
+ min_space=self.mask_min_space,
344
+ )
345
+ mask_indices = torch.from_numpy(mask_indices).to(x.device)
346
+ x = x.transpose(1, 2).contiguous() # [B, T, C, H, W]
347
+ if B == 1:
348
+ x[mask_indices] = 0
349
+ elif is_audio:
350
+ x[mask_indices] = self.mask_emb
351
+ elif self.selection_type == "same_other_seq":
352
+ perm = (torch.arange(B) + torch.randint(low=1, high=B, size=(1,))) % B
353
+ x_perm = x[perm]
354
+ x[mask_indices] = x_perm[mask_indices]
355
+ elif self.selection_type == "same_seq":
356
+ batch_indexes_, other_indexes = [], []
357
+ for batch_index, start, end in zip(batch_indexes, starts, ends):
358
+ length = end - start
359
+ other_start = np.setdiff1d(
360
+ np.arange(T), np.arange(max(0, start - length), end)
361
+ )
362
+ if len(other_start) > 0:
363
+ other_start = np.random.choice(other_start, size=1)
364
+ else:
365
+ other_start = 0
366
+ other_end = other_start + length
367
+ other_indexes.append(
368
+ np.arange(other_start, other_end).clip(max=T - 1)
369
+ )
370
+ batch_indexes_.append(
371
+ np.zeros([length], dtype=np.int64) + batch_index
372
+ )
373
+ batch_indexes, other_indexes = (
374
+ np.concatenate(batch_indexes_),
375
+ np.concatenate(other_indexes),
376
+ )
377
+ x[mask_indices] = x[batch_indexes, other_indexes]
378
+
379
+ x = x.transpose(1, 2).contiguous()
380
+ else:
381
+ mask_indices = None
382
+
383
+ # if self.mask_channel_prob > 0:
384
+ # logger.info(f"No mask channel prob for input masking")
385
+ return x, mask_indices
386
+
387
+ def apply_feature_mask(self, x, padding_mask, target_list):
388
+ B, T, C = x.shape
389
+ assert (
390
+ self.mask_prob_audio == self.mask_prob_image
391
+ and self.mask_length_audio == self.mask_length_image
392
+ ), "masking prob/length for image/audio be same for feature masking"
393
+ mask_prob, mask_length = self.mask_prob_audio, self.mask_length_image
394
+ if mask_prob > 0:
395
+ mask_indices, _, _, _ = compute_mask_indices(
396
+ (B, T),
397
+ padding_mask,
398
+ mask_prob,
399
+ mask_length,
400
+ self.mask_selection,
401
+ self.mask_other,
402
+ min_masks=2,
403
+ no_overlap=self.no_mask_overlap,
404
+ min_space=self.mask_min_space,
405
+ )
406
+ mask_indices = torch.from_numpy(mask_indices).to(x.device)
407
+ x[mask_indices] = self.mask_emb
408
+ else:
409
+ mask_indices = None
410
+
411
+ if self.mask_channel_prob > 0:
412
+ mask_channel_indices, _, _, _ = compute_mask_indices(
413
+ (B, C),
414
+ None,
415
+ self.mask_channel_prob,
416
+ self.mask_channel_length,
417
+ self.mask_channel_selection,
418
+ self.mask_channel_other,
419
+ no_overlap=self.no_mask_channel_overlap,
420
+ min_space=self.mask_channel_min_space,
421
+ )
422
+ mask_channel_indices = (
423
+ torch.from_numpy(mask_channel_indices)
424
+ .to(x.device)
425
+ .unsqueeze(1)
426
+ .expand(-1, T, -1)
427
+ )
428
+ x[mask_channel_indices] = 0
429
+
430
+ return x, mask_indices
431
+
432
+ def forward_features(self, source: torch.Tensor, modality: str) -> torch.Tensor:
433
+ extractor = eval(f"self.feature_extractor_{modality}")
434
+ if self.feature_grad_mult > 0:
435
+ features = extractor(source)
436
+ if self.feature_grad_mult != 1.0:
437
+ features = GradMultiply.apply(features, self.feature_grad_mult)
438
+ else:
439
+ with torch.no_grad():
440
+ features = extractor(source)
441
+ return features
442
+
443
+ def forward_targets(
444
+ self,
445
+ features: torch.Tensor,
446
+ mask_indices: torch.Tensor,
447
+ target_list: List[torch.Tensor],
448
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
449
+ # Trim features to ensure labels exist and then get aligned labels
450
+ feat_tsz = features.size(2)
451
+ targ_tsz = min([t.size(1) for t in target_list])
452
+ if self.feat2tar_ratio * feat_tsz > targ_tsz:
453
+ feat_tsz = int(targ_tsz / self.feat2tar_ratio)
454
+ features = features[..., :feat_tsz]
455
+ if mask_indices is not None:
456
+ mask_indices = mask_indices[..., :feat_tsz]
457
+ target_inds = torch.arange(feat_tsz).float() * self.feat2tar_ratio
458
+ target_list = [t[:, target_inds.long()] for t in target_list]
459
+ return features, mask_indices, target_list
460
+
461
+ def forward_padding_mask(
462
+ self,
463
+ features: torch.Tensor,
464
+ padding_mask: torch.Tensor,
465
+ ) -> torch.Tensor:
466
+ extra = padding_mask.size(1) % features.size(1)
467
+ if extra > 0:
468
+ padding_mask = padding_mask[:, :-extra]
469
+ padding_mask = padding_mask.view(padding_mask.size(0), features.size(1), -1)
470
+ padding_mask = padding_mask.all(-1)
471
+ return padding_mask
472
+
473
+ def compute_logits(self, feats, emb_mat):
474
+ # feats: [B, T, F], emb_mat: [V, F]
475
+ if self.sim_type == "dot":
476
+ logits = torch.matmul(feats, emb_mat.transpose(0, 1))
477
+ elif self.sim_type == "cosine":
478
+ batch_size, timesteps, emb_dim = feats.size()
479
+ feats_ = feats.view(-1, emb_dim)
480
+ nom = (feats_.unsqueeze(dim=1) * emb_mat.unsqueeze(dim=0)).sum(
481
+ dim=-1
482
+ ) # [B*T, V]
483
+ denom = (feats_**2).sum(dim=-1).sqrt().unsqueeze(dim=1) * (emb_mat**2).sum(
484
+ dim=-1
485
+ ).sqrt().unsqueeze(dim=0) # [B*T, V]
486
+ logits = (nom / denom.clamp(min=1e-6)).view(batch_size, timesteps, -1)
487
+ else:
488
+ raise NotImplementedError
489
+ logits = logits / self.logit_temp
490
+ return logits
491
+
492
+ def forward_gen(
493
+ self,
494
+ source: torch.Tensor,
495
+ target_list: Optional[List[torch.Tensor]] = None,
496
+ padding_mask: Optional[torch.Tensor] = None,
497
+ mask: bool = True,
498
+ features_only: bool = False,
499
+ output_layer: Optional[int] = None,
500
+ video: Optional[torch.Tensor] = None,
501
+ ) -> Dict[str, torch.Tensor]:
502
+ """output layer is 1-based"""
503
+ src_audio, src_video = source["audio"], source["video"]
504
+ if mask and self.masking_type == "input":
505
+ src_video, mask_indices_video = self.apply_input_mask(
506
+ src_video, padding_mask, target_list
507
+ )
508
+ src_audio, mask_indices_audio = self.apply_input_mask(
509
+ src_audio, padding_mask, target_list
510
+ )
511
+ mask_indices = torch.logical_or(mask_indices_audio, mask_indices_video)
512
+ else:
513
+ src_audio, src_video, mask_indices = src_audio, src_video, None
514
+
515
+ features_audio = self.forward_features(
516
+ src_audio, modality="audio"
517
+ ) # features: [B, F, T]
518
+ features_video = self.forward_features(src_video, modality="video")
519
+
520
+ if self.modality == "audio":
521
+ features_video = 0 * features_video
522
+ elif self.modality == "video":
523
+ features_audio = 0 * features_audio
524
+ else:
525
+ if self.training:
526
+ modality_drop_prob, audio_drop_prob = (
527
+ np.random.random(),
528
+ np.random.random(),
529
+ )
530
+ if modality_drop_prob < self.modality_dropout:
531
+ if audio_drop_prob < self.audio_dropout:
532
+ features_audio = 0 * features_audio
533
+ else:
534
+ features_video = 0 * features_video
535
+
536
+ if self.modality_fuse == "concat":
537
+ features = torch.cat([features_audio, features_video], dim=1)
538
+ elif self.modality_fuse == "add":
539
+ features = features_audio + features_video
540
+ if target_list is not None:
541
+ features, mask_indices, target_list = self.forward_targets(
542
+ features, mask_indices, target_list
543
+ )
544
+
545
+ features_pen = features.float().pow(2).mean()
546
+
547
+ features = features.transpose(1, 2)
548
+ features = self.layer_norm(features)
549
+
550
+ if padding_mask is not None:
551
+ padding_mask = self.forward_padding_mask(features, padding_mask)
552
+
553
+ if self.post_extract_proj is not None:
554
+ features = self.post_extract_proj(features)
555
+
556
+ features = self.dropout_input(features)
557
+ if self.masking_type == "feature" and mask:
558
+ x, mask_indices = self.apply_feature_mask(
559
+ features, padding_mask, target_list
560
+ )
561
+ else:
562
+ x = features
563
+
564
+ # feature: (B, T, D), float
565
+ # target: (B, T), long
566
+ # x: (B, T, D), float
567
+ # padding_mask: (B, T), bool
568
+ # mask_indices: (B, T), bool
569
+
570
+ x = self.encoder(x, attention_mask=padding_mask)[0]
571
+ # x = self.encoder(
572
+ # x,
573
+ # # attention_mask=padding_mask,
574
+ # # layer=None if output_layer is None else output_layer - 1
575
+ # )[0]
576
+
577
+ if features_only:
578
+ return {"x": x, "padding_mask": padding_mask, "features": features}
579
+
580
+ label_embs_list = self.label_embs_concat.split(self.num_classes, 0)
581
+ proj_x = self.final_proj(x)
582
+ if self.untie_final_proj:
583
+ proj_x_list = proj_x.chunk(len(self.num_classes), dim=-1)
584
+ else:
585
+ proj_x_list = [proj_x for _ in self.num_classes]
586
+ logit_list = [
587
+ self.compute_logits(proj, emb).view(-1, num_class)
588
+ for proj, emb, num_class in zip(
589
+ proj_x_list, label_embs_list, self.num_classes
590
+ )
591
+ ] # [[B*T, V]]
592
+ mask, unmask = (
593
+ torch.logical_and(mask_indices, ~padding_mask).view(-1),
594
+ torch.logical_and(~mask_indices, ~padding_mask).view(-1),
595
+ ) # [B*T]
596
+ logit_m_list, logit_u_list = (
597
+ [logit[mask] for logit in logit_list],
598
+ [logit[unmask] for logit in logit_list],
599
+ )
600
+ target_m_list, target_u_list = (
601
+ [target.view(-1)[mask].long() for target in target_list],
602
+ [target.view(-1)[unmask].long() for target in target_list],
603
+ )
604
+ result = {
605
+ "logit_m_list": logit_m_list,
606
+ "logit_u_list": logit_u_list,
607
+ "target_m_list": target_m_list,
608
+ "target_u_list": target_u_list,
609
+ "padding_mask": padding_mask,
610
+ "features_pen": features_pen,
611
+ }
612
+ return result
613
+
614
+ def forward(
615
+ self,
616
+ input_features: torch.Tensor,
617
+ attention_mask: Optional[torch.Tensor] = None,
618
+ video: torch.Tensor = None,
619
+ **kwargs,
620
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
621
+ res = self.forward_gen(
622
+ {"audio": input_features, "video": video},
623
+ padding_mask=attention_mask,
624
+ mask=False,
625
+ features_only=True,
626
+ output_layer=None,
627
+ )
628
+ feature = res["x"]
629
+ return BaseModelOutput(
630
+ last_hidden_state=feature, hidden_states=None, attentions=None
631
+ )
632
+
633
+ def extract_features(
634
+ self,
635
+ source: torch.Tensor,
636
+ padding_mask: Optional[torch.Tensor] = None,
637
+ mask: bool = False,
638
+ ret_conv: bool = False,
639
+ output_layer: Optional[int] = None,
640
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
641
+ res = self.forward_gen(
642
+ source,
643
+ padding_mask=padding_mask,
644
+ mask=mask,
645
+ features_only=True,
646
+ output_layer=output_layer,
647
+ )
648
+ feature = res["features"] if ret_conv else res["x"]
649
+ return feature, res["padding_mask"]
650
+
651
+ def extract_finetune(
652
+ self, source, padding_mask=None, mask=False, ret_conv=False, output_layer=None
653
+ ):
654
+ src_audio, src_video = source["audio"], source["video"]
655
+ if mask and self.masking_type == "input":
656
+ src_video, mask_indices_video = self.apply_input_mask(
657
+ src_video, padding_mask, target_list=None
658
+ )
659
+ src_audio, mask_indices_audio = self.apply_input_mask(
660
+ src_audio, padding_mask, target_list=None
661
+ )
662
+ mask_indices = torch.logical_or(
663
+ mask_indices_audio, mask_indices_video
664
+ ) # mask_indices not used in fine-tuning
665
+ else:
666
+ src_audio, src_video, mask_indices = src_audio, src_video, None # noqa: F841
667
+
668
+ if src_audio is not None and src_video is None:
669
+ features_audio = self.forward_features(
670
+ src_audio, modality="audio"
671
+ ) # features: [B, F, T]
672
+ features_video = features_audio.new_zeros(
673
+ features_audio.size(0), self.encoder_embed_dim, features_audio.size(-1)
674
+ )
675
+ elif src_audio is None and src_video is not None:
676
+ features_video = self.forward_features(src_video, modality="video")
677
+ features_audio = features_video.new_zeros(
678
+ features_video.size(0), self.encoder_embed_dim, features_video.size(-1)
679
+ )
680
+ elif src_audio is not None and src_video is not None:
681
+ features_video = self.forward_features(src_video, modality="video")
682
+ features_audio = self.forward_features(
683
+ src_audio, modality="audio"
684
+ ) # features: [B, F, T]
685
+
686
+ if self.modality_fuse == "concat":
687
+ features = torch.cat([features_audio, features_video], dim=1)
688
+ elif self.modality_fuse == "add":
689
+ features = features_audio + features_video
690
+ features.float().pow(2).mean()
691
+
692
+ features = features.transpose(1, 2)
693
+ features = self.layer_norm(features)
694
+ unmasked_features = features.clone()
695
+
696
+ if padding_mask is not None:
697
+ padding_mask = self.forward_padding_mask(features, padding_mask)
698
+
699
+ if self.post_extract_proj is not None:
700
+ features = self.post_extract_proj(features)
701
+
702
+ features = self.dropout_input(features)
703
+ unmasked_features = self.dropout_features(unmasked_features)
704
+ x = features
705
+
706
+ # feature: (B, T, D), float
707
+ # target: (B, T), long
708
+ # x: (B, T, D), float
709
+ # padding_mask: (B, T), bool
710
+ # mask_indices: (B, T), bool
711
+ # ``padding_mask`` is the MSP valid-position mask (True = valid). The
712
+ # local AVHubertEncoder follows the Transformers attention-mask
713
+ # convention, so forwarding it prevents padded video frames from
714
+ # participating in self-attention.
715
+ x = self.encoder(x, attention_mask=padding_mask)[0]
716
+
717
+ return x, padding_mask
718
+
719
+ def get_extra_losses(self, net_output):
720
+ extra_losses = []
721
+ names = []
722
+ if "features_pen" in net_output:
723
+ extra_losses.append(net_output["features_pen"])
724
+ names.append("features_pen")
725
+
726
+ return extra_losses, names
727
+
728
+ def remove_pretraining_modules(self):
729
+ self.target_glu = None
730
+ self.final_proj = None
731
+
732
+ def get_logits(self, net_output, is_masked=True):
733
+ raise NotImplementedError
734
+
735
+ def get_targets(self, net_output, is_masked=True):
736
+ raise NotImplementedError
737
+
738
+ def compute_nce(self, x, pos, negs):
739
+ neg_is_pos = (pos == negs).all(-1)
740
+ pos = pos.unsqueeze(0)
741
+ targets = torch.cat([pos, negs], dim=0)
742
+
743
+ logits = torch.cosine_similarity(x.float(), targets.float(), dim=-1).type_as(x)
744
+ logits /= self.logit_temp
745
+ if neg_is_pos.any():
746
+ logits[1:][neg_is_pos] = float("-inf")
747
+ logits = logits.transpose(0, 1) # (num_x, num_cls+1)
748
+ return logits
749
+
750
+
751
+ class AVHubertEncoder(Wav2Vec2Encoder):
752
+ def __init__(self, config):
753
+ super().__init__(config)
754
+ self.layers = nn.ModuleList(
755
+ [AVHubertEncoderLayer(config) for _ in range(config.num_hidden_layers)]
756
+ )
757
+
758
+ def forward(
759
+ self,
760
+ hidden_states: torch.tensor,
761
+ attention_mask: Optional[torch.Tensor] = None,
762
+ output_attentions: bool = False,
763
+ output_hidden_states: bool = False,
764
+ return_dict: bool = True,
765
+ ):
766
+ all_hidden_states = () if output_hidden_states else None
767
+ all_self_attentions = () if output_attentions else None
768
+
769
+ if attention_mask is not None:
770
+ # make sure padded tokens output 0
771
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(
772
+ 1, 1, hidden_states.shape[2]
773
+ )
774
+ hidden_states[~expand_attention_mask] = 0
775
+ if hasattr(self, "_use_flash_attention_2") and self._use_flash_attention_2:
776
+ # 2d mask is passed through the layers
777
+ attention_mask = (
778
+ attention_mask
779
+ if (attention_mask is not None and 0 in attention_mask)
780
+ else None
781
+ )
782
+ else:
783
+ # extend attention_mask
784
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(
785
+ dtype=hidden_states.dtype
786
+ )
787
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
788
+ attention_mask = attention_mask.expand(
789
+ attention_mask.shape[0],
790
+ 1,
791
+ attention_mask.shape[-1],
792
+ attention_mask.shape[-1],
793
+ )
794
+
795
+ position_embeddings = self.pos_conv_embed(hidden_states)
796
+ hidden_states = hidden_states + position_embeddings
797
+ # hidden_states = self.layer_norm(hidden_states)
798
+ hidden_states = self.dropout(hidden_states)
799
+
800
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
801
+
802
+ for layer in self.layers:
803
+ if output_hidden_states:
804
+ all_hidden_states = all_hidden_states + (hidden_states,)
805
+
806
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
807
+ dropout_probability = torch.rand([])
808
+
809
+ skip_the_layer = (
810
+ True
811
+ if self.training and (dropout_probability < self.config.layerdrop)
812
+ else False
813
+ )
814
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
815
+ # under deepspeed zero3 all gpus must run in sync
816
+ if self.gradient_checkpointing and self.training:
817
+ layer_outputs = self._gradient_checkpointing_func(
818
+ layer.__call__,
819
+ hidden_states,
820
+ attention_mask,
821
+ output_attentions,
822
+ )
823
+ else:
824
+ layer_outputs = layer(
825
+ hidden_states,
826
+ attention_mask=attention_mask,
827
+ output_attentions=output_attentions,
828
+ )
829
+ hidden_states = layer_outputs[0]
830
+
831
+ if skip_the_layer:
832
+ layer_outputs = (None, None)
833
+
834
+ if output_attentions:
835
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
836
+
837
+ hidden_states = self.layer_norm(hidden_states)
838
+
839
+ if output_hidden_states:
840
+ all_hidden_states = all_hidden_states + (hidden_states,)
841
+
842
+ if not return_dict:
843
+ return tuple(
844
+ v
845
+ for v in [hidden_states, all_hidden_states, all_self_attentions]
846
+ if v is not None
847
+ )
848
+ return BaseModelOutput(
849
+ last_hidden_state=hidden_states,
850
+ hidden_states=all_hidden_states,
851
+ attentions=all_self_attentions,
852
+ )
853
+
854
+
855
+ class AVHubertEncoderLayer(Wav2Vec2EncoderLayer):
856
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
857
+ attn_residual = hidden_states
858
+ hidden_states = self.layer_norm(hidden_states)
859
+ hidden_states, attn_weights, _ = self.attention(
860
+ hidden_states,
861
+ attention_mask=attention_mask,
862
+ output_attentions=output_attentions,
863
+ )
864
+ hidden_states = self.dropout(hidden_states)
865
+ hidden_states = attn_residual + hidden_states
866
+
867
+ # hidden_states = self.layer_norm(hidden_states)
868
+ residual = hidden_states
869
+ hidden_states = self.final_layer_norm(hidden_states)
870
+ hidden_states = residual + self.feed_forward(hidden_states)
871
+ # hidden_states = self.final_layer_norm(hidden_states)
872
+
873
+ outputs = (hidden_states,)
874
+
875
+ if output_attentions:
876
+ outputs += (attn_weights,)
877
+
878
+ return outputs
modeling_msp.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers import PreTrainedModel
8
+ from transformers.modeling_outputs import CausalLMOutput
9
+ from transformers.utils import ModelOutput, logging
10
+
11
+ from .modeling_msp_audio import MSPAudioForCTC
12
+ from .modeling_msp_visual import MSPVisualForCTC
13
+
14
+ from .configuration_msp import MSPConfig
15
+ from .fusion import MSPFusionModel
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ @dataclass
21
+ class MSPModelOutput(ModelOutput):
22
+ """Encoder and modality-aware fusion representations."""
23
+
24
+ last_hidden_state: torch.FloatTensor | None = None
25
+ padding_mask: torch.BoolTensor | None = None
26
+ audio_input_lengths: torch.LongTensor | None = None
27
+ visual_input_lengths: torch.LongTensor | None = None
28
+ audio_hidden_state: torch.FloatTensor | None = None
29
+ visual_hidden_state: torch.FloatTensor | None = None
30
+ cross_attentions: tuple | None = None
31
+
32
+
33
+ @dataclass
34
+ class MSPCTCOutput(CausalLMOutput):
35
+ """MSP CTC output with optional training-only auxiliary losses."""
36
+
37
+ pass
38
+
39
+
40
+ def _compute_ctc_loss(
41
+ logits: torch.Tensor,
42
+ labels: torch.Tensor,
43
+ input_lengths: torch.Tensor,
44
+ blank: int,
45
+ reduction: str,
46
+ zero_infinity: bool,
47
+ ) -> torch.Tensor:
48
+ labels_mask = labels >= 0
49
+ target_lengths = labels_mask.sum(dim=-1)
50
+ flattened_targets = labels.masked_select(labels_mask)
51
+ log_probs = F.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
52
+ with torch.backends.cudnn.flags(enabled=False):
53
+ return F.ctc_loss(
54
+ log_probs,
55
+ flattened_targets,
56
+ input_lengths,
57
+ target_lengths,
58
+ blank=blank,
59
+ reduction=reduction,
60
+ zero_infinity=zero_infinity,
61
+ )
62
+
63
+
64
+ class MSPPreTrainedModel(PreTrainedModel):
65
+ config_class = MSPConfig
66
+ base_model_prefix = "msp"
67
+ main_input_name = "input_values"
68
+ input_modalities = ["audio", "video"]
69
+ supports_gradient_checkpointing = False
70
+ all_tied_weights_keys = OrderedDict()
71
+
72
+ def _init_weights(self, module):
73
+ if isinstance(module, nn.Linear):
74
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
75
+ if module.bias is not None:
76
+ nn.init.zeros_(module.bias)
77
+ elif isinstance(module, nn.LayerNorm):
78
+ nn.init.zeros_(module.bias)
79
+ nn.init.ones_(module.weight)
80
+
81
+ @property
82
+ def dummy_inputs(self) -> dict:
83
+ return {
84
+ "input_values": torch.zeros(1, 16000, dtype=torch.float32),
85
+ "padding_mask": torch.ones(1, 16000, dtype=torch.long),
86
+ "pixel_values_videos": torch.zeros(1, 1, 25, 88, 88, dtype=torch.float32),
87
+ "padding_mask_videos": torch.ones(1, 25, dtype=torch.long),
88
+ "labels": torch.ones(1, 5, dtype=torch.long),
89
+ }
90
+
91
+
92
+ class MSPModel(MSPPreTrainedModel):
93
+ def __init__(self, config: MSPConfig):
94
+ super().__init__(config)
95
+ self.config = config
96
+ self.audio_model = MSPAudioForCTC(config=config.audio_config)
97
+ self.visual_model = MSPVisualForCTC(config=config.visual_config)
98
+ self.fusion_model = MSPFusionModel(config)
99
+ self.post_init()
100
+
101
+ def encode_audio(
102
+ self,
103
+ input_values: torch.Tensor,
104
+ padding_mask: torch.Tensor | None = None,
105
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
106
+
107
+ if padding_mask is None:
108
+ padding_mask = torch.ones_like(input_values, dtype=torch.long)
109
+ if padding_mask.ndim != 2 or padding_mask.shape != input_values.shape[:2]:
110
+ raise ValueError(
111
+ "padding_mask must match input_values on batch and time axes."
112
+ )
113
+
114
+ outputs = self.audio_model.msp_audio.forward(
115
+ input_values=input_values,
116
+ padding_mask=padding_mask,
117
+ output_attentions=False,
118
+ output_hidden_states=False,
119
+ )
120
+ hidden_states = outputs.last_hidden_state
121
+ feature_mask = self.audio_model._get_feature_vector_attention_mask(
122
+ hidden_states.size(1), padding_mask
123
+ ).to(device=hidden_states.device, dtype=torch.bool)
124
+ input_lengths = feature_mask.sum(dim=-1).to(torch.long)
125
+
126
+ return hidden_states, feature_mask, input_lengths
127
+
128
+ def encode_visual(
129
+ self,
130
+ pixel_values_videos: torch.Tensor,
131
+ padding_mask_videos: torch.Tensor | None = None,
132
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
133
+ batch_size, _, num_frames = pixel_values_videos.shape[:3]
134
+ if padding_mask_videos is None:
135
+ padding_mask_videos = torch.ones(
136
+ batch_size,
137
+ num_frames,
138
+ dtype=torch.long,
139
+ device=pixel_values_videos.device,
140
+ )
141
+
142
+ if padding_mask_videos.ndim != 2 or tuple(padding_mask_videos.shape) != (
143
+ batch_size,
144
+ num_frames,
145
+ ):
146
+ raise ValueError(
147
+ "padding_mask_videos must match pixel_values_videos on batch "
148
+ "and time axes."
149
+ )
150
+
151
+ outputs = self.visual_model.msp_visual.forward(
152
+ pixel_values_videos=pixel_values_videos,
153
+ padding_mask_videos=padding_mask_videos,
154
+ )
155
+ hidden_states = outputs.last_hidden_state
156
+ feature_mask = outputs.padding_mask_videos
157
+ if feature_mask is None:
158
+ feature_mask = torch.ones(
159
+ hidden_states.shape[:2],
160
+ dtype=torch.bool,
161
+ device=hidden_states.device,
162
+ )
163
+ feature_mask = feature_mask.to(device=hidden_states.device, dtype=torch.bool)
164
+ if tuple(feature_mask.shape) != tuple(hidden_states.shape[:2]):
165
+ raise ValueError(
166
+ "The visual encoder returned a padding mask that does not "
167
+ "match its hidden states."
168
+ )
169
+ input_lengths = feature_mask.sum(dim=-1).to(torch.long)
170
+ return hidden_states, feature_mask, input_lengths
171
+
172
+ def forward(
173
+ self,
174
+ input_values: torch.Tensor,
175
+ pixel_values_videos: torch.Tensor,
176
+ padding_mask: torch.Tensor | None = None,
177
+ padding_mask_videos: torch.Tensor | None = None,
178
+ **kwargs,
179
+ ) -> MSPModelOutput:
180
+
181
+ if input_values is None or pixel_values_videos is None:
182
+ raise ValueError("MSP requires synchronized audio and video inputs.")
183
+ audio_states, audio_mask, audio_lengths = self.encode_audio(
184
+ input_values, padding_mask
185
+ )
186
+ visual_states, visual_mask, visual_lengths = self.encode_visual(
187
+ pixel_values_videos, padding_mask_videos
188
+ )
189
+
190
+ fusion_output = self.fusion_model.forward(
191
+ audio_features=audio_states,
192
+ video_features=visual_states,
193
+ audio_mask=audio_mask,
194
+ video_mask=visual_mask,
195
+ **kwargs,
196
+ )
197
+
198
+ return MSPModelOutput(
199
+ last_hidden_state=fusion_output.last_hidden_state,
200
+ padding_mask=fusion_output.padding_mask,
201
+ audio_input_lengths=audio_lengths,
202
+ visual_input_lengths=visual_lengths,
203
+ audio_hidden_state=audio_states,
204
+ visual_hidden_state=visual_states,
205
+ cross_attentions=fusion_output.cross_attentions,
206
+ )
207
+
208
+
209
+ class MSPForCTC(MSPPreTrainedModel):
210
+ def __init__(self, config: MSPConfig):
211
+ super().__init__(config)
212
+
213
+ if config.vocab_size is None:
214
+ raise ValueError(
215
+ "vocab_size must be set in MSPConfig to instantiate MSPForCTC."
216
+ )
217
+
218
+ self.msp = MSPModel(config=config)
219
+ # lm head
220
+ self.dropout = nn.Dropout(config.final_dropout)
221
+ self.lm_head = nn.Linear(config.fusion_hidden_size, config.vocab_size)
222
+ self.post_init()
223
+
224
+ def freeze_feature_encoder(self):
225
+ self.msp.audio_model.freeze_feature_encoder()
226
+ self.msp.visual_model.freeze_feature_encoder()
227
+
228
+ def freeze_feature_encoders(self):
229
+ self.freeze_feature_encoder()
230
+
231
+ def freeze_base_model(self):
232
+ self.msp.audio_model.freeze_base_model()
233
+ self.msp.visual_model.freeze_base_model()
234
+
235
+ def freeze_audio_branch(self):
236
+ for param in self.msp.audio_model.parameters():
237
+ param.requires_grad = False
238
+
239
+ def freeze_visual_branch(self):
240
+ for param in self.msp.visual_model.parameters():
241
+ param.requires_grad = False
242
+
243
+ def forward(
244
+ self,
245
+ input_values: torch.Tensor| None = None,
246
+ pixel_values_videos: torch.Tensor | None = None,
247
+ padding_mask: torch.Tensor | None = None,
248
+ padding_mask_videos: torch.Tensor | None = None,
249
+ labels: torch.Tensor | None = None,
250
+ **kwargs,
251
+ ) -> MSPCTCOutput:
252
+ if not self.training:
253
+ if input_values is not None and pixel_values_videos is None:
254
+ outputs = self.msp.audio_model(
255
+ input_values = input_values,
256
+ padding_mask = padding_mask,
257
+ labels = labels
258
+ )
259
+ return MSPCTCOutput(
260
+ loss=outputs.loss,
261
+ logits=outputs.logits
262
+ )
263
+
264
+ if pixel_values_videos is not None and input_values is None:
265
+ outputs = self.msp.visual_model(
266
+ pixel_values_videos = pixel_values_videos,
267
+ padding_mask_videos = padding_mask_videos,
268
+ labels = labels
269
+ )
270
+ return MSPCTCOutput(
271
+ loss=outputs.loss,
272
+ logits=outputs.logits
273
+ )
274
+
275
+ if input_values is None or pixel_values_videos is None:
276
+ raise ValueError("MSPForCTC training requires both audio and video inputs.")
277
+
278
+ outputs = self.msp.forward(
279
+ input_values=input_values,
280
+ pixel_values_videos=pixel_values_videos,
281
+ padding_mask=padding_mask,
282
+ padding_mask_videos=padding_mask_videos,
283
+ )
284
+
285
+ hidden_states = self.dropout(outputs.last_hidden_state)
286
+ logits = self.lm_head(hidden_states)
287
+ input_lengths = outputs.padding_mask.sum(-1).long()
288
+
289
+ loss = msp_loss = audio_loss = visual_loss = None
290
+ audio_logits = visual_logits = None
291
+
292
+ if labels is not None and outputs.audio_hidden_state is not None:
293
+ audio_logits = self.msp.audio_model.lm_head(
294
+ self.msp.audio_model.dropout(outputs.audio_hidden_state)
295
+ )
296
+
297
+ if labels is not None and outputs.visual_hidden_state is not None:
298
+ visual_logits = self.msp.visual_model.lm_head(
299
+ self.msp.visual_model.dropout(outputs.visual_hidden_state)
300
+ )
301
+
302
+ if labels is not None:
303
+ valid_labels = labels[labels >= 0]
304
+ if valid_labels.numel() and valid_labels.max() >= self.config.vocab_size:
305
+ raise ValueError("A label id is outside the configured vocabulary.")
306
+ msp_loss = _compute_ctc_loss(
307
+ logits,
308
+ labels,
309
+ input_lengths,
310
+ self.config.pad_token_id,
311
+ self.config.ctc_loss_reduction,
312
+ self.config.ctc_zero_infinity,
313
+ )
314
+ loss = self.config.ctc_loss_msp_weight * msp_loss
315
+ # The pretrained branch heads are training-only deep supervision;
316
+ # audiovisual inference decodes the shared MSP head above.
317
+ if audio_logits is not None:
318
+ audio_loss = _compute_ctc_loss(
319
+ audio_logits,
320
+ labels,
321
+ outputs.audio_input_lengths,
322
+ self.config.pad_token_id,
323
+ self.config.ctc_loss_reduction,
324
+ self.config.ctc_zero_infinity,
325
+ )
326
+ loss = loss + self.config.ctc_loss_audio_weight * audio_loss
327
+ if visual_logits is not None:
328
+ visual_loss = _compute_ctc_loss(
329
+ visual_logits,
330
+ labels,
331
+ outputs.visual_input_lengths,
332
+ self.config.pad_token_id,
333
+ self.config.ctc_loss_reduction,
334
+ self.config.ctc_zero_infinity,
335
+ )
336
+ loss = loss + self.config.ctc_loss_visual_weight * visual_loss
337
+
338
+ return MSPCTCOutput(
339
+ loss=loss,
340
+ logits=logits,
341
+ )
modeling_msp_audio.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers import Wav2Vec2Model, Wav2Vec2PreTrainedModel
7
+ from transformers.utils import ModelOutput, logging
8
+
9
+ from .configuration_msp_audio import MSPAudioConfig
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+
14
+ @dataclass
15
+ class MSPAudioOutput(ModelOutput):
16
+ """
17
+ Output for MSPAudioForCTC.
18
+
19
+ Args:
20
+ loss: CTC loss (if labels provided).
21
+ logits: Raw per-frame log-softmax scores of shape (B, T, vocab_size).
22
+ hidden_states: Optional tuple of encoder hidden states.
23
+ attentions: Optional tuple of attention weights.
24
+ """
25
+
26
+ loss: torch.FloatTensor | None = None
27
+ logits: torch.FloatTensor = None
28
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
29
+ attentions: tuple[torch.FloatTensor, ...] | None = None
30
+
31
+
32
+ class MSPAudioPreTrainedModel(Wav2Vec2PreTrainedModel):
33
+ config_class = MSPAudioConfig
34
+ base_model_prefix = "msp_audio"
35
+ main_input_name = "input_values"
36
+ input_modalities = "audio"
37
+ all_tied_weights_keys = OrderedDict()
38
+
39
+
40
+ class MSPAudioModel(MSPAudioPreTrainedModel, Wav2Vec2Model):
41
+ """
42
+ Wav2Vec2 encoder wrapped as MSPAudioModel.
43
+ """
44
+
45
+ def __init__(self, config: MSPAudioConfig):
46
+ super().__init__(config)
47
+ self.config = config
48
+
49
+ @property
50
+ def dummy_inputs(self) -> dict:
51
+ return {
52
+ "input_values": torch.zeros(1, 16000, dtype=torch.float32),
53
+ "padding_mask": torch.ones(1, 16000, dtype=torch.long),
54
+ }
55
+
56
+ def forward(
57
+ self,
58
+ input_values: torch.Tensor | None,
59
+ padding_mask: torch.Tensor | None = None,
60
+ output_attentions: bool | None = None,
61
+ output_hidden_states: bool | None = None,
62
+ **kwargs,
63
+ ):
64
+ """
65
+ Args:
66
+ input_values: Raw waveform tensor of shape (B, T).
67
+ padding_mask: Boolean mask of shape (B, T); 1 = valid, 0 = padded.
68
+ output_attentions: Return attention weights if True.
69
+ output_hidden_states: Return all hidden states if True.
70
+
71
+ Returns:
72
+ Wav2Vec2BaseModelOutput with last_hidden_state of shape (B, T', D).
73
+ """
74
+ return super().forward(
75
+ input_values=input_values,
76
+ attention_mask=padding_mask,
77
+ output_attentions=output_attentions,
78
+ output_hidden_states=output_hidden_states,
79
+ )
80
+
81
+
82
+ class MSPAudioForCTC(MSPAudioPreTrainedModel):
83
+ def __init__(self, config: MSPAudioConfig):
84
+ super().__init__(config)
85
+
86
+ if config.vocab_size is None:
87
+ raise ValueError(
88
+ "vocab_size must be set in the config to instantiate MSPAudioForCTC."
89
+ )
90
+
91
+ self.msp_audio = MSPAudioModel(config)
92
+ self.dropout = nn.Dropout(config.final_dropout)
93
+
94
+ output_hidden_size = (
95
+ config.output_hidden_size if config.add_adapter else config.hidden_size
96
+ )
97
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
98
+
99
+ @property
100
+ def dummy_inputs(self) -> dict:
101
+ """Minimal inputs for model tracing."""
102
+ return {
103
+ "input_values": torch.zeros(1, 16000, dtype=torch.float32),
104
+ "padding_mask": torch.ones(1, 16000, dtype=torch.long),
105
+ }
106
+
107
+ def freeze_feature_encoder(self) -> None:
108
+ self.msp_audio.feature_extractor._freeze_parameters()
109
+
110
+ def freeze_base_model(self) -> None:
111
+ for param in self.msp_audio.parameters():
112
+ param.requires_grad = False
113
+
114
+ def forward(
115
+ self,
116
+ input_values: torch.Tensor | None,
117
+ padding_mask: torch.Tensor | None = None,
118
+ output_attentions: bool | None = None,
119
+ output_hidden_states: bool | None = None,
120
+ labels: torch.Tensor | None = None,
121
+ **kwargs,
122
+ ) -> MSPAudioOutput:
123
+ """
124
+ Args:
125
+ input_values: Raw waveform of shape (B, T).
126
+ padding_mask: Boolean mask of shape (B, T); 1 = valid frame.
127
+ output_attentions: Return attention weights.
128
+ output_hidden_states: Return all hidden states.
129
+ labels: Token ids of shape (B, L); -100 entries are ignored.
130
+
131
+ Returns:
132
+ MSPAudioOutput with loss (if labels given), logits, hidden_states,
133
+ and attentions.
134
+ """
135
+
136
+ if labels is not None and labels.max() >= self.config.vocab_size:
137
+ raise ValueError(
138
+ f"Label value {labels.max()} exceeds vocab_size={self.config.vocab_size}."
139
+ )
140
+
141
+ outputs = self.msp_audio(
142
+ input_values=input_values,
143
+ padding_mask=padding_mask,
144
+ output_attentions=output_attentions,
145
+ output_hidden_states=output_hidden_states,
146
+ )
147
+
148
+ hidden_states = self.dropout(outputs[0])
149
+ logits = self.lm_head(hidden_states) # (B, T', vocab_size)
150
+
151
+ loss = None
152
+ if labels is not None:
153
+ # Compute CTC input lengths from padding mask
154
+ padding_mask = (
155
+ padding_mask
156
+ if padding_mask is not None
157
+ else torch.ones_like(
158
+ input_values, dtype=torch.long, device=input_values.device
159
+ )
160
+ )
161
+ input_lengths = self._get_feat_extract_output_lengths(
162
+ padding_mask.sum(-1)
163
+ ).to(torch.long)
164
+
165
+ labels_mask = labels >= 0
166
+ target_lengths = labels_mask.sum(-1)
167
+ flattened_targets = labels.masked_select(labels_mask)
168
+
169
+ # ctc_loss doesn't support fp16
170
+ log_probs = nn.functional.log_softmax(
171
+ logits, dim=-1, dtype=torch.float32
172
+ ).transpose(0, 1) # (T', B, vocab_size)
173
+
174
+ with torch.backends.cudnn.flags(enabled=False):
175
+ loss = nn.functional.ctc_loss(
176
+ log_probs,
177
+ flattened_targets,
178
+ input_lengths,
179
+ target_lengths,
180
+ blank=self.config.pad_token_id,
181
+ reduction=self.config.ctc_loss_reduction,
182
+ zero_infinity=self.config.ctc_zero_infinity,
183
+ )
184
+
185
+ return MSPAudioOutput(
186
+ loss=loss,
187
+ logits=logits,
188
+ hidden_states=outputs.hidden_states,
189
+ attentions=outputs.attentions,
190
+ )
modeling_msp_visual.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from dataclasses import dataclass
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from transformers import PreTrainedModel
8
+ from transformers.modeling_outputs import CausalLMOutput
9
+ from transformers.utils import ModelOutput, logging
10
+
11
+ from .configuration_msp_visual import MSPVisualConfig
12
+ from .modeling_avhubert import AVHubertModel
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+
17
+ @dataclass
18
+ class MSPVisualOutput(ModelOutput):
19
+ last_hidden_state: Optional[torch.Tensor] = None
20
+ padding_mask_videos: Optional[torch.Tensor] = None
21
+ hidden_states: Optional[torch.Tensor] = None
22
+ attentions: Optional[torch.Tensor] = None
23
+
24
+
25
+ class MSPVisualPreTrainedModel(PreTrainedModel):
26
+ config_class = MSPVisualConfig
27
+ base_model_prefix = "msp_visual"
28
+ main_input_name = "pixel_values_videos"
29
+ input_modalities = "video"
30
+ supports_gradient_checkpointing = False
31
+ all_tied_weights_keys = OrderedDict()
32
+
33
+ def _init_weights(self, module):
34
+ if isinstance(module, nn.Linear):
35
+ module.weight.data.normal_(mean=0.0, std=0.02)
36
+ if module.bias is not None:
37
+ module.bias.data.zero_()
38
+ elif isinstance(module, nn.LayerNorm):
39
+ module.bias.data.zero_()
40
+ module.weight.data.fill_(1.0)
41
+
42
+
43
+ class MSPVisualModel(MSPVisualPreTrainedModel, AVHubertModel):
44
+ def __init__(self, config: MSPVisualConfig):
45
+ super().__init__(config.visual_config)
46
+ self.config = config.visual_config
47
+ self.feature_extractor_audio.requires_grad_(False)
48
+
49
+ @property
50
+ def dummy_inputs(self) -> dict:
51
+ return {
52
+ "pixel_values_videos": torch.zeros(1, 1, 10, 88, 88, dtype=torch.float32),
53
+ "padding_mask_videos": torch.ones(1, 10, dtype=torch.long),
54
+ }
55
+
56
+ def forward(
57
+ self,
58
+ pixel_values_videos: torch.Tensor | None = None,
59
+ padding_mask_videos: torch.Tensor | None = None,
60
+ **kwargs,
61
+ ) -> MSPVisualOutput:
62
+ # Public MSP masks consistently use 1/True for valid positions.
63
+ if padding_mask_videos is not None:
64
+ padding_mask_videos = padding_mask_videos.to(dtype=torch.bool)
65
+
66
+ feature, padding_mask = self.extract_finetune(
67
+ source={
68
+ "video": pixel_values_videos, # shape [batch_size, num_channels=1, num_frames, height, width]
69
+ "audio": None,
70
+ },
71
+ padding_mask=padding_mask_videos, # shape [batch_size, num_frames]
72
+ )
73
+
74
+ return MSPVisualOutput(
75
+ last_hidden_state=feature, # shape [batch_size, num_frames, hidden_size]
76
+ padding_mask_videos=padding_mask, # shape [batch_size, num_frames]
77
+ hidden_states=None,
78
+ attentions=None,
79
+ )
80
+
81
+
82
+ class MSPVisualForCTC(MSPVisualPreTrainedModel):
83
+ def __init__(self, config: MSPVisualConfig):
84
+ super().__init__(config)
85
+
86
+ if config.vocab_size is None:
87
+ raise ValueError(
88
+ "vocab_size must be set in MSPVisualConfig to instantiate MSPVisualForCTC."
89
+ )
90
+
91
+ self.msp_visual = MSPVisualModel(config)
92
+ for param in self.msp_visual.feature_extractor_audio.parameters():
93
+ param.requires_grad = False
94
+
95
+ self.dropout = nn.Dropout(config.final_dropout)
96
+ output_hidden_size = (
97
+ config.visual_config.adim
98
+ if hasattr(config.visual_config, "adim")
99
+ else config.visual_config.hidden_size
100
+ )
101
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
102
+
103
+ @property
104
+ def dummy_inputs(self) -> dict:
105
+ return {
106
+ "pixel_values_videos": torch.zeros(1, 1, 10, 88, 88, dtype=torch.float32),
107
+ "padding_mask_videos": torch.ones(1, 10, dtype=torch.long),
108
+ }
109
+
110
+ def freeze_feature_encoder(self) -> None:
111
+ for param in self.msp_visual.feature_extractor_video.parameters():
112
+ param.requires_grad = False
113
+ for param in self.msp_visual.feature_extractor_audio.parameters():
114
+ param.requires_grad = False
115
+
116
+ def freeze_base_model(self) -> None:
117
+ for param in self.msp_visual.parameters():
118
+ param.requires_grad = False
119
+
120
+ def forward(
121
+ self,
122
+ pixel_values_videos: torch.Tensor,
123
+ padding_mask_videos: torch.Tensor | None = None,
124
+ output_attentions: bool | None = None,
125
+ output_hidden_states: bool | None = None,
126
+ labels: torch.Tensor | None = None,
127
+ **kwargs,
128
+ ) -> CausalLMOutput:
129
+
130
+ if labels is not None:
131
+ valid_labels = labels[labels >= 0]
132
+ if (
133
+ valid_labels.numel() > 0
134
+ and valid_labels.max() >= self.config.vocab_size
135
+ ):
136
+ raise ValueError(
137
+ f"Label value {valid_labels.max()} >= "
138
+ f"vocab_size={self.config.vocab_size}."
139
+ )
140
+
141
+ outputs = self.msp_visual(
142
+ pixel_values_videos=pixel_values_videos,
143
+ padding_mask_videos=padding_mask_videos,
144
+ output_attentions=output_attentions,
145
+ output_hidden_states=output_hidden_states,
146
+ )
147
+
148
+ hidden_states = self.dropout(outputs.last_hidden_state)
149
+ padding_mask_videos = outputs.padding_mask_videos
150
+
151
+ logits = self.lm_head(hidden_states)
152
+
153
+ loss = None
154
+ if labels is not None:
155
+ if padding_mask_videos is not None:
156
+ input_lengths = (
157
+ padding_mask_videos.sum(-1)
158
+ .to(torch.long)
159
+ .to(pixel_values_videos.device)
160
+ )
161
+
162
+ else:
163
+ input_lengths = torch.full(
164
+ (pixel_values_videos.shape[0],),
165
+ pixel_values_videos.shape[2],
166
+ dtype=torch.long,
167
+ device=pixel_values_videos.device,
168
+ )
169
+
170
+ labels_mask = labels >= 0
171
+ target_lengths = labels_mask.sum(-1)
172
+ flattened_targets = labels.masked_select(labels_mask)
173
+
174
+ # ctc_loss doesn't support fp16
175
+ log_probs = nn.functional.log_softmax(
176
+ logits, dim=-1, dtype=torch.float32
177
+ ).transpose(0, 1)
178
+
179
+ with torch.backends.cudnn.flags(enabled=False):
180
+ loss = nn.functional.ctc_loss(
181
+ log_probs,
182
+ flattened_targets,
183
+ input_lengths,
184
+ target_lengths,
185
+ blank=self.config.pad_token_id,
186
+ reduction=self.config.ctc_loss_reduction,
187
+ zero_infinity=self.config.ctc_zero_infinity,
188
+ )
189
+
190
+ return CausalLMOutput(
191
+ loss=loss,
192
+ logits=logits,
193
+ hidden_states=outputs.hidden_states,
194
+ attentions=outputs.attentions,
195
+ )
resnet.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import math
3
+ from collections import OrderedDict
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def conv3x3(in_planes, out_planes, stride=1):
12
+ return nn.Conv2d(
13
+ in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
14
+ )
15
+
16
+
17
+ def downsample_basic_block(inplanes, outplanes, stride):
18
+ return nn.Sequential(
19
+ nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=stride, bias=False),
20
+ nn.BatchNorm2d(outplanes),
21
+ )
22
+
23
+
24
+ def downsample_basic_block_v2(inplanes, outplanes, stride):
25
+ return nn.Sequential(
26
+ nn.AvgPool2d(
27
+ kernel_size=stride, stride=stride, ceil_mode=True, count_include_pad=False
28
+ ),
29
+ nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=1, bias=False),
30
+ nn.BatchNorm2d(outplanes),
31
+ )
32
+
33
+
34
+ class BasicBlock(nn.Module):
35
+ expansion = 1
36
+
37
+ def __init__(self, inplanes, planes, stride=1, downsample=None, relu_type="relu"):
38
+ super(BasicBlock, self).__init__()
39
+
40
+ assert relu_type in ["relu", "prelu"]
41
+
42
+ self.conv1 = conv3x3(inplanes, planes, stride)
43
+ self.bn1 = nn.BatchNorm2d(planes)
44
+
45
+ if relu_type == "relu":
46
+ self.relu1 = nn.ReLU(inplace=True)
47
+ self.relu2 = nn.ReLU(inplace=True)
48
+ elif relu_type == "prelu":
49
+ self.relu1 = nn.PReLU(num_parameters=planes)
50
+ self.relu2 = nn.PReLU(num_parameters=planes)
51
+ else:
52
+ raise Exception("relu type not implemented")
53
+
54
+ self.conv2 = conv3x3(planes, planes)
55
+ self.bn2 = nn.BatchNorm2d(planes)
56
+
57
+ self.downsample = downsample
58
+ self.stride = stride
59
+
60
+ def forward(self, x):
61
+ residual = x
62
+ out = self.conv1(x)
63
+ out = self.bn1(out)
64
+ out = self.relu1(out)
65
+ out = self.conv2(out)
66
+ out = self.bn2(out)
67
+ if self.downsample is not None:
68
+ residual = self.downsample(x)
69
+
70
+ out += residual
71
+ out = self.relu2(out)
72
+
73
+ return out
74
+
75
+
76
+ class ResNet(nn.Module):
77
+ def __init__(
78
+ self,
79
+ block,
80
+ layers,
81
+ num_classes=1000,
82
+ relu_type="relu",
83
+ gamma_zero=False,
84
+ avg_pool_downsample=False,
85
+ ):
86
+ self.inplanes = 64
87
+ self.relu_type = relu_type
88
+ self.gamma_zero = gamma_zero
89
+ self.downsample_block = (
90
+ downsample_basic_block_v2 if avg_pool_downsample else downsample_basic_block
91
+ )
92
+
93
+ super(ResNet, self).__init__()
94
+ self.layer1 = self._make_layer(block, 64, layers[0])
95
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
96
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
97
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
98
+ self.avgpool = nn.AdaptiveAvgPool2d(1)
99
+
100
+ for m in self.modules():
101
+ if isinstance(m, nn.Conv2d):
102
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
103
+ m.weight.data.normal_(0, math.sqrt(2.0 / n))
104
+ elif isinstance(m, nn.BatchNorm2d):
105
+ m.weight.data.fill_(1)
106
+ m.bias.data.zero_()
107
+
108
+ if self.gamma_zero:
109
+ for m in self.modules():
110
+ if isinstance(m, BasicBlock):
111
+ m.bn2.weight.data.zero_()
112
+
113
+ def _make_layer(self, block, planes, blocks, stride=1):
114
+
115
+ downsample = None
116
+ if stride != 1 or self.inplanes != planes * block.expansion:
117
+ downsample = self.downsample_block(
118
+ inplanes=self.inplanes,
119
+ outplanes=planes * block.expansion,
120
+ stride=stride,
121
+ )
122
+
123
+ layers = []
124
+ layers.append(
125
+ block(self.inplanes, planes, stride, downsample, relu_type=self.relu_type)
126
+ )
127
+ self.inplanes = planes * block.expansion
128
+ for i in range(1, blocks):
129
+ layers.append(block(self.inplanes, planes, relu_type=self.relu_type))
130
+
131
+ return nn.Sequential(*layers)
132
+
133
+ def forward(self, x):
134
+ x = self.layer1(x)
135
+ x = self.layer2(x)
136
+ x = self.layer3(x)
137
+ x = self.layer4(x)
138
+ x = self.avgpool(x)
139
+ x = x.view(x.size(0), -1)
140
+ return x
141
+
142
+
143
+ class ResEncoder(nn.Module):
144
+ def __init__(self, relu_type, weights):
145
+ super(ResEncoder, self).__init__()
146
+ self.frontend_nout = 64
147
+ self.backend_out = 512
148
+ frontend_relu = (
149
+ nn.PReLU(num_parameters=self.frontend_nout)
150
+ if relu_type == "prelu"
151
+ else nn.ReLU()
152
+ )
153
+ self.frontend3D = nn.Sequential(
154
+ nn.Conv3d(
155
+ 1,
156
+ self.frontend_nout,
157
+ kernel_size=(5, 7, 7),
158
+ stride=(1, 2, 2),
159
+ padding=(2, 3, 3),
160
+ bias=False,
161
+ ),
162
+ nn.BatchNorm3d(self.frontend_nout),
163
+ frontend_relu,
164
+ nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1)),
165
+ )
166
+ self.trunk = ResNet(BasicBlock, [2, 2, 2, 2], relu_type=relu_type)
167
+ if weights is not None:
168
+ logger.info(f"Load {weights} for resnet")
169
+ std = torch.load(weights, map_location=torch.device("cpu"))[
170
+ "model_state_dict"
171
+ ]
172
+ frontend_std, trunk_std = OrderedDict(), OrderedDict()
173
+ for key, val in std.items():
174
+ new_key = ".".join(key.split(".")[1:])
175
+ if "frontend3D" in key:
176
+ frontend_std[new_key] = val
177
+ if "trunk" in key:
178
+ trunk_std[new_key] = val
179
+ self.frontend3D.load_state_dict(frontend_std)
180
+ self.trunk.load_state_dict(trunk_std)
181
+
182
+ def forward(self, x):
183
+ B, C, T, H, W = x.size()
184
+ x = self.frontend3D(x)
185
+ Tnew = x.shape[2]
186
+ x = self.threeD_to_2D_tensor(x)
187
+ x = self.trunk(x)
188
+ x = x.view(B, Tnew, x.size(1))
189
+ x = x.transpose(1, 2).contiguous()
190
+ return x
191
+
192
+ def threeD_to_2D_tensor(self, x):
193
+ n_batch, n_channels, s_time, sx, sy = x.shape
194
+ x = x.transpose(1, 2).contiguous()
195
+ return x.reshape(n_batch * s_time, n_channels, sx, sy)