torchaudio 2.9.1__cp310-cp310-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. torchaudio/.dylibs/libc++.1.0.dylib +0 -0
  2. torchaudio/__init__.py +204 -0
  3. torchaudio/_extension/__init__.py +61 -0
  4. torchaudio/_extension/utils.py +133 -0
  5. torchaudio/_internal/__init__.py +10 -0
  6. torchaudio/_internal/module_utils.py +171 -0
  7. torchaudio/_torchcodec.py +340 -0
  8. torchaudio/compliance/__init__.py +5 -0
  9. torchaudio/compliance/kaldi.py +813 -0
  10. torchaudio/datasets/__init__.py +47 -0
  11. torchaudio/datasets/cmuarctic.py +157 -0
  12. torchaudio/datasets/cmudict.py +186 -0
  13. torchaudio/datasets/commonvoice.py +86 -0
  14. torchaudio/datasets/dr_vctk.py +121 -0
  15. torchaudio/datasets/fluentcommands.py +108 -0
  16. torchaudio/datasets/gtzan.py +1118 -0
  17. torchaudio/datasets/iemocap.py +147 -0
  18. torchaudio/datasets/librilight_limited.py +111 -0
  19. torchaudio/datasets/librimix.py +133 -0
  20. torchaudio/datasets/librispeech.py +174 -0
  21. torchaudio/datasets/librispeech_biasing.py +189 -0
  22. torchaudio/datasets/libritts.py +168 -0
  23. torchaudio/datasets/ljspeech.py +107 -0
  24. torchaudio/datasets/musdb_hq.py +139 -0
  25. torchaudio/datasets/quesst14.py +136 -0
  26. torchaudio/datasets/snips.py +157 -0
  27. torchaudio/datasets/speechcommands.py +183 -0
  28. torchaudio/datasets/tedlium.py +218 -0
  29. torchaudio/datasets/utils.py +54 -0
  30. torchaudio/datasets/vctk.py +143 -0
  31. torchaudio/datasets/voxceleb1.py +309 -0
  32. torchaudio/datasets/yesno.py +89 -0
  33. torchaudio/functional/__init__.py +130 -0
  34. torchaudio/functional/_alignment.py +128 -0
  35. torchaudio/functional/filtering.py +1685 -0
  36. torchaudio/functional/functional.py +2505 -0
  37. torchaudio/lib/__init__.py +0 -0
  38. torchaudio/lib/_torchaudio.so +0 -0
  39. torchaudio/lib/libtorchaudio.so +0 -0
  40. torchaudio/models/__init__.py +85 -0
  41. torchaudio/models/_hdemucs.py +1008 -0
  42. torchaudio/models/conformer.py +293 -0
  43. torchaudio/models/conv_tasnet.py +330 -0
  44. torchaudio/models/decoder/__init__.py +64 -0
  45. torchaudio/models/decoder/_ctc_decoder.py +568 -0
  46. torchaudio/models/decoder/_cuda_ctc_decoder.py +187 -0
  47. torchaudio/models/deepspeech.py +84 -0
  48. torchaudio/models/emformer.py +884 -0
  49. torchaudio/models/rnnt.py +816 -0
  50. torchaudio/models/rnnt_decoder.py +339 -0
  51. torchaudio/models/squim/__init__.py +11 -0
  52. torchaudio/models/squim/objective.py +326 -0
  53. torchaudio/models/squim/subjective.py +150 -0
  54. torchaudio/models/tacotron2.py +1046 -0
  55. torchaudio/models/wav2letter.py +72 -0
  56. torchaudio/models/wav2vec2/__init__.py +45 -0
  57. torchaudio/models/wav2vec2/components.py +1167 -0
  58. torchaudio/models/wav2vec2/model.py +1579 -0
  59. torchaudio/models/wav2vec2/utils/__init__.py +7 -0
  60. torchaudio/models/wav2vec2/utils/import_fairseq.py +213 -0
  61. torchaudio/models/wav2vec2/utils/import_huggingface.py +134 -0
  62. torchaudio/models/wav2vec2/wavlm_attention.py +214 -0
  63. torchaudio/models/wavernn.py +409 -0
  64. torchaudio/pipelines/__init__.py +102 -0
  65. torchaudio/pipelines/_source_separation_pipeline.py +109 -0
  66. torchaudio/pipelines/_squim_pipeline.py +156 -0
  67. torchaudio/pipelines/_tts/__init__.py +16 -0
  68. torchaudio/pipelines/_tts/impl.py +385 -0
  69. torchaudio/pipelines/_tts/interface.py +255 -0
  70. torchaudio/pipelines/_tts/utils.py +230 -0
  71. torchaudio/pipelines/_wav2vec2/__init__.py +0 -0
  72. torchaudio/pipelines/_wav2vec2/aligner.py +87 -0
  73. torchaudio/pipelines/_wav2vec2/impl.py +1699 -0
  74. torchaudio/pipelines/_wav2vec2/utils.py +346 -0
  75. torchaudio/pipelines/rnnt_pipeline.py +380 -0
  76. torchaudio/transforms/__init__.py +78 -0
  77. torchaudio/transforms/_multi_channel.py +467 -0
  78. torchaudio/transforms/_transforms.py +2138 -0
  79. torchaudio/utils/__init__.py +4 -0
  80. torchaudio/utils/download.py +89 -0
  81. torchaudio/version.py +2 -0
  82. torchaudio-2.9.1.dist-info/METADATA +133 -0
  83. torchaudio-2.9.1.dist-info/RECORD +86 -0
  84. torchaudio-2.9.1.dist-info/WHEEL +5 -0
  85. torchaudio-2.9.1.dist-info/licenses/LICENSE +25 -0
  86. torchaudio-2.9.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,7 @@
1
+ from .import_fairseq import import_fairseq_model
2
+ from .import_huggingface import import_huggingface_model
3
+
4
+ __all__ = [
5
+ "import_huggingface_model",
6
+ "import_fairseq_model",
7
+ ]
@@ -0,0 +1,213 @@
1
+ """Import fariseq's wav2vec2.0 pretrained weights to torchaudios's format.
2
+
3
+ For this module to work, you need `fairseq`.
4
+ """
5
+ import re
6
+
7
+ from torch.nn import Module
8
+
9
+ from ..model import wav2vec2_model, Wav2Vec2Model
10
+
11
+
12
+ def _parse_config(w2v_model):
13
+ encoder = w2v_model.encoder
14
+ conv_layers = w2v_model.feature_extractor.conv_layers
15
+
16
+ extractor_mode = "layer_norm"
17
+ if "GroupNorm" in conv_layers[0][2].__class__.__name__:
18
+ extractor_mode = "group_norm"
19
+ else:
20
+ extractor_mode = "layer_norm"
21
+
22
+ conv_layer_config = [(l[0].out_channels, l[0].kernel_size[0], l[0].stride[0]) for l in conv_layers]
23
+
24
+ if all(l[0].bias is None for l in conv_layers):
25
+ conv_bias = False
26
+ elif all(l[0].bias is not None for l in conv_layers):
27
+ conv_bias = True
28
+ else:
29
+ raise ValueError("Either all the convolutions layers have bias term or none of them should.")
30
+
31
+ config = {
32
+ "extractor_mode": extractor_mode,
33
+ "extractor_conv_layer_config": conv_layer_config,
34
+ "extractor_conv_bias": conv_bias,
35
+ "encoder_embed_dim": w2v_model.post_extract_proj.out_features,
36
+ "encoder_projection_dropout": w2v_model.dropout_input.p,
37
+ "encoder_pos_conv_kernel": encoder.pos_conv[0].kernel_size[0],
38
+ "encoder_pos_conv_groups": encoder.pos_conv[0].groups,
39
+ "encoder_num_layers": len(encoder.layers),
40
+ "encoder_num_heads": encoder.layers[0].self_attn.num_heads,
41
+ "encoder_attention_dropout": encoder.layers[0].self_attn.dropout_module.p,
42
+ "encoder_ff_interm_features": encoder.layers[0].fc1.out_features,
43
+ "encoder_ff_interm_dropout": encoder.layers[0].dropout2.p,
44
+ "encoder_dropout": encoder.layers[0].dropout3.p,
45
+ "encoder_layer_norm_first": encoder.layer_norm_first,
46
+ "encoder_layer_drop": encoder.layerdrop,
47
+ }
48
+ return config
49
+
50
+
51
+ def _map_key(key):
52
+ key_ = key
53
+ if key.startswith("w2v_model."):
54
+ key = key.replace("w2v_model.", "")
55
+ if re.match(r"(mask_emb|quantizer|project_q|final_proj|mask_emb)", key):
56
+ return None
57
+ # Feature Extractor
58
+ # Group norm when "extractor_mode" is "default".
59
+ # (Only the first layer)
60
+ # "conv_layers.0.2.weight" -> "conv_layers.0.layer_norm.weight"
61
+ # "conv_layers.0.2.bias" -> "conv_layers.0.layer_norm.bias"
62
+ match = re.match(r"feature_extractor\.conv_layers\.0\.2\.(weight|bias)", key)
63
+ if match:
64
+ return f"feature_extractor.conv_layers.0.layer_norm.{match.group(1)}"
65
+ # Convolutions
66
+ # "conv_layers.X.0.weight" -> "conv_layers.X.conv.weight"
67
+ # "conv_layers.X.0.bias" -> "conv_layers.X.conv.bias"
68
+ match = re.match(r"feature_extractor\.conv_layers\.(\d+)\.0\.(weight|bias)", key)
69
+ if match:
70
+ return f"feature_extractor.conv_layers.{match.group(1)}.conv.{match.group(2)}"
71
+ # Layer norm when "extractor_mode" is "layer_norm".
72
+ # "conv_layers.X.2.1.weight" -> "conv_layers.X.layer_norm.weight"
73
+ # "conv_layers.X.2.1.bias" -> "conv_layers.X.layer_norm.bias"
74
+ match = re.match(r"feature_extractor\.conv_layers\.(\d+)\.2\.1\.(weight|bias)", key)
75
+ if match:
76
+ return f"feature_extractor.conv_layers.{match.group(1)}.layer_norm.{match.group(2)}"
77
+ match = re.match(r"post_extract_proj\.(weight|bias)", key)
78
+ # Encoder - Feature projection
79
+ if match:
80
+ return f"encoder.feature_projection.projection.{match.group(1)}"
81
+ match = re.match(r"layer_norm\.(weight|bias)", key)
82
+ if match:
83
+ return f"encoder.feature_projection.layer_norm.{match.group(1)}"
84
+ # Encoder - Transformer - Convolutional positional embedding
85
+ match = re.match(r"encoder\.pos_conv\.0\.(bias|weight_g|weight_v)", key)
86
+ if match:
87
+ return f"encoder.transformer.pos_conv_embed.conv.{match.group(1)}"
88
+ match = re.match(r"encoder\.layer_norm\.(weight|bias)", key)
89
+ if match:
90
+ return f"encoder.transformer.layer_norm.{match.group(1)}"
91
+ # Encoder - Transformer - Self attention layers
92
+ match = re.match(r"encoder\.layers\.(\d+)\.self_attn\.((k_|v_|q_|out_)proj\.(weight|bias))", key)
93
+ if match:
94
+ return f"encoder.transformer.layers.{match.group(1)}.attention.{match.group(2)}"
95
+ match = re.match(r"encoder\.layers\.(\d+)\.self_attn_layer_norm\.(weight|bias)", key)
96
+ if match:
97
+ return f"encoder.transformer.layers.{match.group(1)}.layer_norm.{match.group(2)}"
98
+ match = re.match(r"encoder\.layers\.(\d+)\.fc1\.(weight|bias)", key)
99
+ if match:
100
+ return f"encoder.transformer.layers.{match.group(1)}.feed_forward.intermediate_dense.{match.group(2)}"
101
+ match = re.match(r"encoder\.layers\.(\d+)\.fc2\.(weight|bias)", key)
102
+ if match:
103
+ return f"encoder.transformer.layers.{match.group(1)}.feed_forward.output_dense.{match.group(2)}"
104
+ match = re.match(r"encoder\.layers\.(\d+)\.final_layer_norm\.(weight|bias)", key)
105
+ if match:
106
+ return f"encoder.transformer.layers.{match.group(1)}.final_layer_norm.{match.group(2)}"
107
+ match = re.match(r"proj\.(weight|bias)", key)
108
+ # Auxiliary Module
109
+ # Only relevant when loading fine-tuned models
110
+ if match:
111
+ return f"aux.{match.group(1)}"
112
+ # HuBERT Extension
113
+ if key in ["label_embs_concat"]:
114
+ return key
115
+ raise ValueError(f"Unexpected key: {key_}")
116
+
117
+
118
+ def _convert_state_dict(state_dict):
119
+ converted = {}
120
+ for k, v in state_dict.items():
121
+ k = _map_key(k)
122
+ if k is not None:
123
+ converted[k] = v
124
+ return converted
125
+
126
+
127
+ def import_fairseq_model(original: Module) -> Wav2Vec2Model:
128
+ """Builds :class:`Wav2Vec2Model` from the corresponding model object of
129
+ `fairseq <https://github.com/pytorch/fairseq>`_.
130
+
131
+ Args:
132
+ original (torch.nn.Module):
133
+ An instance of fairseq's Wav2Vec2.0 or HuBERT model.
134
+ One of ``fairseq.models.wav2vec.wav2vec2_asr.Wav2VecEncoder``,
135
+ ``fairseq.models.wav2vec.wav2vec2.Wav2Vec2Model`` or
136
+ ``fairseq.models.hubert.hubert_asr.HubertEncoder``.
137
+
138
+ Returns:
139
+ Wav2Vec2Model: Imported model.
140
+
141
+ Example - Loading pretrain-only model
142
+ >>> from torchaudio.models.wav2vec2.utils import import_fairseq_model
143
+ >>>
144
+ >>> # Load model using fairseq
145
+ >>> model_file = 'wav2vec_small.pt'
146
+ >>> model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task([model_file])
147
+ >>> original = model[0]
148
+ >>> imported = import_fairseq_model(original)
149
+ >>>
150
+ >>> # Perform feature extraction
151
+ >>> waveform, _ = torchaudio.load('audio.wav')
152
+ >>> features, _ = imported.extract_features(waveform)
153
+ >>>
154
+ >>> # Compare result with the original model from fairseq
155
+ >>> reference = original.feature_extractor(waveform).transpose(1, 2)
156
+ >>> torch.testing.assert_allclose(features, reference)
157
+
158
+ Example - Fine-tuned model
159
+ >>> from torchaudio.models.wav2vec2.utils import import_fairseq_model
160
+ >>>
161
+ >>> # Load model using fairseq
162
+ >>> model_file = 'wav2vec_small_960h.pt'
163
+ >>> model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task([model_file])
164
+ >>> original = model[0]
165
+ >>> imported = import_fairseq_model(original.w2v_encoder)
166
+ >>>
167
+ >>> # Perform encoding
168
+ >>> waveform, _ = torchaudio.load('audio.wav')
169
+ >>> emission, _ = imported(waveform)
170
+ >>>
171
+ >>> # Compare result with the original model from fairseq
172
+ >>> mask = torch.zeros_like(waveform)
173
+ >>> reference = original(waveform, mask)['encoder_out'].transpose(0, 1)
174
+ >>> torch.testing.assert_allclose(emission, reference)
175
+ """
176
+ class_ = original.__class__.__name__
177
+ if class_ == "Wav2Vec2Model":
178
+ return _import_wav2vec2_pretraining(original)
179
+ if class_ == "Wav2VecEncoder":
180
+ return _import_wav2vec2_finetuning(original)
181
+ if class_ == "HubertModel":
182
+ return _import_hubert_pretraining(original)
183
+ if class_ == "HubertEncoder":
184
+ return _import_hubert_finetuning(original)
185
+ raise ValueError(f"Expected an instance of `Wav2Vec2Model` or `Wav2VecEncoder`. Found: {class_}")
186
+
187
+
188
+ def _import_wav2vec2_finetuning(original: Module) -> Wav2Vec2Model:
189
+ config = _parse_config(original.w2v_model)
190
+ model = wav2vec2_model(**config, aux_num_out=original.proj.out_features)
191
+ model.load_state_dict(_convert_state_dict(original.state_dict()))
192
+ return model
193
+
194
+
195
+ def _import_wav2vec2_pretraining(original: Module) -> Wav2Vec2Model:
196
+ config = _parse_config(original)
197
+ model = wav2vec2_model(**config, aux_num_out=None)
198
+ model.load_state_dict(_convert_state_dict(original.state_dict()), strict=False)
199
+ return model
200
+
201
+
202
+ def _import_hubert_finetuning(original: Module) -> Wav2Vec2Model:
203
+ config = _parse_config(original.w2v_model)
204
+ model = wav2vec2_model(**config, aux_num_out=original.proj.out_features)
205
+ model.load_state_dict(_convert_state_dict(original.state_dict()), strict=False)
206
+ return model
207
+
208
+
209
+ def _import_hubert_pretraining(original: Module) -> Wav2Vec2Model:
210
+ config = _parse_config(original)
211
+ model = wav2vec2_model(**config, aux_num_out=None)
212
+ model.load_state_dict(_convert_state_dict(original.state_dict()), strict=False)
213
+ return model
@@ -0,0 +1,134 @@
1
+ """Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format.
2
+ """
3
+ import logging
4
+ from typing import Any, Dict
5
+
6
+ import torch
7
+ from torch.nn import Module
8
+
9
+ from ..model import wav2vec2_model, Wav2Vec2Model, wavlm_model
10
+
11
+ _LG = logging.getLogger(__name__)
12
+
13
+
14
+ def _get_config(cfg):
15
+ config = {
16
+ "extractor_mode": f"{cfg.feat_extract_norm}_norm",
17
+ "extractor_conv_layer_config": list(zip(cfg.conv_dim, cfg.conv_kernel, cfg.conv_stride)),
18
+ "extractor_conv_bias": cfg.conv_bias,
19
+ "encoder_embed_dim": cfg.hidden_size,
20
+ "encoder_projection_dropout": cfg.feat_proj_dropout,
21
+ "encoder_pos_conv_kernel": cfg.num_conv_pos_embeddings,
22
+ "encoder_pos_conv_groups": cfg.num_conv_pos_embedding_groups,
23
+ "encoder_num_layers": cfg.num_hidden_layers,
24
+ "encoder_num_heads": cfg.num_attention_heads,
25
+ "encoder_attention_dropout": cfg.attention_dropout,
26
+ "encoder_ff_interm_features": cfg.intermediate_size,
27
+ "encoder_ff_interm_dropout": cfg.activation_dropout,
28
+ "encoder_dropout": cfg.hidden_dropout,
29
+ "encoder_layer_norm_first": cfg.do_stable_layer_norm,
30
+ "encoder_layer_drop": cfg.layerdrop,
31
+ }
32
+ return config
33
+
34
+
35
+ def _get_config_wavlm(cfg):
36
+ config = {
37
+ "extractor_mode": f"{cfg.feat_extract_norm}_norm",
38
+ "extractor_conv_layer_config": list(zip(cfg.conv_dim, cfg.conv_kernel, cfg.conv_stride)),
39
+ "extractor_conv_bias": cfg.conv_bias,
40
+ "encoder_embed_dim": cfg.hidden_size,
41
+ "encoder_projection_dropout": cfg.feat_proj_dropout,
42
+ "encoder_pos_conv_kernel": cfg.num_conv_pos_embeddings,
43
+ "encoder_pos_conv_groups": cfg.num_conv_pos_embedding_groups,
44
+ "encoder_num_layers": cfg.num_hidden_layers,
45
+ "encoder_num_heads": cfg.num_attention_heads,
46
+ "encoder_num_buckets": cfg.num_buckets,
47
+ "encoder_max_distance": cfg.max_bucket_distance,
48
+ "encoder_attention_dropout": cfg.attention_dropout,
49
+ "encoder_ff_interm_features": cfg.intermediate_size,
50
+ "encoder_ff_interm_dropout": cfg.activation_dropout,
51
+ "encoder_dropout": cfg.hidden_dropout,
52
+ "encoder_layer_norm_first": cfg.do_stable_layer_norm,
53
+ "encoder_layer_drop": cfg.layerdrop,
54
+ }
55
+ return config
56
+
57
+
58
+ def _build(config, original):
59
+ is_for_ctc = original.__class__.__name__ in ["Wav2Vec2ForCTC", "WavLMForCTC"]
60
+ if is_for_ctc:
61
+ aux_num_out = original.config.vocab_size
62
+ wav2vec2 = original.wav2vec2
63
+ else:
64
+ _LG.warning(
65
+ "The model is not an instance of Wav2Vec2ForCTC or WavLMForCTC. " '"lm_head" module is not imported.'
66
+ )
67
+ aux_num_out = None
68
+ wav2vec2 = original
69
+ is_wavlm = original.__class__.__name__ in ["WavLMModel", "WavLMForCTC"]
70
+ if is_wavlm:
71
+ imported = wavlm_model(**config, aux_num_out=aux_num_out)
72
+ else:
73
+ imported = wav2vec2_model(**config, aux_num_out=aux_num_out)
74
+ imported.feature_extractor.load_state_dict(wav2vec2.feature_extractor.state_dict())
75
+ imported.encoder.feature_projection.load_state_dict(wav2vec2.feature_projection.state_dict())
76
+ encoder_state_dict = wav2vec2.encoder.state_dict()
77
+ if is_wavlm: # Rename paramaters of linear transformations for compatibility with the HF model
78
+ transform_wavlm_encoder_state(encoder_state_dict, config["encoder_num_layers"])
79
+ imported.encoder.transformer.load_state_dict(encoder_state_dict)
80
+ if is_for_ctc:
81
+ imported.aux.load_state_dict(original.lm_head.state_dict())
82
+ return imported
83
+
84
+
85
+ def transform_wavlm_encoder_state(state: Dict[str, Any], encoder_num_layers: int):
86
+ """Converts WavLM encoder state from HuggingFace format. In particular, concatenates linear projection weights and
87
+ biases to align with the structure of ``torch.nn.MultiheadAttention``.
88
+ """
89
+ for i in range(encoder_num_layers):
90
+ q_proj_bias = state.pop(f"layers.{i}.attention.q_proj.bias")
91
+ k_proj_bias = state.pop(f"layers.{i}.attention.k_proj.bias")
92
+ v_proj_bias = state.pop(f"layers.{i}.attention.v_proj.bias")
93
+ q_proj_weight = state.pop(f"layers.{i}.attention.q_proj.weight")
94
+ k_proj_weight = state.pop(f"layers.{i}.attention.k_proj.weight")
95
+ v_proj_weight = state.pop(f"layers.{i}.attention.v_proj.weight")
96
+ state[f"layers.{i}.attention.attention.in_proj_bias"] = torch.cat((q_proj_bias, k_proj_bias, v_proj_bias))
97
+ state[f"layers.{i}.attention.attention.in_proj_weight"] = torch.cat(
98
+ (q_proj_weight, k_proj_weight, v_proj_weight)
99
+ )
100
+
101
+ state[f"layers.{i}.attention.attention.out_proj.weight"] = state.pop(f"layers.{i}.attention.out_proj.weight")
102
+ state[f"layers.{i}.attention.attention.out_proj.bias"] = state.pop(f"layers.{i}.attention.out_proj.bias")
103
+
104
+
105
+ def import_huggingface_model(original: Module) -> Wav2Vec2Model:
106
+ """Builds :class:`Wav2Vec2Model` from the corresponding model object of
107
+ `Transformers <https://huggingface.co/transformers/>`_.
108
+
109
+ Args:
110
+ original (torch.nn.Module): An instance of ``Wav2Vec2ForCTC`` from ``transformers``.
111
+
112
+ Returns:
113
+ Wav2Vec2Model: Imported model.
114
+
115
+ Example
116
+ >>> from torchaudio.models.wav2vec2.utils import import_huggingface_model
117
+ >>>
118
+ >>> original = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
119
+ >>> model = import_huggingface_model(original)
120
+ >>>
121
+ >>> waveforms, _ = torchaudio.load("audio.wav")
122
+ >>> logits, _ = model(waveforms)
123
+ """
124
+ _LG.info("Importing model.")
125
+ _LG.info("Loading model configuration.")
126
+ is_wavlm = original.__class__.__name__ in ["WavLMModel", "WavLMForCTC"]
127
+ if is_wavlm:
128
+ config = _get_config_wavlm(original.config)
129
+ else:
130
+ config = _get_config(original.config)
131
+ _LG.debug(" - config: %s", config)
132
+ _LG.info("Building model.")
133
+ imported = _build(config, original)
134
+ return imported
@@ -0,0 +1,214 @@
1
+ """
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) Microsoft Corporation
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ """
24
+
25
+ import math
26
+ from typing import Optional, Tuple
27
+
28
+ import torch
29
+ from torch import nn, Tensor
30
+
31
+
32
+ class WavLMSelfAttention(nn.Module):
33
+ """Multi-headed self-attention for WavLM model :cite:`chen2022wavlm`.
34
+ Wraps around ``torch.nn.MultiheadAttention``, creating relaive position embeddings and passing them to multi-headed
35
+ attention as a mask.
36
+ Source: https://github.com/microsoft/unilm/blob/2d8302f09c99bca2b82e6e868d81d4281cceebc8/wavlm/modules.py#L303-L763
37
+
38
+ Args:
39
+ embed_dim (int): Total dimension of the model.
40
+ num_heads (int): The number of heads.
41
+ dropout (float, optional): Dropout probability on attn_output_weights. (Default: to ``0.0``)
42
+ bias (bool, optional): If ``True``, add bias to input / output projection layers. (Default: ``True``)
43
+ has_relative_attention_bias (bool, optional): If ``True``, apply relative position embedding.
44
+ Necessary in the first encoder layer, but not in the subsequent ones. (Default: ``False``)
45
+ num_buckets (int, optional): Number of buckets for relative position embedding. (Default: ``32``)
46
+ max_distance (int, optional): Naximum distance for relative position embedding. (Default: ``128``)
47
+ gru_rel_pos (bool, optional): If ``True``, apply gated relative position embedding. (Default: ``False``)
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ embed_dim: int,
53
+ num_heads: int,
54
+ dropout: float = 0.0,
55
+ bias: bool = True,
56
+ has_relative_attention_bias: bool = False,
57
+ num_buckets: int = 32,
58
+ max_distance: int = 128,
59
+ gru_rel_pos: bool = True,
60
+ ):
61
+ super().__init__()
62
+ self.embed_dim = embed_dim
63
+ self.num_heads = num_heads
64
+ self.has_relative_attention_bias = has_relative_attention_bias
65
+ self.num_buckets = num_buckets
66
+ self.max_distance = max_distance
67
+
68
+ if has_relative_attention_bias:
69
+ self.rel_attn_embed = nn.Embedding(num_buckets, num_heads)
70
+ else:
71
+ self.rel_attn_embed = None
72
+
73
+ self.head_dim = embed_dim // num_heads
74
+ assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
75
+
76
+ self.dropout = dropout
77
+ self.attention = nn.MultiheadAttention(embed_dim, num_heads, dropout=dropout, bias=bias, batch_first=True)
78
+
79
+ self.gru_rel_pos = gru_rel_pos
80
+ if self.gru_rel_pos:
81
+ self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)
82
+ self.gru_rel_pos_const = nn.Parameter(torch.ones(1, num_heads, 1, 1))
83
+ self.has_position_bias = True
84
+
85
+ def compute_bias(self, query_length: int, key_length: int) -> Tensor:
86
+ """Compute relative position embeddings for WavLM model.
87
+ Args:
88
+ query_length (int): Query position can take values between 0 and ``query_length - 1``.
89
+ key_length (int): Key position can take values between 0 and ``key_length - 1``.
90
+ Returns:
91
+ Tensor of shape `(num_heads, query_length, key_length)`, relative positions embeddings
92
+ """
93
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
94
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
95
+ relative_position = memory_position - context_position # Shape (query_length, key_length)
96
+ relative_position_bucket = self._relative_positions_bucket(relative_position, bidirectional=True)
97
+ relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)
98
+ values = self.rel_attn_embed(relative_position_bucket) # Shape (query_length, key_length, num_heads)
99
+ values = values.permute([2, 0, 1])
100
+ return values
101
+
102
+ def _relative_positions_bucket(self, relative_positions: Tensor, bidirectional: bool = True):
103
+ """Compute relative position buckets for WavLM model. Computation similar to formula (5) in WavLM
104
+ paper :cite:`chen2022wavlm`.
105
+ Args:
106
+ relative_positions (Tensor): Relative offsets between query and key positions,
107
+ of shape ``(query_length, key_length)``.
108
+ bidirectional (bool): If ``True``, values will be filled both above and below the diagonal in the resulting
109
+ matrix. If ``False``, the elements above the diagonal (i.e. with negative relative offsets) will be set
110
+ to zero. (Default ``True``)
111
+ Returns:
112
+ Tensor of shape ``(query_length, key_length)`` filled bucketed values of with relative positions.
113
+ """
114
+ num_buckets = self.num_buckets
115
+ max_distance = self.max_distance
116
+ # Shape (query_length, key_length)
117
+ relative_buckets = torch.zeros_like(relative_positions, dtype=torch.long)
118
+
119
+ if bidirectional:
120
+ num_buckets = num_buckets // 2
121
+ relative_buckets += (relative_positions > 0).to(torch.long) * num_buckets
122
+ relative_positions = torch.abs(relative_positions)
123
+ else:
124
+ relative_positions = -torch.min(relative_positions, torch.zeros_like(relative_positions))
125
+
126
+ max_exact = num_buckets // 2
127
+ is_small = relative_positions < max_exact
128
+
129
+ relative_postion_if_large = max_exact + (
130
+ torch.log(relative_positions.float() / max_exact)
131
+ / math.log(max_distance / max_exact)
132
+ * (num_buckets - max_exact)
133
+ ).to(torch.long)
134
+ relative_postion_if_large = torch.min(
135
+ relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1)
136
+ )
137
+
138
+ relative_buckets += torch.where(is_small, relative_positions, relative_postion_if_large)
139
+ return relative_buckets
140
+
141
+ def forward(
142
+ self,
143
+ query: Tensor,
144
+ key_padding_mask: Optional[Tensor] = None,
145
+ attention_mask: Optional[Tensor] = None,
146
+ position_bias: Optional[Tensor] = None,
147
+ ) -> Tuple[Tensor, Optional[Tensor]]:
148
+ """
149
+ Args:
150
+ query (Tensor): Input of shape ``(batch_size, src_len, embed_dim)``.
151
+ key_padding_mask (Tensor or None, optional): Mask to exclude keys that are pads, of shape
152
+ `(batch, src_len)`, where padding elements are indicated by 1s. (Default: ``None``)
153
+ attn_mask: Needs to be ``None``. The argument exists for compatibility with
154
+ ``EncoderLayer``. (Default: ``None``)
155
+ position_bias (Tensor or None, optional): Position bias of shape
156
+ ``(batch_size * num_heads, src_len, src_len)``. When used inside WavLM model encoder, will be
157
+ generated in the first layer and then passed from each encoder layer to the next one.
158
+ (Default: ``None``)
159
+ Returns:
160
+ attn_output (Tensor): Attention output of shape ``(batch_size, src_len, embed_dim)``.
161
+ position_bias (Tensor or None): Position bias of shape ``(batch_size * num_heads, src_len, src_len)``.
162
+ """
163
+ bsz, seq_len, embed_dim = query.size()
164
+ assert embed_dim == self.embed_dim
165
+ assert attention_mask is None
166
+
167
+ if self.rel_attn_embed is not None and position_bias is None:
168
+ position_bias = self.compute_bias(seq_len, seq_len)
169
+ position_bias = position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1)
170
+
171
+ attn_mask_rel_pos: Optional[Tensor] = None
172
+ if position_bias is not None:
173
+ attn_mask_rel_pos = position_bias
174
+ if self.gru_rel_pos: # Apply gating on relative position bias
175
+ query_layer = query.view(bsz, seq_len, self.num_heads, -1)
176
+ query_layer = query_layer.permute(0, 2, 1, 3)
177
+
178
+ gate_a, gate_b = torch.sigmoid(
179
+ self.gru_rel_pos_linear(query_layer).view(bsz, self.num_heads, seq_len, 2, 4).sum(-1, keepdim=False)
180
+ ).chunk(2, dim=-1)
181
+ gate_a_1 = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0
182
+ attn_mask_rel_pos = gate_a_1.view(bsz, self.num_heads, -1, 1) * position_bias
183
+
184
+ attn_mask_rel_pos = attn_mask_rel_pos.view((bsz, self.num_heads, seq_len, seq_len))
185
+
186
+ if attn_mask_rel_pos is not None and key_padding_mask is not None:
187
+ key_padding_mask = key_padding_mask.view(bsz, 1, 1, seq_len).expand(-1, self.num_heads, -1, -1)
188
+ key_padding_mask = torch.nn.functional._canonical_mask(
189
+ mask=key_padding_mask,
190
+ mask_name="key_padding_mask",
191
+ other_type=torch.nn.functional._none_or_dtype(attn_mask_rel_pos),
192
+ other_name="",
193
+ target_type=query.dtype,
194
+ )
195
+ if attn_mask_rel_pos is not None and key_padding_mask is not None:
196
+ attn_mask_rel_pos = attn_mask_rel_pos + key_padding_mask
197
+ query_projected = torch.nn.functional.linear(query, self.attention.in_proj_weight, self.attention.in_proj_bias)
198
+ query, key, value = query_projected.chunk(3, -1)
199
+ shape = (bsz, seq_len, self.num_heads, self.head_dim)
200
+ query = query.view(shape).transpose(2, 1) # (batch, num_heads, seq_len, head_dim)
201
+ key = key.view(shape).transpose(2, 1) # (batch, num_heads, seq_len, head_dim)
202
+ value = value.view(shape).transpose(2, 1) # (batch, num_heads, seq_len, head_dim)
203
+ dropout = self.dropout if self.training else 0.0
204
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
205
+ query,
206
+ key,
207
+ value,
208
+ attn_mask=attn_mask_rel_pos,
209
+ dropout_p=dropout,
210
+ is_causal=False,
211
+ )
212
+ attn_output = attn_output.transpose(1, 2).reshape(bsz, -1, self.num_heads * self.head_dim)
213
+ attn_output = self.attention.out_proj(attn_output)
214
+ return attn_output, position_bias