Automatic Speech Recognition
Transformers
TensorBoard
Safetensors
msp_visual
Generated from Trainer
custom_code
Instructions to use MahmoodAnaam/MSP-Visual with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MahmoodAnaam/MSP-Visual with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("automatic-speech-recognition", model="MahmoodAnaam/MSP-Visual", trust_remote_code=True)# Load model directly from transformers import AutoModelForCTC model = AutoModelForCTC.from_pretrained("MahmoodAnaam/MSP-Visual", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
End of training
Browse files- README.md +80 -0
- configuration_avhubert.py +312 -0
- configuration_msp_visual.py +44 -0
- model.safetensors +1 -1
- modeling_avhubert.py +878 -0
- modeling_msp_visual.py +185 -0
- resnet.py +195 -0
- runs/Jul05_01-50-22_cdfd359d8cce/events.out.tfevents.1783250074.cdfd359d8cce.8290.1 +3 -0
README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags:
|
| 4 |
+
- generated_from_trainer
|
| 5 |
+
metrics:
|
| 6 |
+
- wer
|
| 7 |
+
model-index:
|
| 8 |
+
- name: MSP-Visual
|
| 9 |
+
results: []
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
| 13 |
+
should probably proofread and complete it, then remove this comment. -->
|
| 14 |
+
|
| 15 |
+
# MSP-Visual
|
| 16 |
+
|
| 17 |
+
This model is a fine-tuned version of [](https://huggingface.co/) on the None dataset.
|
| 18 |
+
It achieves the following results on the evaluation set:
|
| 19 |
+
- Loss: 1.3334
|
| 20 |
+
- Wer: 0.6493
|
| 21 |
+
- Cer: 0.3725
|
| 22 |
+
|
| 23 |
+
## Model description
|
| 24 |
+
|
| 25 |
+
More information needed
|
| 26 |
+
|
| 27 |
+
## Intended uses & limitations
|
| 28 |
+
|
| 29 |
+
More information needed
|
| 30 |
+
|
| 31 |
+
## Training and evaluation data
|
| 32 |
+
|
| 33 |
+
More information needed
|
| 34 |
+
|
| 35 |
+
## Training procedure
|
| 36 |
+
|
| 37 |
+
### Training hyperparameters
|
| 38 |
+
|
| 39 |
+
The following hyperparameters were used during training:
|
| 40 |
+
- learning_rate: 0.0001
|
| 41 |
+
- train_batch_size: 32
|
| 42 |
+
- eval_batch_size: 32
|
| 43 |
+
- seed: 42
|
| 44 |
+
- optimizer: Use OptimizerNames.ADAMW_TORCH_FUSED with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments
|
| 45 |
+
- lr_scheduler_type: cosine
|
| 46 |
+
- lr_scheduler_warmup_steps: 1000.0
|
| 47 |
+
- training_steps: 20000
|
| 48 |
+
|
| 49 |
+
### Training results
|
| 50 |
+
|
| 51 |
+
| Training Loss | Epoch | Step | Validation Loss | Wer | Cer |
|
| 52 |
+
|:-------------:|:-----:|:-----:|:---------------:|:------:|:------:|
|
| 53 |
+
| 2.5771 | 0.05 | 1000 | 2.3988 | 0.9791 | 0.6114 |
|
| 54 |
+
| 2.0987 | 0.1 | 2000 | 1.7770 | 0.8288 | 0.4786 |
|
| 55 |
+
| 1.9764 | 0.15 | 3000 | 1.6459 | 0.7827 | 0.4485 |
|
| 56 |
+
| 1.9493 | 0.2 | 4000 | 1.6139 | 0.7614 | 0.4388 |
|
| 57 |
+
| 1.9069 | 0.25 | 5000 | 1.5498 | 0.7351 | 0.4191 |
|
| 58 |
+
| 1.9144 | 0.3 | 6000 | 1.5212 | 0.7212 | 0.4142 |
|
| 59 |
+
| 1.8289 | 0.35 | 7000 | 1.4857 | 0.7139 | 0.4063 |
|
| 60 |
+
| 1.8845 | 0.4 | 8000 | 1.4832 | 0.6958 | 0.3979 |
|
| 61 |
+
| 1.7763 | 0.45 | 9000 | 1.4466 | 0.6938 | 0.3946 |
|
| 62 |
+
| 1.9370 | 0.5 | 10000 | 1.4235 | 0.6825 | 0.3916 |
|
| 63 |
+
| 1.7678 | 0.55 | 11000 | 1.4164 | 0.6784 | 0.3857 |
|
| 64 |
+
| 1.8403 | 0.6 | 12000 | 1.3981 | 0.6696 | 0.3868 |
|
| 65 |
+
| 1.6723 | 0.65 | 13000 | 1.3849 | 0.6631 | 0.3769 |
|
| 66 |
+
| 1.7040 | 0.7 | 14000 | 1.3884 | 0.6579 | 0.3763 |
|
| 67 |
+
| 1.5821 | 0.75 | 15000 | 1.3599 | 0.6588 | 0.3756 |
|
| 68 |
+
| 1.5721 | 0.8 | 16000 | 1.3480 | 0.6519 | 0.3728 |
|
| 69 |
+
| 1.6635 | 0.85 | 17000 | 1.3432 | 0.6527 | 0.3732 |
|
| 70 |
+
| 1.6557 | 0.9 | 18000 | 1.3501 | 0.6525 | 0.3748 |
|
| 71 |
+
| 1.7992 | 0.95 | 19000 | 1.3334 | 0.6493 | 0.3725 |
|
| 72 |
+
| 1.7090 | 1.0 | 20000 | 1.3328 | 0.6499 | 0.3724 |
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
### Framework versions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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_visual.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 1300783936
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:790a58a8b56daca254f2e8a4d25062fc165954d87ac278d8b51f7d7d8e9e6d4e
|
| 3 |
size 1300783936
|
modeling_avhubert.py
ADDED
|
@@ -0,0 +1,878 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
x = self.encoder(
|
| 712 |
+
x,
|
| 713 |
+
# padding_mask=padding_mask,
|
| 714 |
+
# layer=None if output_layer is None else output_layer - 1
|
| 715 |
+
)[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 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_visual.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, 10, 1, 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 |
+
feature, padding_mask = self.extract_finetune(
|
| 63 |
+
source={
|
| 64 |
+
"video": pixel_values_videos, # shape [batch_size, num_channels=1, num_frames, height, width]
|
| 65 |
+
"audio": None,
|
| 66 |
+
},
|
| 67 |
+
padding_mask=padding_mask_videos, # shape [batch_size, num_frames]
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
return MSPVisualOutput(
|
| 71 |
+
last_hidden_state=feature, # shape [batch_size, num_frames, hidden_size]
|
| 72 |
+
padding_mask_videos=padding_mask, # shape [batch_size, num_frames]
|
| 73 |
+
hidden_states=None,
|
| 74 |
+
attentions=None,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class MSPVisualForCTC(MSPVisualPreTrainedModel):
|
| 79 |
+
def __init__(self, config: MSPVisualConfig):
|
| 80 |
+
super().__init__(config)
|
| 81 |
+
|
| 82 |
+
if config.vocab_size is None:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
"vocab_size must be set in MSPVisualConfig to instantiate MSPVisualForCTC."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
self.msp_visual = MSPVisualModel(config)
|
| 88 |
+
for param in self.msp_visual.feature_extractor_audio.parameters():
|
| 89 |
+
param.requires_grad = False
|
| 90 |
+
|
| 91 |
+
self.dropout = nn.Dropout(config.final_dropout)
|
| 92 |
+
output_hidden_size = (
|
| 93 |
+
config.visual_config.adim
|
| 94 |
+
if hasattr(config.visual_config, "adim")
|
| 95 |
+
else config.visual_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 |
+
return {
|
| 102 |
+
"pixel_values_videos": torch.zeros(1, 10, 1, 88, 88, dtype=torch.float32),
|
| 103 |
+
"padding_mask_videos": torch.ones(1, 10, dtype=torch.long),
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
def freeze_feature_encoder(self) -> None:
|
| 107 |
+
for param in self.msp_visual.feature_extractor_video.parameters():
|
| 108 |
+
param.requires_grad = False
|
| 109 |
+
for param in self.msp_visual.feature_extractor_audio.parameters():
|
| 110 |
+
param.requires_grad = False
|
| 111 |
+
|
| 112 |
+
def freeze_base_model(self) -> None:
|
| 113 |
+
for param in self.msp_visual.parameters():
|
| 114 |
+
param.requires_grad = False
|
| 115 |
+
|
| 116 |
+
def forward(
|
| 117 |
+
self,
|
| 118 |
+
pixel_values_videos: torch.Tensor,
|
| 119 |
+
padding_mask_videos: torch.Tensor | None = None,
|
| 120 |
+
output_attentions: bool | None = None,
|
| 121 |
+
output_hidden_states: bool | None = None,
|
| 122 |
+
labels: torch.Tensor | None = None,
|
| 123 |
+
**kwargs,
|
| 124 |
+
) -> CausalLMOutput:
|
| 125 |
+
|
| 126 |
+
if labels is not None and labels.max() >= self.config.vocab_size:
|
| 127 |
+
raise ValueError(
|
| 128 |
+
f"Label value {labels.max()} >= vocab_size={self.config.vocab_size}."
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
outputs = self.msp_visual(
|
| 132 |
+
pixel_values_videos=pixel_values_videos,
|
| 133 |
+
padding_mask_videos=padding_mask_videos,
|
| 134 |
+
output_attentions=output_attentions,
|
| 135 |
+
output_hidden_states=output_hidden_states,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
hidden_states = self.dropout(outputs.last_hidden_state)
|
| 139 |
+
padding_mask_videos = outputs.padding_mask_videos
|
| 140 |
+
|
| 141 |
+
logits = self.lm_head(hidden_states)
|
| 142 |
+
|
| 143 |
+
loss = None
|
| 144 |
+
if labels is not None:
|
| 145 |
+
if padding_mask_videos is not None:
|
| 146 |
+
input_lengths = (
|
| 147 |
+
padding_mask_videos.sum(-1)
|
| 148 |
+
.to(torch.long)
|
| 149 |
+
.to(pixel_values_videos.device)
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
else:
|
| 153 |
+
input_lengths = torch.full(
|
| 154 |
+
(pixel_values_videos.shape[0],),
|
| 155 |
+
pixel_values_videos.shape[1],
|
| 156 |
+
dtype=torch.long,
|
| 157 |
+
device=pixel_values_videos.device,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
labels_mask = labels >= 0
|
| 161 |
+
target_lengths = labels_mask.sum(-1)
|
| 162 |
+
flattened_targets = labels.masked_select(labels_mask)
|
| 163 |
+
|
| 164 |
+
# ctc_loss doesn't support fp16
|
| 165 |
+
log_probs = nn.functional.log_softmax(
|
| 166 |
+
logits, dim=-1, dtype=torch.float32
|
| 167 |
+
).transpose(0, 1)
|
| 168 |
+
|
| 169 |
+
with torch.backends.cudnn.flags(enabled=False):
|
| 170 |
+
loss = nn.functional.ctc_loss(
|
| 171 |
+
log_probs,
|
| 172 |
+
flattened_targets,
|
| 173 |
+
input_lengths,
|
| 174 |
+
target_lengths,
|
| 175 |
+
blank=self.config.pad_token_id,
|
| 176 |
+
reduction=self.config.ctc_loss_reduction,
|
| 177 |
+
zero_infinity=self.config.ctc_zero_infinity,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
return CausalLMOutput(
|
| 181 |
+
loss=loss,
|
| 182 |
+
logits=logits,
|
| 183 |
+
hidden_states=outputs.hidden_states,
|
| 184 |
+
attentions=outputs.attentions,
|
| 185 |
+
)
|
resnet.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
runs/Jul05_01-50-22_cdfd359d8cce/events.out.tfevents.1783250074.cdfd359d8cce.8290.1
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e02eb359269c1faaa7232f38447f5ee7e6225f3bd3941caa623738539a5d1ce9
|
| 3 |
+
size 460
|