yunqi1766 commited on
Commit
770eaeb
·
verified ·
1 Parent(s): 9b46594

Add Meta OmniASR Modal baseline (part 20)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +6 -0
  2. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/INSTALLER +1 -0
  3. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/METADATA +659 -0
  4. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/RECORD +0 -0
  5. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/REQUESTED +0 -0
  6. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/WHEEL +5 -0
  7. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/entry_points.txt +2 -0
  8. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/licenses/LICENSE +203 -0
  9. .venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/top_level.txt +1 -0
  10. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-312.pyc +0 -0
  11. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-312.pyc +0 -0
  12. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-312.pyc +0 -0
  13. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py +204 -0
  14. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py +1529 -0
  15. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py +1077 -0
  16. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py +99 -0
  17. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__init__.py +27 -0
  18. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-312.pyc +0 -0
  19. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-312.pyc +0 -0
  20. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-312.pyc +0 -0
  21. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-312.pyc +0 -0
  22. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py +249 -0
  23. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py +1942 -0
  24. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py +718 -0
  25. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py +26 -0
  26. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-312.pyc +0 -0
  27. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-312.pyc +0 -0
  28. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py +581 -0
  29. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__init__.py +26 -0
  30. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-312.pyc +0 -0
  31. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-312.pyc +0 -0
  32. .venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py +610 -0
  33. .venv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py +27 -0
  34. .venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/__init__.cpython-312.pyc +0 -0
  35. .venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-312.pyc +0 -0
  36. .venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-312.pyc +0 -0
  37. .venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modular_wavlm.cpython-312.pyc +0 -0
  38. .venv/lib/python3.12/site-packages/transformers/models/wavlm/configuration_wavlm.py +239 -0
  39. .venv/lib/python3.12/site-packages/transformers/models/wavlm/modeling_wavlm.py +1654 -0
  40. .venv/lib/python3.12/site-packages/transformers/models/wavlm/modular_wavlm.py +590 -0
  41. .venv/lib/python3.12/site-packages/transformers/models/whisper/__init__.py +30 -0
  42. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/__init__.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/configuration_whisper.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/english_normalizer.cpython-312.pyc +0 -0
  45. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-312.pyc +0 -0
  46. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/generation_whisper.cpython-312.pyc +0 -0
  47. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/modeling_whisper.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/processing_whisper.cpython-312.pyc +0 -0
  49. .venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/tokenization_whisper.cpython-312.pyc +0 -0
  50. .venv/lib/python3.12/site-packages/transformers/models/whisper/configuration_whisper.py +167 -0
.gitattributes CHANGED
@@ -293,3 +293,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
293
  .venv/lib/python3.12/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
294
  .venv/lib/python3.12/site-packages/transformers/models/tapas/__pycache__/tokenization_tapas.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
295
  .venv/lib/python3.12/site-packages/transformers/models/wav2vec2/__pycache__/modeling_wav2vec2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
293
  .venv/lib/python3.12/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
294
  .venv/lib/python3.12/site-packages/transformers/models/tapas/__pycache__/tokenization_tapas.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
295
  .venv/lib/python3.12/site-packages/transformers/models/wav2vec2/__pycache__/modeling_wav2vec2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
296
+ .venv/lib/python3.12/site-packages/transformers/models/xlnet/__pycache__/modeling_xlnet.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
297
+ .venv/lib/python3.12/site-packages/transformers/utils/__pycache__/auto_docstring.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
298
+ .venv/lib/python3.12/site-packages/transformers/utils/__pycache__/import_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
299
+ .venv/lib/python3.12/site-packages/watchfiles/_rust_notify.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
300
+ .venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
301
+ .venv/lib/python3.12/site-packages/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/METADATA ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: transformers
3
+ Version: 5.12.0
4
+ Summary: Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
5
+ Home-page: https://github.com/huggingface/transformers
6
+ Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)
7
+ Author-email: transformers@huggingface.co
8
+ License: Apache 2.0 License
9
+ Keywords: machine-learning nlp python pytorch transformer llm vlm deep-learning inference training model-hub pretrained-models llama gemma qwen
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10.0
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: huggingface-hub<2.0,>=1.5.0
26
+ Requires-Dist: numpy>=1.17
27
+ Requires-Dist: packaging>=20.0
28
+ Requires-Dist: pyyaml>=5.1
29
+ Requires-Dist: regex>=2025.10.22
30
+ Requires-Dist: tokenizers<=0.23.0,>=0.22.0
31
+ Requires-Dist: typer
32
+ Requires-Dist: safetensors>=0.4.3
33
+ Requires-Dist: tqdm>=4.60
34
+ Provides-Extra: torch
35
+ Requires-Dist: torch>=2.4; extra == "torch"
36
+ Requires-Dist: accelerate>=1.1.0; extra == "torch"
37
+ Provides-Extra: vision
38
+ Requires-Dist: torchvision; extra == "vision"
39
+ Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "vision"
40
+ Provides-Extra: audio
41
+ Requires-Dist: torchaudio; extra == "audio"
42
+ Requires-Dist: librosa; extra == "audio"
43
+ Requires-Dist: pyctcdecode>=0.4.0; extra == "audio"
44
+ Requires-Dist: phonemizer; extra == "audio"
45
+ Provides-Extra: video
46
+ Requires-Dist: av; extra == "video"
47
+ Provides-Extra: timm
48
+ Requires-Dist: timm>=1.0.23; extra == "timm"
49
+ Provides-Extra: quality
50
+ Requires-Dist: datasets>=2.15.0; extra == "quality"
51
+ Requires-Dist: ruff==0.14.10; extra == "quality"
52
+ Requires-Dist: GitPython<3.1.19; extra == "quality"
53
+ Requires-Dist: urllib3<2.0.0; extra == "quality"
54
+ Requires-Dist: libcst; extra == "quality"
55
+ Requires-Dist: rich; extra == "quality"
56
+ Requires-Dist: ty==0.0.20; extra == "quality"
57
+ Requires-Dist: tomli; extra == "quality"
58
+ Requires-Dist: transformers-mlinter==0.1.1; extra == "quality"
59
+ Provides-Extra: docs
60
+ Requires-Dist: hf-doc-builder; extra == "docs"
61
+ Provides-Extra: kernels
62
+ Requires-Dist: kernels<0.13,>=0.12.0; extra == "kernels"
63
+ Provides-Extra: sentencepiece
64
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "sentencepiece"
65
+ Requires-Dist: protobuf; extra == "sentencepiece"
66
+ Provides-Extra: tiktoken
67
+ Requires-Dist: tiktoken; extra == "tiktoken"
68
+ Requires-Dist: blobfile; extra == "tiktoken"
69
+ Provides-Extra: mistral-common
70
+ Requires-Dist: mistral-common[image]>=1.10.0; extra == "mistral-common"
71
+ Provides-Extra: chat-template
72
+ Requires-Dist: jinja2>=3.1.0; extra == "chat-template"
73
+ Requires-Dist: jmespath>=1.0.1; extra == "chat-template"
74
+ Provides-Extra: sklearn
75
+ Requires-Dist: scikit-learn; extra == "sklearn"
76
+ Provides-Extra: accelerate
77
+ Requires-Dist: accelerate>=1.1.0; extra == "accelerate"
78
+ Provides-Extra: retrieval
79
+ Requires-Dist: faiss-cpu; extra == "retrieval"
80
+ Requires-Dist: datasets>=2.15.0; extra == "retrieval"
81
+ Provides-Extra: sagemaker
82
+ Requires-Dist: sagemaker>=2.31.0; extra == "sagemaker"
83
+ Provides-Extra: deepspeed
84
+ Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed"
85
+ Requires-Dist: accelerate>=1.1.0; extra == "deepspeed"
86
+ Provides-Extra: optuna
87
+ Requires-Dist: optuna; extra == "optuna"
88
+ Provides-Extra: integrations
89
+ Requires-Dist: kernels<0.13,>=0.12.0; extra == "integrations"
90
+ Requires-Dist: optuna; extra == "integrations"
91
+ Requires-Dist: codecarbon>=2.8.1; extra == "integrations"
92
+ Requires-Dist: ray[tune]>=2.7.0; extra == "integrations"
93
+ Provides-Extra: ray
94
+ Requires-Dist: ray[tune]>=2.7.0; extra == "ray"
95
+ Provides-Extra: codecarbon
96
+ Requires-Dist: codecarbon>=2.8.1; extra == "codecarbon"
97
+ Provides-Extra: serving
98
+ Requires-Dist: openai>=1.98.0; extra == "serving"
99
+ Requires-Dist: pydantic>=2; extra == "serving"
100
+ Requires-Dist: uvicorn; extra == "serving"
101
+ Requires-Dist: fastapi; extra == "serving"
102
+ Requires-Dist: starlette; extra == "serving"
103
+ Requires-Dist: rich; extra == "serving"
104
+ Requires-Dist: torch>=2.4; extra == "serving"
105
+ Requires-Dist: accelerate>=1.1.0; extra == "serving"
106
+ Provides-Extra: num2words
107
+ Requires-Dist: num2words; extra == "num2words"
108
+ Provides-Extra: benchmark
109
+ Requires-Dist: optimum-benchmark>=0.3.0; extra == "benchmark"
110
+ Provides-Extra: ja
111
+ Requires-Dist: fugashi>=1.0; extra == "ja"
112
+ Requires-Dist: ipadic<2.0,>=1.0.0; extra == "ja"
113
+ Requires-Dist: unidic_lite>=1.0.7; extra == "ja"
114
+ Requires-Dist: unidic>=1.0.2; extra == "ja"
115
+ Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "ja"
116
+ Requires-Dist: sudachipy>=0.6.6; extra == "ja"
117
+ Requires-Dist: sudachidict_core>=20220729; extra == "ja"
118
+ Provides-Extra: testing
119
+ Requires-Dist: pytest<9.0.0,>=7.2.0; extra == "testing"
120
+ Requires-Dist: pytest-asyncio>=1.2.0; extra == "testing"
121
+ Requires-Dist: pytest-random-order; extra == "testing"
122
+ Requires-Dist: pytest-rich; extra == "testing"
123
+ Requires-Dist: pytest-xdist; extra == "testing"
124
+ Requires-Dist: pytest-order; extra == "testing"
125
+ Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"
126
+ Requires-Dist: pytest-timeout; extra == "testing"
127
+ Requires-Dist: pytest-env; extra == "testing"
128
+ Requires-Dist: timeout-decorator; extra == "testing"
129
+ Requires-Dist: parameterized>=0.9; extra == "testing"
130
+ Requires-Dist: psutil; extra == "testing"
131
+ Requires-Dist: dill<0.3.5; extra == "testing"
132
+ Requires-Dist: evaluate>=0.4.6; extra == "testing"
133
+ Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "testing"
134
+ Requires-Dist: nltk<=3.8.1; extra == "testing"
135
+ Requires-Dist: sacremoses; extra == "testing"
136
+ Requires-Dist: rjieba; extra == "testing"
137
+ Requires-Dist: beautifulsoup4; extra == "testing"
138
+ Requires-Dist: tensorboard; extra == "testing"
139
+ Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "testing"
140
+ Requires-Dist: filelock; extra == "testing"
141
+ Requires-Dist: hf-doc-builder; extra == "testing"
142
+ Requires-Dist: datasets>=2.15.0; extra == "testing"
143
+ Requires-Dist: ruff==0.14.10; extra == "testing"
144
+ Requires-Dist: GitPython<3.1.19; extra == "testing"
145
+ Requires-Dist: urllib3<2.0.0; extra == "testing"
146
+ Requires-Dist: libcst; extra == "testing"
147
+ Requires-Dist: rich; extra == "testing"
148
+ Requires-Dist: ty==0.0.20; extra == "testing"
149
+ Requires-Dist: tomli; extra == "testing"
150
+ Requires-Dist: transformers-mlinter==0.1.1; extra == "testing"
151
+ Requires-Dist: faiss-cpu; extra == "testing"
152
+ Requires-Dist: datasets>=2.15.0; extra == "testing"
153
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "testing"
154
+ Requires-Dist: protobuf; extra == "testing"
155
+ Requires-Dist: openai>=1.98.0; extra == "testing"
156
+ Requires-Dist: pydantic>=2; extra == "testing"
157
+ Requires-Dist: uvicorn; extra == "testing"
158
+ Requires-Dist: fastapi; extra == "testing"
159
+ Requires-Dist: starlette; extra == "testing"
160
+ Requires-Dist: rich; extra == "testing"
161
+ Requires-Dist: torch>=2.4; extra == "testing"
162
+ Requires-Dist: accelerate>=1.1.0; extra == "testing"
163
+ Requires-Dist: mistral-common[image]>=1.10.0; extra == "testing"
164
+ Provides-Extra: deepspeed-testing
165
+ Requires-Dist: deepspeed>=0.9.3; extra == "deepspeed-testing"
166
+ Requires-Dist: accelerate>=1.1.0; extra == "deepspeed-testing"
167
+ Requires-Dist: pytest<9.0.0,>=7.2.0; extra == "deepspeed-testing"
168
+ Requires-Dist: pytest-asyncio>=1.2.0; extra == "deepspeed-testing"
169
+ Requires-Dist: pytest-random-order; extra == "deepspeed-testing"
170
+ Requires-Dist: pytest-rich; extra == "deepspeed-testing"
171
+ Requires-Dist: pytest-xdist; extra == "deepspeed-testing"
172
+ Requires-Dist: pytest-order; extra == "deepspeed-testing"
173
+ Requires-Dist: pytest-rerunfailures<16.0; extra == "deepspeed-testing"
174
+ Requires-Dist: pytest-timeout; extra == "deepspeed-testing"
175
+ Requires-Dist: pytest-env; extra == "deepspeed-testing"
176
+ Requires-Dist: timeout-decorator; extra == "deepspeed-testing"
177
+ Requires-Dist: parameterized>=0.9; extra == "deepspeed-testing"
178
+ Requires-Dist: psutil; extra == "deepspeed-testing"
179
+ Requires-Dist: dill<0.3.5; extra == "deepspeed-testing"
180
+ Requires-Dist: evaluate>=0.4.6; extra == "deepspeed-testing"
181
+ Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "deepspeed-testing"
182
+ Requires-Dist: nltk<=3.8.1; extra == "deepspeed-testing"
183
+ Requires-Dist: sacremoses; extra == "deepspeed-testing"
184
+ Requires-Dist: rjieba; extra == "deepspeed-testing"
185
+ Requires-Dist: beautifulsoup4; extra == "deepspeed-testing"
186
+ Requires-Dist: tensorboard; extra == "deepspeed-testing"
187
+ Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "deepspeed-testing"
188
+ Requires-Dist: filelock; extra == "deepspeed-testing"
189
+ Requires-Dist: hf-doc-builder; extra == "deepspeed-testing"
190
+ Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing"
191
+ Requires-Dist: ruff==0.14.10; extra == "deepspeed-testing"
192
+ Requires-Dist: GitPython<3.1.19; extra == "deepspeed-testing"
193
+ Requires-Dist: urllib3<2.0.0; extra == "deepspeed-testing"
194
+ Requires-Dist: libcst; extra == "deepspeed-testing"
195
+ Requires-Dist: rich; extra == "deepspeed-testing"
196
+ Requires-Dist: ty==0.0.20; extra == "deepspeed-testing"
197
+ Requires-Dist: tomli; extra == "deepspeed-testing"
198
+ Requires-Dist: transformers-mlinter==0.1.1; extra == "deepspeed-testing"
199
+ Requires-Dist: faiss-cpu; extra == "deepspeed-testing"
200
+ Requires-Dist: datasets>=2.15.0; extra == "deepspeed-testing"
201
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing"
202
+ Requires-Dist: protobuf; extra == "deepspeed-testing"
203
+ Requires-Dist: openai>=1.98.0; extra == "deepspeed-testing"
204
+ Requires-Dist: pydantic>=2; extra == "deepspeed-testing"
205
+ Requires-Dist: uvicorn; extra == "deepspeed-testing"
206
+ Requires-Dist: fastapi; extra == "deepspeed-testing"
207
+ Requires-Dist: starlette; extra == "deepspeed-testing"
208
+ Requires-Dist: rich; extra == "deepspeed-testing"
209
+ Requires-Dist: torch>=2.4; extra == "deepspeed-testing"
210
+ Requires-Dist: accelerate>=1.1.0; extra == "deepspeed-testing"
211
+ Requires-Dist: mistral-common[image]>=1.10.0; extra == "deepspeed-testing"
212
+ Requires-Dist: optuna; extra == "deepspeed-testing"
213
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "deepspeed-testing"
214
+ Requires-Dist: protobuf; extra == "deepspeed-testing"
215
+ Provides-Extra: all
216
+ Requires-Dist: torch>=2.4; extra == "all"
217
+ Requires-Dist: accelerate>=1.1.0; extra == "all"
218
+ Requires-Dist: torchvision; extra == "all"
219
+ Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "all"
220
+ Requires-Dist: torchaudio; extra == "all"
221
+ Requires-Dist: librosa; extra == "all"
222
+ Requires-Dist: pyctcdecode>=0.4.0; extra == "all"
223
+ Requires-Dist: phonemizer; extra == "all"
224
+ Requires-Dist: av; extra == "all"
225
+ Requires-Dist: kernels<0.13,>=0.12.0; extra == "all"
226
+ Requires-Dist: timm>=1.0.23; extra == "all"
227
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "all"
228
+ Requires-Dist: protobuf; extra == "all"
229
+ Requires-Dist: tiktoken; extra == "all"
230
+ Requires-Dist: blobfile; extra == "all"
231
+ Requires-Dist: jinja2>=3.1.0; extra == "all"
232
+ Requires-Dist: jmespath>=1.0.1; extra == "all"
233
+ Requires-Dist: num2words; extra == "all"
234
+ Requires-Dist: mistral-common[image]>=1.10.0; extra == "all"
235
+ Provides-Extra: dev
236
+ Requires-Dist: torch>=2.4; extra == "dev"
237
+ Requires-Dist: accelerate>=1.1.0; extra == "dev"
238
+ Requires-Dist: torchvision; extra == "dev"
239
+ Requires-Dist: Pillow<=15.0,>=10.0.1; extra == "dev"
240
+ Requires-Dist: torchaudio; extra == "dev"
241
+ Requires-Dist: librosa; extra == "dev"
242
+ Requires-Dist: pyctcdecode>=0.4.0; extra == "dev"
243
+ Requires-Dist: phonemizer; extra == "dev"
244
+ Requires-Dist: av; extra == "dev"
245
+ Requires-Dist: kernels<0.13,>=0.12.0; extra == "dev"
246
+ Requires-Dist: timm>=1.0.23; extra == "dev"
247
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev"
248
+ Requires-Dist: protobuf; extra == "dev"
249
+ Requires-Dist: tiktoken; extra == "dev"
250
+ Requires-Dist: blobfile; extra == "dev"
251
+ Requires-Dist: jinja2>=3.1.0; extra == "dev"
252
+ Requires-Dist: jmespath>=1.0.1; extra == "dev"
253
+ Requires-Dist: num2words; extra == "dev"
254
+ Requires-Dist: mistral-common[image]>=1.10.0; extra == "dev"
255
+ Requires-Dist: pytest<9.0.0,>=7.2.0; extra == "dev"
256
+ Requires-Dist: pytest-asyncio>=1.2.0; extra == "dev"
257
+ Requires-Dist: pytest-random-order; extra == "dev"
258
+ Requires-Dist: pytest-rich; extra == "dev"
259
+ Requires-Dist: pytest-xdist; extra == "dev"
260
+ Requires-Dist: pytest-order; extra == "dev"
261
+ Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"
262
+ Requires-Dist: pytest-timeout; extra == "dev"
263
+ Requires-Dist: pytest-env; extra == "dev"
264
+ Requires-Dist: timeout-decorator; extra == "dev"
265
+ Requires-Dist: parameterized>=0.9; extra == "dev"
266
+ Requires-Dist: psutil; extra == "dev"
267
+ Requires-Dist: dill<0.3.5; extra == "dev"
268
+ Requires-Dist: evaluate>=0.4.6; extra == "dev"
269
+ Requires-Dist: rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1; extra == "dev"
270
+ Requires-Dist: nltk<=3.8.1; extra == "dev"
271
+ Requires-Dist: sacremoses; extra == "dev"
272
+ Requires-Dist: rjieba; extra == "dev"
273
+ Requires-Dist: beautifulsoup4; extra == "dev"
274
+ Requires-Dist: tensorboard; extra == "dev"
275
+ Requires-Dist: sacrebleu<2.0.0,>=1.4.12; extra == "dev"
276
+ Requires-Dist: filelock; extra == "dev"
277
+ Requires-Dist: hf-doc-builder; extra == "dev"
278
+ Requires-Dist: datasets>=2.15.0; extra == "dev"
279
+ Requires-Dist: ruff==0.14.10; extra == "dev"
280
+ Requires-Dist: GitPython<3.1.19; extra == "dev"
281
+ Requires-Dist: urllib3<2.0.0; extra == "dev"
282
+ Requires-Dist: libcst; extra == "dev"
283
+ Requires-Dist: rich; extra == "dev"
284
+ Requires-Dist: ty==0.0.20; extra == "dev"
285
+ Requires-Dist: tomli; extra == "dev"
286
+ Requires-Dist: transformers-mlinter==0.1.1; extra == "dev"
287
+ Requires-Dist: faiss-cpu; extra == "dev"
288
+ Requires-Dist: datasets>=2.15.0; extra == "dev"
289
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev"
290
+ Requires-Dist: protobuf; extra == "dev"
291
+ Requires-Dist: openai>=1.98.0; extra == "dev"
292
+ Requires-Dist: pydantic>=2; extra == "dev"
293
+ Requires-Dist: uvicorn; extra == "dev"
294
+ Requires-Dist: fastapi; extra == "dev"
295
+ Requires-Dist: starlette; extra == "dev"
296
+ Requires-Dist: rich; extra == "dev"
297
+ Requires-Dist: torch>=2.4; extra == "dev"
298
+ Requires-Dist: accelerate>=1.1.0; extra == "dev"
299
+ Requires-Dist: mistral-common[image]>=1.10.0; extra == "dev"
300
+ Requires-Dist: fugashi>=1.0; extra == "dev"
301
+ Requires-Dist: ipadic<2.0,>=1.0.0; extra == "dev"
302
+ Requires-Dist: unidic_lite>=1.0.7; extra == "dev"
303
+ Requires-Dist: unidic>=1.0.2; extra == "dev"
304
+ Requires-Dist: rhoknp<1.3.1,>=1.1.0; extra == "dev"
305
+ Requires-Dist: sudachipy>=0.6.6; extra == "dev"
306
+ Requires-Dist: sudachidict_core>=20220729; extra == "dev"
307
+ Requires-Dist: scikit-learn; extra == "dev"
308
+ Dynamic: author
309
+ Dynamic: author-email
310
+ Dynamic: classifier
311
+ Dynamic: description
312
+ Dynamic: description-content-type
313
+ Dynamic: home-page
314
+ Dynamic: keywords
315
+ Dynamic: license
316
+ Dynamic: license-file
317
+ Dynamic: provides-extra
318
+ Dynamic: requires-dist
319
+ Dynamic: requires-python
320
+ Dynamic: summary
321
+
322
+ <!---
323
+ Copyright 2020 The HuggingFace Team. All rights reserved.
324
+
325
+ Licensed under the Apache License, Version 2.0 (the "License");
326
+ you may not use this file except in compliance with the License.
327
+ You may obtain a copy of the License at
328
+
329
+ http://www.apache.org/licenses/LICENSE-2.0
330
+
331
+ Unless required by applicable law or agreed to in writing, software
332
+ distributed under the License is distributed on an "AS IS" BASIS,
333
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
334
+ See the License for the specific language governing permissions and
335
+ limitations under the License.
336
+ -->
337
+
338
+ <p align="center">
339
+ <picture>
340
+ <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-dark.svg">
341
+ <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg">
342
+ <img alt="Hugging Face Transformers Library" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/transformers-logo-light.svg" width="352" height="59" style="max-width: 100%;">
343
+ </picture>
344
+ <br/>
345
+ <br/>
346
+ </p>
347
+
348
+ <p align="center">
349
+ <a href="https://huggingface.com/models"><img alt="Checkpoints on Hub" src="https://img.shields.io/endpoint?url=https://huggingface.co/api/shields/models&color=brightgreen"></a>
350
+ <a href="https://circleci.com/gh/huggingface/transformers"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/main"></a>
351
+ <a href="https://github.com/huggingface/transformers/blob/main/LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/huggingface/transformers.svg?color=blue"></a>
352
+ <a href="https://huggingface.co/docs/transformers/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/transformers/index.svg?down_color=red&down_message=offline&up_message=online"></a>
353
+ <a href="https://github.com/huggingface/transformers/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/transformers.svg"></a>
354
+ <a href="https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
355
+ <a href="https://zenodo.org/badge/latestdoi/155220641"><img src="https://zenodo.org/badge/155220641.svg" alt="DOI"></a>
356
+ </p>
357
+
358
+ <h4 align="center">
359
+ <p>
360
+ <b>English</b> |
361
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hans.md">简体中文</a> |
362
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_zh-hant.md">繁體中文</a> |
363
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ko.md">한국어</a> |
364
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_es.md">Español</a> |
365
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ja.md">日本語</a> |
366
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_hd.md">हिन्दी</a> |
367
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ru.md">Русский</a> |
368
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_pt-br.md">Português</a> |
369
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_te.md">తెలుగు</a> |
370
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_fr.md">Français</a> |
371
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_de.md">Deutsch</a> |
372
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_it.md">Italiano</a> |
373
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_vi.md">Tiếng Việt</a> |
374
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ar.md">العربية</a> |
375
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_ur.md">اردو</a> |
376
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_bn.md">বাংলা</a> |
377
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_fa.md">فارسی</a> |
378
+ <a href="https://github.com/huggingface/transformers/blob/main/i18n/README_tr.md">Türkçe</a> |
379
+ </p>
380
+ </h4>
381
+
382
+ <h3 align="center">
383
+ <p>State-of-the-art pretrained models for inference and training</p>
384
+ </h3>
385
+
386
+ <h3 align="center">
387
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/transformers_as_a_model_definition.png"/>
388
+ </h3>
389
+
390
+ Transformers acts as the model-definition framework for state-of-the-art machine learning with text, computer
391
+ vision, audio, video, and multimodal models, for both inference and training.
392
+
393
+ It centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the
394
+ pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
395
+ frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
396
+ and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.
397
+
398
+ We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be
399
+ simple, customizable, and efficient.
400
+
401
+ There are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.co/models) you can use.
402
+
403
+ Explore the [Hub](https://huggingface.co/) today to find a model and use Transformers to help you get started right away.
404
+
405
+ ## Installation
406
+
407
+ Transformers works with Python 3.10+, and [PyTorch](https://pytorch.org/get-started/locally/) 2.4+.
408
+
409
+ Create and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager.
410
+
411
+ ```py
412
+ # venv
413
+ python -m venv .my-env
414
+ source .my-env/bin/activate
415
+ # uv
416
+ uv venv .my-env
417
+ source .my-env/bin/activate
418
+ ```
419
+
420
+ Install Transformers in your virtual environment.
421
+
422
+ ```py
423
+ # pip
424
+ pip install "transformers[torch]"
425
+
426
+ # uv
427
+ uv pip install "transformers[torch]"
428
+ ```
429
+
430
+ Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the *latest* version may not be stable. Feel free to open an [issue](https://github.com/huggingface/transformers/issues) if you encounter an error.
431
+
432
+ ```shell
433
+ git clone https://github.com/huggingface/transformers.git
434
+ cd transformers
435
+
436
+ # pip
437
+ pip install '.[torch]'
438
+
439
+ # uv
440
+ uv pip install '.[torch]'
441
+ ```
442
+
443
+ ## Quickstart
444
+
445
+ Get started with Transformers right away with the [Pipeline](https://huggingface.co/docs/transformers/pipeline_tutorial) API. The `Pipeline` is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output.
446
+
447
+ Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model.
448
+
449
+ ```py
450
+ from transformers import pipeline
451
+
452
+ pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
453
+ pipeline("the secret to baking a really good cake is ")
454
+ [{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}]
455
+ ```
456
+
457
+ To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to `Pipeline`) between you and the system.
458
+
459
+ > [!TIP]
460
+ > You can also chat with a model directly from the command line, as long as [`transformers serve` is running](https://huggingface.co/docs/transformers/main/en/serving).
461
+ > ```shell
462
+ > transformers chat Qwen/Qwen2.5-0.5B-Instruct
463
+ > ```
464
+
465
+ ```py
466
+ import torch
467
+ from transformers import pipeline
468
+
469
+ chat = [
470
+ {"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
471
+ {"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
472
+ ]
473
+
474
+ pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
475
+ response = pipeline(chat, max_new_tokens=512)
476
+ print(response[0]["generated_text"][-1]["content"])
477
+ ```
478
+
479
+ Expand the examples below to see how `Pipeline` works for different modalities and tasks.
480
+
481
+ <details>
482
+ <summary>Automatic speech recognition</summary>
483
+
484
+ ```py
485
+ from transformers import pipeline
486
+
487
+ pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
488
+ pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
489
+ {'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
490
+ ```
491
+
492
+ </details>
493
+
494
+ <details>
495
+ <summary>Image classification</summary>
496
+
497
+ <h3 align="center">
498
+ <a><img src="https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png"></a>
499
+ </h3>
500
+
501
+ ```py
502
+ from transformers import pipeline
503
+
504
+ pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
505
+ pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
506
+ [{'label': 'macaw', 'score': 0.997848391532898},
507
+ {'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
508
+ 'score': 0.0016551691805943847},
509
+ {'label': 'lorikeet', 'score': 0.00018523589824326336},
510
+ {'label': 'African grey, African gray, Psittacus erithacus',
511
+ 'score': 7.85409429227002e-05},
512
+ {'label': 'quail', 'score': 5.502637941390276e-05}]
513
+ ```
514
+
515
+ </details>
516
+
517
+ <details>
518
+ <summary>Visual question answering</summary>
519
+
520
+ <h3 align="center">
521
+ <a><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg"></a>
522
+ </h3>
523
+
524
+ ```py
525
+ from transformers import pipeline
526
+
527
+ pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
528
+ pipeline(
529
+ image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
530
+ question="What is in the image?",
531
+ )
532
+ [{'answer': 'statue of liberty'}]
533
+ ```
534
+
535
+ </details>
536
+
537
+ ## Why should I use Transformers?
538
+
539
+ 1. Easy-to-use state-of-the-art models:
540
+ - High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks.
541
+ - Low barrier to entry for researchers, engineers, and developers.
542
+ - Few user-facing abstractions with just three classes to learn.
543
+ - A unified API for using all our pretrained models.
544
+
545
+ 1. Lower compute costs, smaller carbon footprint:
546
+ - Share trained models instead of training from scratch.
547
+ - Reduce compute time and production costs.
548
+ - Hundreds of model architectures with 1M+ pretrained checkpoints across all modalities.
549
+
550
+ 1. Choose the right framework for every part of a model's lifetime:
551
+ - Train state-of-the-art models in 3 lines of code.
552
+ - Move a single model between PyTorch/JAX/TF2.0 frameworks at will.
553
+ - Pick the right framework for training, evaluation, and production.
554
+
555
+ 1. Easily customize a model or an example to your needs:
556
+ - We provide examples for each architecture to reproduce the results published by its original authors.
557
+ - Model internals are exposed as consistently as possible.
558
+ - Model files can be used independently of the library for quick experiments.
559
+
560
+ <a target="_blank" href="https://huggingface.co/enterprise">
561
+ <img alt="Hugging Face Enterprise Hub" src="https://github.com/user-attachments/assets/247fb16d-d251-4583-96c4-d3d76dda4925">
562
+ </a><br>
563
+
564
+ ## When shouldn't I use Transformers?
565
+
566
+ - This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files.
567
+ - The training API is optimized to work with PyTorch models provided by Transformers. For generic machine learning loops, you should use another library like [Accelerate](https://huggingface.co/docs/accelerate).
568
+ - The [example scripts](https://github.com/huggingface/transformers/tree/main/examples) are only *examples*. They may not necessarily work out-of-the-box on your specific use case and you'll need to adapt the code for it to work.
569
+
570
+ ## 100 projects using Transformers
571
+
572
+ Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the
573
+ Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone
574
+ else to build their dream projects.
575
+
576
+ In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the
577
+ community with the [awesome-transformers](./awesome-transformers.md) page which lists 100
578
+ incredible projects built with Transformers.
579
+
580
+ If you own or use a project that you believe should be part of the list, please open a PR to add it!
581
+
582
+ ## Example models
583
+
584
+ You can test most of our models directly on their [Hub model pages](https://huggingface.co/models).
585
+
586
+ Expand each modality below to see a few example models for various use cases.
587
+
588
+ <details>
589
+ <summary>Audio</summary>
590
+
591
+ - Audio classification with [CLAP](https://huggingface.co/laion/clap-htsat-fused)
592
+ - Automatic speech recognition with [Parakeet](https://huggingface.co/nvidia/parakeet-ctc-1.1b#transcribing-using-transformers-%F0%9F%A4%97), [Whisper](https://huggingface.co/openai/whisper-large-v3-turbo), [GLM-ASR](https://huggingface.co/zai-org/GLM-ASR-Nano-2512) and [Moonshine-Streaming](https://huggingface.co/UsefulSensors/moonshine-streaming-medium)
593
+ - Keyword spotting with [Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks)
594
+ - Speech to speech generation with [Moshi](https://huggingface.co/kyutai/moshiko-pytorch-bf16)
595
+ - Text to audio with [MusicGen](https://huggingface.co/facebook/musicgen-large)
596
+ - Text to speech with [CSM](https://huggingface.co/sesame/csm-1b)
597
+
598
+ </details>
599
+
600
+ <details>
601
+ <summary>Computer vision</summary>
602
+
603
+ - Automatic mask generation with [SAM](https://huggingface.co/facebook/sam-vit-base)
604
+ - Depth estimation with [DepthPro](https://huggingface.co/apple/DepthPro-hf)
605
+ - Image classification with [DINO v2](https://huggingface.co/facebook/dinov2-base)
606
+ - Keypoint detection with [SuperPoint](https://huggingface.co/magic-leap-community/superpoint)
607
+ - Keypoint matching with [SuperGlue](https://huggingface.co/magic-leap-community/superglue_outdoor)
608
+ - Object detection with [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r50vd)
609
+ - Pose Estimation with [VitPose](https://huggingface.co/usyd-community/vitpose-base-simple)
610
+ - Universal segmentation with [OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_swin_large)
611
+ - Video classification with [VideoMAE](https://huggingface.co/MCG-NJU/videomae-large)
612
+
613
+ </details>
614
+
615
+ <details>
616
+ <summary>Multimodal</summary>
617
+
618
+ - Audio or text to text with [Voxtral](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507), [Audio Flamingo](https://huggingface.co/nvidia/audio-flamingo-3-hf)
619
+ - Document question answering with [LayoutLMv3](https://huggingface.co/microsoft/layoutlmv3-base)
620
+ - Image or text to text with [Qwen-VL](https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct)
621
+ - Image captioning [BLIP-2](https://huggingface.co/Salesforce/blip2-opt-2.7b)
622
+ - OCR-based document understanding with [GOT-OCR2](https://huggingface.co/stepfun-ai/GOT-OCR-2.0-hf)
623
+ - Table question answering with [TAPAS](https://huggingface.co/google/tapas-base)
624
+ - Unified multimodal understanding and generation with [Emu3](https://huggingface.co/BAAI/Emu3-Gen)
625
+ - Vision to text with [Llava-OneVision](https://huggingface.co/llava-hf/llava-onevision-qwen2-0.5b-ov-hf)
626
+ - Visual question answering with [Llava](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
627
+ - Visual referring expression segmentation with [Kosmos-2](https://huggingface.co/microsoft/kosmos-2-patch14-224)
628
+
629
+ </details>
630
+
631
+ <details>
632
+ <summary>NLP</summary>
633
+
634
+ - Masked word completion with [ModernBERT](https://huggingface.co/answerdotai/ModernBERT-base)
635
+ - Named entity recognition with [Gemma](https://huggingface.co/google/gemma-2-2b)
636
+ - Question answering with [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1)
637
+ - Summarization with [BART](https://huggingface.co/facebook/bart-large-cnn)
638
+ - Translation with [T5](https://huggingface.co/google-t5/t5-base)
639
+ - Text generation with [Llama](https://huggingface.co/meta-llama/Llama-3.2-1B)
640
+ - Text classification with [Qwen](https://huggingface.co/Qwen/Qwen2.5-0.5B)
641
+
642
+ </details>
643
+
644
+ ## Citation
645
+
646
+ We now have a [paper](https://aclanthology.org/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library:
647
+ ```bibtex
648
+ @inproceedings{wolf-etal-2020-transformers,
649
+ title = "Transformers: State-of-the-Art Natural Language Processing",
650
+ author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
651
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
652
+ month = oct,
653
+ year = "2020",
654
+ address = "Online",
655
+ publisher = "Association for Computational Linguistics",
656
+ url = "https://aclanthology.org/2020.emnlp-demos.6/",
657
+ pages = "38--45"
658
+ }
659
+ ```
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ transformers = transformers.cli.transformers:main
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2018- The Hugging Face team. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
.venv/lib/python3.12/site-packages/transformers-5.12.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ transformers
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modeling_wav2vec2_bert.cpython-312.pyc ADDED
Binary file (75.4 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/modular_wav2vec2_bert.cpython-312.pyc ADDED
Binary file (52.1 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/__pycache__/processing_wav2vec2_bert.cpython-312.pyc ADDED
Binary file (4.35 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Wav2Vec2Bert model configuration"""
15
+
16
+ from typing import Literal
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import auto_docstring
22
+
23
+
24
+ @auto_docstring(checkpoint="facebook/wav2vec2-bert-rel-pos-large")
25
+ @strict
26
+ class Wav2Vec2BertConfig(PreTrainedConfig):
27
+ r"""
28
+ feature_projection_input_dim (`int`, *optional*, defaults to 160):
29
+ Input dimension of this model, i.e the dimension after processing input audios with [`SeamlessM4TFeatureExtractor`] or [`Wav2Vec2BertProcessor`].
30
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
31
+ The dropout probability for the feature projection.
32
+ final_dropout (`float`, *optional*, defaults to 0.1):
33
+ The dropout probability for the final projection layer of [`Wav2Vec2BertForCTC`].
34
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
35
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
36
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
37
+ Recognition](https://huggingface.co/papers/1904.08779).
38
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
39
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
40
+ procedure generates `mask_time_prob*len(time_axis)/mask_time_length ``independent masks over the axis. If
41
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
42
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
43
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
44
+ mask_time_length (`int`, *optional*, defaults to 10):
45
+ Length of vector span along the time axis.
46
+ mask_time_min_masks (`int`, *optional*, defaults to 2):
47
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
48
+ irrespectively of `mask_feature_prob`. Only relevant if `mask_time_prob*len(time_axis)/mask_time_length <
49
+ mask_time_min_masks`.
50
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
51
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
52
+ masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
53
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
54
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
55
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
56
+ True`.
57
+ mask_feature_length (`int`, *optional*, defaults to 10):
58
+ Length of vector span along the feature axis.
59
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
60
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
61
+ step, irrespectively of `mask_feature_prob`. Only relevant if
62
+ `mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks`.
63
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
64
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
65
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
66
+ of [`Wav2Vec2BertForCTC`].
67
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
68
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
69
+ instance of [`Wav2Vec2BertForSequenceClassification`].
70
+ classifier_proj_size (`int`, *optional*, defaults to 768):
71
+ Dimensionality of the projection before token mean-pooling for classification.
72
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
73
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
74
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
75
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
76
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
77
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
78
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
79
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
80
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
81
+ xvector_output_dim (`int`, *optional*, defaults to 512):
82
+ Dimensionality of the *XVector* embedding vectors.
83
+ add_adapter (`bool`, *optional*, defaults to `False`):
84
+ Whether a convolutional attention network should be stacked on top of the Wav2Vec2Bert Encoder. Can be very
85
+ useful for warm-starting Wav2Vec2Bert for SpeechEncoderDecoder models.
86
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
87
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
88
+ adapter_stride (`int`, *optional*, defaults to 2):
89
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
90
+ num_adapter_layers (`int`, *optional*, defaults to 1):
91
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
92
+ True`.
93
+ adapter_act (`str` or `function`, *optional*, defaults to `"relu"`):
94
+ The non-linear activation function (function or string) in the adapter layers. If string, `"gelu"`,
95
+ `"relu"`, `"selu"`, `"swish"` and `"gelu_new"` are supported.
96
+ use_intermediate_ffn_before_adapter (`bool`, *optional*, defaults to `False`):
97
+ Whether an intermediate feed-forward block should be stacked on top of the Wav2Vec2Bert Encoder and before the adapter network.
98
+ Only relevant if `add_adapter is True`.
99
+ output_hidden_size (`int`, *optional*):
100
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
101
+ if `add_adapter is True`.
102
+ position_embeddings_type (`str`, *optional*, defaults to `"relative_key"`):
103
+ Can be specified to :
104
+ - `rotary`, for rotary position embeddings.
105
+ - `relative`, for relative position embeddings.
106
+ - `relative_key`, for relative position embeddings as defined by Shaw in [Self-Attention
107
+ with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
108
+ If left to `None`, no relative position embeddings is applied.
109
+ rotary_embedding_base (`int`, *optional*, defaults to 10000):
110
+ If `"rotary"` position embeddings are used, defines the size of the embedding base.
111
+ max_source_positions (`int`, *optional*, defaults to 5000):
112
+ if `"relative"` position embeddings are used, defines the maximum source input positions.
113
+ left_max_position_embeddings (`int`, *optional*, defaults to 64):
114
+ If `"relative_key"` (aka Shaw) position embeddings are used, defines the left clipping value for relative positions.
115
+ right_max_position_embeddings (`int`, *optional*, defaults to 8):
116
+ If `"relative_key"` (aka Shaw) position embeddings are used, defines the right clipping value for relative positions.
117
+ conv_depthwise_kernel_size (`int`, *optional*, defaults to 31):
118
+ Kernel size of convolutional depthwise 1D layer in Conformer blocks.
119
+ conformer_conv_dropout (`float`, *optional*, defaults to 0.1):
120
+ The dropout probability for all convolutional layers in Conformer blocks.
121
+
122
+ Example:
123
+
124
+ ```python
125
+ >>> from transformers import Wav2Vec2BertConfig, Wav2Vec2BertModel
126
+
127
+ >>> # Initializing a Wav2Vec2Bert facebook/wav2vec2-bert-rel-pos-large style configuration
128
+ >>> configuration = Wav2Vec2BertConfig()
129
+
130
+ >>> # Initializing a model (with random weights) from the facebook/wav2vec2-bert-rel-pos-large style configuration
131
+ >>> model = Wav2Vec2BertModel(configuration)
132
+
133
+ >>> # Accessing the model configuration
134
+ >>> configuration = model.config
135
+ ```"""
136
+
137
+ model_type = "wav2vec2-bert"
138
+
139
+ vocab_size: int | None = None
140
+ hidden_size: int = 1024
141
+ num_hidden_layers: int = 24
142
+ num_attention_heads: int = 16
143
+ intermediate_size: int = 4096
144
+ feature_projection_input_dim: int = 160
145
+ hidden_act: str = "swish"
146
+ hidden_dropout: float | int = 0.0
147
+ activation_dropout: float | int = 0.0
148
+ attention_dropout: float | int = 0.0
149
+ feat_proj_dropout: float | int = 0.0
150
+ final_dropout: float | int = 0.1
151
+ layerdrop: float | int = 0.1
152
+ initializer_range: float = 0.02
153
+ layer_norm_eps: float = 1e-5
154
+ apply_spec_augment: bool = True
155
+ mask_time_prob: float | int = 0.05
156
+ mask_time_length: int = 10
157
+ mask_time_min_masks: int = 2
158
+ mask_feature_prob: float | int = 0.0
159
+ mask_feature_length: int = 10
160
+ mask_feature_min_masks: int = 0
161
+ ctc_loss_reduction: str = "sum"
162
+ ctc_zero_infinity: bool = False
163
+ use_weighted_layer_sum: bool = False
164
+ classifier_proj_size: int = 768
165
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
166
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
167
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
168
+ xvector_output_dim: int = 512
169
+ pad_token_id: int | None = 0
170
+ bos_token_id: int | None = 1
171
+ eos_token_id: int | list[int] | None = 2
172
+ add_adapter: bool = False
173
+ adapter_kernel_size: int = 3
174
+ adapter_stride: int = 2
175
+ num_adapter_layers: int = 1
176
+ adapter_act: str = "relu"
177
+ use_intermediate_ffn_before_adapter: bool = False
178
+ output_hidden_size: int | None = None
179
+ position_embeddings_type: Literal["rotary", "relative", "relative_key"] | None = "relative_key"
180
+ rotary_embedding_base: int = 10000
181
+ max_source_positions: int = 5000
182
+ left_max_position_embeddings: int = 64
183
+ right_max_position_embeddings: int = 8
184
+ conv_depthwise_kernel_size: int = 31
185
+ conformer_conv_dropout: float | int = 0.1
186
+
187
+ def __post_init__(self, **kwargs):
188
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
189
+ super().__post_init__(**kwargs)
190
+
191
+ def validate_architecture(self):
192
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
193
+ if self.use_intermediate_ffn_before_adapter and not self.add_adapter:
194
+ raise ValueError("`use_intermediate_ffn_before_adapter` is `True` but `add_adapter` is `False`.")
195
+
196
+ @property
197
+ def inputs_to_logits_ratio(self):
198
+ ratio = self.feature_projection_input_dim * 2
199
+ if self.add_adapter:
200
+ ratio = ratio * (self.adapter_stride**self.num_adapter_layers)
201
+ return ratio
202
+
203
+
204
+ __all__ = ["Wav2Vec2BertConfig"]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py ADDED
@@ -0,0 +1,1529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_wav2vec2_bert.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ import math
8
+ import warnings
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torch import nn
13
+ from torch.nn import CrossEntropyLoss
14
+
15
+ from ... import initialization as init
16
+ from ...activations import ACT2FN
17
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
18
+ from ...integrations.fsdp import is_fsdp_managed_module
19
+ from ...masking_utils import create_bidirectional_mask
20
+ from ...modeling_layers import GradientCheckpointingLayer
21
+ from ...modeling_outputs import (
22
+ BaseModelOutput,
23
+ CausalLMOutput,
24
+ SequenceClassifierOutput,
25
+ TokenClassifierOutput,
26
+ Wav2Vec2BaseModelOutput,
27
+ XVectorOutput,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import auto_docstring, is_peft_available
31
+ from .configuration_wav2vec2_bert import Wav2Vec2BertConfig
32
+
33
+
34
+ class Wav2Vec2BertRotaryPositionalEmbedding(nn.Module):
35
+ """Rotary positional embedding
36
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://huggingface.co/papers/2104.09864
37
+ """
38
+
39
+ def __init__(self, config):
40
+ super().__init__()
41
+ dim = config.hidden_size // config.num_attention_heads
42
+ base = config.rotary_embedding_base
43
+
44
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
45
+ # Ignore copy
46
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
47
+ self.cached_sequence_length = None
48
+ self.cached_rotary_positional_embedding = None
49
+
50
+ def forward(self, hidden_states):
51
+ sequence_length = hidden_states.shape[1]
52
+
53
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
54
+ return self.cached_rotary_positional_embedding
55
+
56
+ self.cached_sequence_length = sequence_length
57
+ # Embeddings are computed in the dtype of the inv_freq constant
58
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
59
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
60
+ embeddings = torch.cat((freqs, freqs), dim=-1)
61
+
62
+ cos_embeddings = embeddings.cos()[:, None, None, :]
63
+ sin_embeddings = embeddings.sin()[:, None, None, :]
64
+ # Computed embeddings are cast to the dtype of the hidden state inputs
65
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
66
+ return self.cached_rotary_positional_embedding
67
+
68
+
69
+ class Wav2Vec2BertRelPositionalEmbedding(nn.Module):
70
+ """Relative positional encoding module."""
71
+
72
+ def __init__(self, config):
73
+ super().__init__()
74
+ self.max_len = config.max_source_positions
75
+ self.d_model = config.hidden_size
76
+ self.register_buffer("pe", self.extend_pe(torch.tensor(0.0).expand(1, self.max_len)), persistent=False)
77
+
78
+ def extend_pe(self, x, pe=None):
79
+ # Reset the positional encodings
80
+ if pe is not None:
81
+ # self.pe contains both positive and negative parts
82
+ # the length of self.pe is 2 * input_len - 1
83
+ if pe.size(1) >= x.size(1) * 2 - 1:
84
+ if pe.dtype != x.dtype or pe.device != x.device:
85
+ pe = pe.to(dtype=x.dtype, device=x.device)
86
+ return pe
87
+ # Suppose `i` is the position of query vector and `j` is the
88
+ # position of key vector. We use positive relative positions when keys
89
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
90
+ pe_positive = torch.zeros(x.size(1), self.d_model)
91
+ pe_negative = torch.zeros(x.size(1), self.d_model)
92
+ position = torch.arange(0, x.size(1), dtype=torch.int64).float().unsqueeze(1)
93
+ div_term = torch.exp(
94
+ torch.arange(0, self.d_model, 2, dtype=torch.int64).float() * -(math.log(10000.0) / self.d_model)
95
+ )
96
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
97
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
98
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
99
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
100
+
101
+ # Reverse the order of positive indices and concat both positive and
102
+ # negative indices. This is used to support the shifting trick
103
+ # as in https://huggingface.co/papers/1901.02860
104
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
105
+ pe_negative = pe_negative[1:].unsqueeze(0)
106
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
107
+ return pe.to(device=x.device, dtype=x.dtype)
108
+
109
+ def forward(self, hidden_states: torch.Tensor):
110
+ self.pe = self.extend_pe(hidden_states, self.pe)
111
+ start_idx = self.pe.size(1) // 2 - hidden_states.size(1) + 1
112
+ end_idx = self.pe.size(1) // 2 + hidden_states.size(1)
113
+ relative_position_embeddings = self.pe[:, start_idx:end_idx]
114
+
115
+ return relative_position_embeddings
116
+
117
+
118
+ class Wav2Vec2BertFeatureProjection(nn.Module):
119
+ def __init__(self, config):
120
+ super().__init__()
121
+ self.layer_norm = nn.LayerNorm(config.feature_projection_input_dim, eps=config.layer_norm_eps)
122
+ self.projection = nn.Linear(config.feature_projection_input_dim, config.hidden_size)
123
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
124
+
125
+ def forward(self, hidden_states):
126
+ # non-projected hidden states are needed for quantization
127
+ norm_hidden_states = self.layer_norm(hidden_states)
128
+ hidden_states = self.projection(norm_hidden_states)
129
+ hidden_states = self.dropout(hidden_states)
130
+ return hidden_states, norm_hidden_states
131
+
132
+
133
+ class Wav2Vec2BertFeedForward(nn.Module):
134
+ def __init__(self, config, act_fn=None, hidden_size=None):
135
+ super().__init__()
136
+ act_fn = act_fn if act_fn is not None else config.hidden_act
137
+ hidden_size = hidden_size if hidden_size is not None else config.hidden_size
138
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
139
+
140
+ self.intermediate_dense = nn.Linear(hidden_size, config.intermediate_size)
141
+ self.intermediate_act_fn = ACT2FN[act_fn] if isinstance(act_fn, str) else act_fn
142
+
143
+ self.output_dense = nn.Linear(config.intermediate_size, hidden_size)
144
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
145
+
146
+ def forward(self, hidden_states):
147
+ hidden_states = self.intermediate_dense(hidden_states)
148
+ hidden_states = self.intermediate_act_fn(hidden_states)
149
+ hidden_states = self.intermediate_dropout(hidden_states)
150
+
151
+ hidden_states = self.output_dense(hidden_states)
152
+ hidden_states = self.output_dropout(hidden_states)
153
+ return hidden_states
154
+
155
+
156
+ class Wav2Vec2BertConvolutionModule(nn.Module):
157
+ """Convolution block used in the conformer block"""
158
+
159
+ def __init__(self, config):
160
+ super().__init__()
161
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
162
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
163
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
164
+ self.pointwise_conv1 = nn.Conv1d(
165
+ config.hidden_size,
166
+ 2 * config.hidden_size,
167
+ kernel_size=1,
168
+ stride=1,
169
+ padding=0,
170
+ bias=False,
171
+ )
172
+ self.glu = nn.GLU(dim=1)
173
+ self.depthwise_conv = nn.Conv1d(
174
+ config.hidden_size,
175
+ config.hidden_size,
176
+ config.conv_depthwise_kernel_size,
177
+ stride=1,
178
+ padding=0,
179
+ groups=config.hidden_size,
180
+ bias=False,
181
+ )
182
+
183
+ self.depthwise_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
184
+ self.activation = ACT2FN[config.hidden_act]
185
+ self.pointwise_conv2 = nn.Conv1d(
186
+ config.hidden_size,
187
+ config.hidden_size,
188
+ kernel_size=1,
189
+ stride=1,
190
+ padding=0,
191
+ bias=False,
192
+ )
193
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
194
+
195
+ def forward(self, hidden_states, attention_mask=None):
196
+ hidden_states = self.layer_norm(hidden_states)
197
+
198
+ # Ensure that we do not leak padded positions in depthwise convolution if attention mask is passed.
199
+ # Put 0 where necessary
200
+ if attention_mask is not None:
201
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
202
+
203
+ # exchange the temporal dimension and the feature dimension
204
+ hidden_states = hidden_states.transpose(1, 2)
205
+
206
+ # GLU mechanism
207
+ # => (batch, 2*channel, dim)
208
+ hidden_states = self.pointwise_conv1(hidden_states)
209
+ # => (batch, channel, dim)
210
+ hidden_states = self.glu(hidden_states)
211
+
212
+ # Pad the sequence entirely on the left because of causal convolution.
213
+ hidden_states = torch.nn.functional.pad(hidden_states, (self.depthwise_conv.kernel_size[0] - 1, 0))
214
+
215
+ # 1D Depthwise Conv
216
+ hidden_states = self.depthwise_conv(hidden_states)
217
+
218
+ hidden_states = self.depthwise_layer_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
219
+
220
+ hidden_states = self.activation(hidden_states)
221
+
222
+ hidden_states = self.pointwise_conv2(hidden_states)
223
+ hidden_states = self.dropout(hidden_states)
224
+ hidden_states = hidden_states.transpose(1, 2)
225
+ return hidden_states
226
+
227
+
228
+ class Wav2Vec2BertSelfAttention(nn.Module):
229
+ """Construct an Wav2Vec2BertSelfAttention object.
230
+ Can be enhanced with rotary or relative position embeddings.
231
+ """
232
+
233
+ def __init__(self, config, is_adapter_attention=False):
234
+ super().__init__()
235
+ hidden_size = config.hidden_size if not is_adapter_attention else config.output_hidden_size
236
+
237
+ self.head_size = hidden_size // config.num_attention_heads
238
+ self.num_heads = config.num_attention_heads
239
+ self.position_embeddings_type = config.position_embeddings_type if not is_adapter_attention else None
240
+
241
+ self.linear_q = nn.Linear(hidden_size, hidden_size)
242
+ self.linear_k = nn.Linear(hidden_size, hidden_size)
243
+ self.linear_v = nn.Linear(hidden_size, hidden_size)
244
+ self.linear_out = nn.Linear(hidden_size, hidden_size)
245
+
246
+ self.dropout = nn.Dropout(p=config.attention_dropout)
247
+
248
+ if self.position_embeddings_type == "relative":
249
+ # linear transformation for positional encoding
250
+ self.linear_pos = nn.Linear(hidden_size, hidden_size, bias=False)
251
+ # these two learnable bias are used in matrix c and matrix d
252
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
253
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
254
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
255
+
256
+ if self.position_embeddings_type == "relative_key":
257
+ self.left_max_position_embeddings = config.left_max_position_embeddings
258
+ self.right_max_position_embeddings = config.right_max_position_embeddings
259
+ num_positions = self.left_max_position_embeddings + self.right_max_position_embeddings + 1
260
+ self.distance_embedding = nn.Embedding(num_positions, self.head_size)
261
+
262
+ def forward(
263
+ self,
264
+ hidden_states: torch.Tensor,
265
+ attention_mask: torch.Tensor | None = None,
266
+ relative_position_embeddings: torch.Tensor | None = None,
267
+ output_attentions: bool = False,
268
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
269
+ # self-attention mechanism
270
+ batch_size, sequence_length, hidden_size = hidden_states.size()
271
+
272
+ # make sure query/key states can be != value states
273
+ query_key_states = hidden_states
274
+ value_states = hidden_states
275
+
276
+ if self.position_embeddings_type == "rotary":
277
+ if relative_position_embeddings is None:
278
+ raise ValueError(
279
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
280
+ )
281
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
282
+
283
+ # project query_key_states and value_states
284
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
285
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
286
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
287
+
288
+ # => (batch, head, time1, d_k)
289
+ query = query.transpose(1, 2)
290
+ key = key.transpose(1, 2)
291
+ value = value.transpose(1, 2)
292
+
293
+ if self.position_embeddings_type == "relative":
294
+ if relative_position_embeddings is None:
295
+ raise ValueError(
296
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
297
+ " 'relative'"
298
+ )
299
+ # apply relative_position_embeddings to qk scores
300
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
301
+ scores = self._apply_relative_embeddings(
302
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
303
+ )
304
+ else:
305
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
306
+
307
+ if self.position_embeddings_type == "relative_key":
308
+ query_length, key_length = query.shape[2], key.shape[2]
309
+
310
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
311
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
312
+ distance = position_ids_r - position_ids_l
313
+ distance = torch.clamp(distance, -self.left_max_position_embeddings, self.right_max_position_embeddings)
314
+
315
+ positional_embedding = self.distance_embedding(distance + self.left_max_position_embeddings)
316
+ positional_embedding = positional_embedding.to(dtype=query.dtype) # fp16 compatibility
317
+
318
+ relative_position_attn_weights = torch.einsum("bhld,lrd->bhlr", query, positional_embedding)
319
+ scores = scores + (relative_position_attn_weights / math.sqrt(self.head_size))
320
+
321
+ # apply attention_mask if necessary
322
+ if attention_mask is not None:
323
+ scores = scores + attention_mask
324
+
325
+ # => (batch, head, time1, time2)
326
+ probs = torch.softmax(scores, dim=-1)
327
+ probs = self.dropout(probs)
328
+
329
+ # => (batch, head, time1, d_k)
330
+ hidden_states = torch.matmul(probs, value)
331
+
332
+ # => (batch, time1, hidden_size)
333
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
334
+ hidden_states = self.linear_out(hidden_states)
335
+
336
+ return hidden_states, probs
337
+
338
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
339
+ batch_size, sequence_length, hidden_size = hidden_states.size()
340
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
341
+
342
+ cos = relative_position_embeddings[0, :sequence_length, ...]
343
+ sin = relative_position_embeddings[1, :sequence_length, ...]
344
+
345
+ # rotate hidden_states with rotary embeddings
346
+ hidden_states = hidden_states.transpose(0, 1)
347
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
348
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
349
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
350
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
351
+ hidden_states = hidden_states.transpose(0, 1)
352
+
353
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
354
+
355
+ return hidden_states
356
+
357
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
358
+ # 1. project positional embeddings
359
+ # => (batch, head, 2*time1-1, d_k)
360
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
361
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
362
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size
363
+ )
364
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)
365
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)
366
+
367
+ # 2. Add bias to query
368
+ # => (batch, head, time1, d_k)
369
+ query = query.transpose(1, 2)
370
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
371
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
372
+
373
+ # 3. attention score: first compute matrix a and matrix c
374
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
375
+ # => (batch, head, time1, time2)
376
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
377
+
378
+ # 4. then compute matrix b and matrix d
379
+ # => (batch, head, time1, 2*time1-1)
380
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
381
+
382
+ # 5. shift matrix b and matrix d
383
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
384
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
385
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
386
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
387
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
388
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
389
+
390
+ # 6. sum matrices
391
+ # => (batch, head, time1, time2)
392
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
393
+
394
+ return scores
395
+
396
+
397
+ class Wav2Vec2BertEncoderLayer(GradientCheckpointingLayer):
398
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
399
+
400
+ def __init__(self, config):
401
+ super().__init__()
402
+ embed_dim = config.hidden_size
403
+ dropout = config.attention_dropout
404
+
405
+ # Feed-forward 1
406
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
407
+ self.ffn1 = Wav2Vec2BertFeedForward(config)
408
+
409
+ # Self-Attention
410
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
411
+ self.self_attn_dropout = nn.Dropout(dropout)
412
+ self.self_attn = Wav2Vec2BertSelfAttention(config)
413
+
414
+ # Conformer Convolution
415
+ self.conv_module = Wav2Vec2BertConvolutionModule(config)
416
+
417
+ # Feed-forward 2
418
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
419
+ self.ffn2 = Wav2Vec2BertFeedForward(config)
420
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states,
425
+ attention_mask: torch.Tensor | None = None,
426
+ relative_position_embeddings: torch.Tensor | None = None,
427
+ output_attentions: bool = False,
428
+ conv_attention_mask: torch.Tensor | None = None,
429
+ ):
430
+ # 1. Feed-Forward 1 layer
431
+ residual = hidden_states
432
+ hidden_states = self.ffn1_layer_norm(hidden_states)
433
+ hidden_states = self.ffn1(hidden_states)
434
+ hidden_states = hidden_states * 0.5 + residual
435
+ residual = hidden_states
436
+
437
+ # 2. Self-Attention layer
438
+ hidden_states = self.self_attn_layer_norm(hidden_states)
439
+ hidden_states, attn_weigts = self.self_attn(
440
+ hidden_states=hidden_states,
441
+ attention_mask=attention_mask,
442
+ relative_position_embeddings=relative_position_embeddings,
443
+ output_attentions=output_attentions,
444
+ )
445
+ hidden_states = self.self_attn_dropout(hidden_states)
446
+ hidden_states = hidden_states + residual
447
+
448
+ # 3. Convolutional Layer
449
+ residual = hidden_states
450
+ hidden_states = self.conv_module(hidden_states, attention_mask=conv_attention_mask)
451
+ hidden_states = residual + hidden_states
452
+
453
+ # 4. Feed-Forward 2 Layer
454
+ residual = hidden_states
455
+ hidden_states = self.ffn2_layer_norm(hidden_states)
456
+ hidden_states = self.ffn2(hidden_states)
457
+ hidden_states = hidden_states * 0.5 + residual
458
+ hidden_states = self.final_layer_norm(hidden_states)
459
+
460
+ return hidden_states, attn_weigts
461
+
462
+
463
+ class Wav2Vec2BertEncoder(nn.Module):
464
+ def __init__(self, config):
465
+ super().__init__()
466
+ self.config = config
467
+
468
+ if config.position_embeddings_type == "relative":
469
+ self.embed_positions = Wav2Vec2BertRelPositionalEmbedding(config)
470
+ elif config.position_embeddings_type == "rotary":
471
+ self.embed_positions = Wav2Vec2BertRotaryPositionalEmbedding(config)
472
+ else:
473
+ self.embed_positions = None
474
+
475
+ self.dropout = nn.Dropout(config.hidden_dropout)
476
+ self.layers = nn.ModuleList([Wav2Vec2BertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
477
+ self.gradient_checkpointing = False
478
+
479
+ def forward(
480
+ self,
481
+ hidden_states,
482
+ attention_mask=None,
483
+ output_attentions=False,
484
+ output_hidden_states=False,
485
+ return_dict=True,
486
+ ):
487
+ all_hidden_states = () if output_hidden_states else None
488
+ all_self_attentions = () if output_attentions else None
489
+
490
+ conv_attention_mask = attention_mask
491
+ if attention_mask is not None:
492
+ # make sure padded tokens output 0
493
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
494
+
495
+ # extend attention_mask
496
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
497
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
498
+ attention_mask = attention_mask.expand(
499
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
500
+ )
501
+
502
+ hidden_states = self.dropout(hidden_states)
503
+
504
+ if self.embed_positions is not None:
505
+ relative_position_embeddings = self.embed_positions(hidden_states)
506
+ else:
507
+ relative_position_embeddings = None
508
+
509
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
510
+
511
+ for i, layer in enumerate(self.layers):
512
+ if output_hidden_states:
513
+ all_hidden_states = all_hidden_states + (hidden_states,)
514
+
515
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
516
+ dropout_probability = torch.rand([])
517
+
518
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
519
+ if not skip_the_layer or synced_gpus:
520
+ # under fsdp or deepspeed zero3 all gpus must run in sync
521
+ layer_outputs = layer(
522
+ hidden_states,
523
+ attention_mask=attention_mask,
524
+ relative_position_embeddings=relative_position_embeddings,
525
+ output_attentions=output_attentions,
526
+ conv_attention_mask=conv_attention_mask,
527
+ )
528
+ hidden_states = layer_outputs[0]
529
+
530
+ if skip_the_layer:
531
+ layer_outputs = (None, None)
532
+
533
+ if output_attentions:
534
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
535
+
536
+ if output_hidden_states:
537
+ all_hidden_states = all_hidden_states + (hidden_states,)
538
+
539
+ if not return_dict:
540
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
541
+ return BaseModelOutput(
542
+ last_hidden_state=hidden_states,
543
+ hidden_states=all_hidden_states,
544
+ attentions=all_self_attentions,
545
+ )
546
+
547
+
548
+ class Wav2Vec2BertAdapter(nn.Module):
549
+ def __init__(self, config):
550
+ super().__init__()
551
+ # feature dim might need to be down-projected
552
+ if config.output_hidden_size != config.hidden_size:
553
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
554
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size, eps=config.layer_norm_eps)
555
+ else:
556
+ self.proj = self.proj_layer_norm = None
557
+ self.layers = nn.ModuleList(Wav2Vec2BertAdapterLayer(config) for _ in range(config.num_adapter_layers))
558
+ self.layerdrop = config.layerdrop
559
+
560
+ self.kernel_size = config.adapter_kernel_size
561
+ self.stride = config.adapter_stride
562
+
563
+ def _compute_sub_sample_lengths_from_attention_mask(self, seq_lens):
564
+ if seq_lens is None:
565
+ return seq_lens
566
+ pad = self.kernel_size // 2
567
+ seq_lens = ((seq_lens + 2 * pad - self.kernel_size) / self.stride) + 1
568
+ return seq_lens.floor()
569
+
570
+ def forward(self, hidden_states, attention_mask=None):
571
+ # down project hidden_states if necessary
572
+ if self.proj is not None and self.proj_layer_norm is not None:
573
+ hidden_states = self.proj(hidden_states)
574
+ hidden_states = self.proj_layer_norm(hidden_states)
575
+
576
+ sub_sampled_lengths = None
577
+ if attention_mask is not None:
578
+ sub_sampled_lengths = (attention_mask.size(1) - (1 - attention_mask.int()).sum(1)).to(hidden_states.device)
579
+
580
+ for layer in self.layers:
581
+ layerdrop_prob = torch.rand([])
582
+ sub_sampled_lengths = self._compute_sub_sample_lengths_from_attention_mask(sub_sampled_lengths)
583
+ if not self.training or (layerdrop_prob > self.layerdrop):
584
+ hidden_states = layer(
585
+ hidden_states, attention_mask=attention_mask, sub_sampled_lengths=sub_sampled_lengths
586
+ )
587
+
588
+ return hidden_states
589
+
590
+
591
+ # Copied from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2._compute_new_attention_mask
592
+ def _compute_new_attention_mask(hidden_states: torch.Tensor, seq_lens: torch.Tensor):
593
+ """
594
+ Computes an attention mask of the form `(batch, seq_len)` with an attention for each element in the batch that
595
+ stops at the corresponding element in `seq_lens`.
596
+ Args:
597
+ hidden_states (`torch.FloatTensor` of shape `(batch, seq_len, *)`):
598
+ The sequences to mask, where `*` is any number of sequence-specific dimensions including none.
599
+ seq_lens (`torch.Tensor` of shape `(batch)`:
600
+ Each element represents the length of the sequence at the same index in `hidden_states`
601
+ Returns:
602
+ `torch.FloatTensor`: The float attention mask of shape `(batch, seq_len)`
603
+ """
604
+ batch_size, mask_seq_len = hidden_states.shape[:2]
605
+
606
+ indices = torch.arange(mask_seq_len, device=seq_lens.device).expand(batch_size, -1)
607
+
608
+ bool_mask = indices >= seq_lens.unsqueeze(1).expand(-1, mask_seq_len)
609
+
610
+ mask = hidden_states.new_ones((batch_size, mask_seq_len))
611
+
612
+ mask = mask.masked_fill(bool_mask, 0)
613
+
614
+ return mask
615
+
616
+
617
+ class Wav2Vec2BertAdapterLayer(nn.Module):
618
+ def __init__(self, config):
619
+ super().__init__()
620
+ self.config = config
621
+
622
+ embed_dim = config.output_hidden_size
623
+ dropout = config.conformer_conv_dropout
624
+
625
+ self.kernel_size = config.adapter_kernel_size
626
+ self.stride = config.adapter_stride
627
+
628
+ # 1. residual convolution
629
+ self.residual_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
630
+ self.residual_conv = nn.Conv1d(
631
+ embed_dim,
632
+ 2 * embed_dim,
633
+ self.kernel_size,
634
+ stride=self.stride,
635
+ padding=self.stride // 2,
636
+ )
637
+ self.activation = nn.GLU(dim=1)
638
+
639
+ # Self-Attention
640
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
641
+ self.self_attn_conv = nn.Conv1d(
642
+ embed_dim,
643
+ 2 * embed_dim,
644
+ self.kernel_size,
645
+ stride=self.stride,
646
+ padding=self.stride // 2,
647
+ )
648
+ self.self_attn = Wav2Vec2BertSelfAttention(config, is_adapter_attention=True)
649
+ self.self_attn_dropout = nn.Dropout(dropout)
650
+
651
+ # Feed-forward
652
+ self.ffn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
653
+ self.ffn = Wav2Vec2BertFeedForward(config, act_fn=config.adapter_act, hidden_size=embed_dim)
654
+
655
+ def forward(
656
+ self,
657
+ hidden_states,
658
+ attention_mask: torch.Tensor | None = None,
659
+ output_attentions: bool = False,
660
+ sub_sampled_lengths: torch.Tensor | None = None,
661
+ ):
662
+ residual = self.residual_layer_norm(hidden_states)
663
+
664
+ # Apply pooling to the residual to match the sequence length of the
665
+ # multi-head attention output.
666
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
667
+ residual = residual.transpose(1, 2)
668
+ residual = self.residual_conv(residual)
669
+ residual = self.activation(residual)
670
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
671
+ residual = residual.transpose(1, 2)
672
+
673
+ hidden_states = self.self_attn_layer_norm(hidden_states)
674
+ # Apply pooling before feeding to the multihead-attention layer.
675
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
676
+ hidden_states = hidden_states.transpose(1, 2)
677
+ hidden_states = self.self_attn_conv(hidden_states)
678
+ hidden_states = self.activation(hidden_states)
679
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
680
+ hidden_states = hidden_states.transpose(1, 2)
681
+
682
+ if attention_mask is not None:
683
+ attention_mask = _compute_new_attention_mask(hidden_states=hidden_states, seq_lens=sub_sampled_lengths)
684
+ attention_mask = create_bidirectional_mask(
685
+ config=self.config,
686
+ inputs_embeds=hidden_states,
687
+ attention_mask=attention_mask,
688
+ )
689
+
690
+ # The rest of the computation is identical to a vanilla Transformer
691
+ # encoder layer.
692
+ hidden_states, attn_weights = self.self_attn(
693
+ hidden_states,
694
+ attention_mask=attention_mask,
695
+ output_attentions=output_attentions,
696
+ )
697
+ hidden_states = self.self_attn_dropout(hidden_states)
698
+ hidden_states = hidden_states + residual
699
+
700
+ residual = hidden_states
701
+
702
+ hidden_states = self.ffn_layer_norm(hidden_states)
703
+ hidden_states = self.ffn(hidden_states) + residual
704
+
705
+ return hidden_states
706
+
707
+
708
+ @auto_docstring
709
+ class Wav2Vec2BertPreTrainedModel(PreTrainedModel):
710
+ config: Wav2Vec2BertConfig
711
+ base_model_prefix = "wav2vec2_bert"
712
+ main_input_name = "input_features"
713
+ input_modalities = "audio"
714
+ supports_gradient_checkpointing = True
715
+
716
+ @torch.no_grad()
717
+ def _init_weights(self, module):
718
+ """Initialize the weights"""
719
+ if isinstance(module, Wav2Vec2BertSelfAttention):
720
+ if hasattr(module, "pos_bias_u"):
721
+ init.xavier_uniform_(module.pos_bias_u)
722
+ if hasattr(module, "pos_bias_v"):
723
+ init.xavier_uniform_(module.pos_bias_v)
724
+ elif isinstance(module, Wav2Vec2BertFeatureProjection):
725
+ k = math.sqrt(1 / module.projection.in_features)
726
+ init.uniform_(module.projection.weight, a=-k, b=k)
727
+ init.uniform_(module.projection.bias, a=-k, b=k)
728
+ elif isinstance(module, nn.Linear):
729
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
730
+
731
+ if module.bias is not None:
732
+ init.zeros_(module.bias)
733
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
734
+ init.zeros_(module.bias)
735
+ init.ones_(module.weight)
736
+ elif isinstance(module, nn.Conv1d):
737
+ init.kaiming_normal_(module.weight)
738
+
739
+ if module.bias is not None:
740
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
741
+ init.uniform_(module.bias, a=-k, b=k)
742
+ elif isinstance(module, Wav2Vec2BertModel):
743
+ if hasattr(module, "masked_spec_embed"):
744
+ init.uniform_(module.masked_spec_embed)
745
+ elif isinstance(
746
+ module,
747
+ (Wav2Vec2BertForSequenceClassification, Wav2Vec2BertForAudioFrameClassification, Wav2Vec2BertForXVector),
748
+ ):
749
+ if hasattr(module, "layer_weights"):
750
+ init.constant_(module.layer_weights, 1.0 / (self.config.num_hidden_layers + 1))
751
+ elif isinstance(module, AMSoftmaxLoss): # noqa: F821
752
+ init.normal_(module.weight)
753
+ elif isinstance(module, Wav2Vec2BertRotaryPositionalEmbedding):
754
+ dim = self.config.hidden_size // self.config.num_attention_heads
755
+ base = self.config.rotary_embedding_base
756
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
757
+ init.copy_(module.inv_freq, inv_freq)
758
+ elif isinstance(module, Wav2Vec2BertRelPositionalEmbedding):
759
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
760
+
761
+ # Ignore copy
762
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
763
+ """
764
+ Computes the output length of the convolutional layers
765
+ """
766
+
767
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
768
+
769
+ def _conv_out_length(input_length, kernel_size, stride, padding):
770
+ # 1D convolutional layer output length formula taken
771
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
772
+ return torch.div(input_length + 2 * padding - kernel_size, stride, rounding_mode="floor") + 1
773
+
774
+ if add_adapter:
775
+ padding = self.config.adapter_kernel_size // 2
776
+ for _ in range(self.config.num_adapter_layers):
777
+ input_lengths = _conv_out_length(
778
+ input_lengths, self.config.adapter_kernel_size, self.config.adapter_stride, padding
779
+ )
780
+
781
+ return input_lengths
782
+
783
+ def _get_feature_vector_attention_mask(
784
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
785
+ ):
786
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
787
+ # on inference mode.
788
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
789
+
790
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
791
+ output_lengths = output_lengths.to(torch.long)
792
+
793
+ batch_size = attention_mask.shape[0]
794
+
795
+ attention_mask = torch.zeros(
796
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
797
+ )
798
+ # these two operations makes sure that all values before the output lengths idxs are attended to
799
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
800
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
801
+ return attention_mask
802
+
803
+
804
+ def _compute_mask_indices(
805
+ shape: tuple[int, int],
806
+ mask_prob: float,
807
+ mask_length: int,
808
+ attention_mask: torch.LongTensor | None = None,
809
+ min_masks: int = 0,
810
+ ) -> np.ndarray:
811
+ """
812
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
813
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
814
+ CPU as part of the preprocessing during training.
815
+
816
+ Args:
817
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
818
+ the first element is the batch size and the second element is the length of the axis to span.
819
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
820
+ independently generated mask spans of length `mask_length` is computed by
821
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
822
+ actual percentage will be smaller.
823
+ mask_length: size of the mask
824
+ min_masks: minimum number of masked spans
825
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
826
+ each batch dimension.
827
+ """
828
+ batch_size, sequence_length = shape
829
+
830
+ if mask_length < 1:
831
+ raise ValueError("`mask_length` has to be bigger than 0.")
832
+
833
+ if mask_length > sequence_length:
834
+ raise ValueError(
835
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
836
+ f" and `sequence_length`: {sequence_length}`"
837
+ )
838
+
839
+ # epsilon is used for probabilistic rounding
840
+ epsilon = np.random.rand(1).item()
841
+
842
+ def compute_num_masked_span(input_length):
843
+ """Given input length, compute how many spans should be masked"""
844
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
845
+ num_masked_span = max(num_masked_span, min_masks)
846
+
847
+ # make sure num masked span <= sequence_length
848
+ if num_masked_span * mask_length > sequence_length:
849
+ num_masked_span = sequence_length // mask_length
850
+
851
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
852
+ if input_length - (mask_length - 1) < num_masked_span:
853
+ num_masked_span = max(input_length - (mask_length - 1), 0)
854
+
855
+ return num_masked_span
856
+
857
+ # compute number of masked spans in batch
858
+ input_lengths = (
859
+ attention_mask.detach().sum(-1).tolist()
860
+ if attention_mask is not None
861
+ else [sequence_length for _ in range(batch_size)]
862
+ )
863
+
864
+ # SpecAugment mask to fill
865
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
866
+ spec_aug_mask_idxs = []
867
+
868
+ max_num_masked_span = compute_num_masked_span(sequence_length)
869
+
870
+ if max_num_masked_span == 0:
871
+ return spec_aug_mask
872
+
873
+ for input_length in input_lengths:
874
+ # compute num of masked spans for this input
875
+ num_masked_span = compute_num_masked_span(input_length)
876
+
877
+ # get random indices to mask
878
+ spec_aug_mask_idx = np.random.choice(
879
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
880
+ )
881
+
882
+ # pick first sampled index that will serve as a dummy index to pad vector
883
+ # to ensure same dimension for all batches due to probabilistic rounding
884
+ # Picking first sample just pads those vectors twice.
885
+ if len(spec_aug_mask_idx) == 0:
886
+ # this case can only happen if `input_length` is strictly smaller then
887
+ # `sequence_length` in which case the last token has to be a padding
888
+ # token which we can use as a dummy mask id
889
+ dummy_mask_idx = sequence_length - 1
890
+ else:
891
+ dummy_mask_idx = spec_aug_mask_idx[0]
892
+
893
+ spec_aug_mask_idx = np.concatenate(
894
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
895
+ )
896
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
897
+
898
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
899
+
900
+ # expand masked indices to masked spans
901
+ spec_aug_mask_idxs = np.broadcast_to(
902
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
903
+ )
904
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
905
+
906
+ # add offset to the starting indexes so that indexes now create a span
907
+ offsets = np.arange(mask_length)[None, None, :]
908
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
909
+ batch_size, max_num_masked_span * mask_length
910
+ )
911
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
912
+
913
+ # ensure that we cannot have indices larger than sequence_length
914
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
915
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
916
+
917
+ # scatter indices to mask
918
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
919
+
920
+ return spec_aug_mask
921
+
922
+
923
+ Wav2Vec2BertBaseModelOutput = Wav2Vec2BaseModelOutput
924
+
925
+
926
+ @auto_docstring
927
+ class Wav2Vec2BertModel(Wav2Vec2BertPreTrainedModel):
928
+ def __init__(self, config: Wav2Vec2BertConfig):
929
+ super().__init__(config)
930
+ self.config = config
931
+ self.feature_projection = Wav2Vec2BertFeatureProjection(config)
932
+
933
+ # model only needs masking vector if mask prob is > 0.0
934
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
935
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
936
+
937
+ self.encoder = Wav2Vec2BertEncoder(config)
938
+
939
+ self.adapter = Wav2Vec2BertAdapter(config) if config.add_adapter else None
940
+
941
+ self.intermediate_ffn = None
942
+ if config.use_intermediate_ffn_before_adapter:
943
+ self.intermediate_ffn = Wav2Vec2BertFeedForward(config, act_fn="relu")
944
+
945
+ # Initialize weights and apply final processing
946
+ self.post_init()
947
+
948
+ def _mask_hidden_states(
949
+ self,
950
+ hidden_states: torch.FloatTensor,
951
+ mask_time_indices: torch.FloatTensor | None = None,
952
+ attention_mask: torch.LongTensor | None = None,
953
+ ):
954
+ """
955
+ Masks extracted features along time axis and/or along feature axis according to
956
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
957
+ """
958
+
959
+ # `config.apply_spec_augment` can set masking to False
960
+ if not getattr(self.config, "apply_spec_augment", True):
961
+ return hidden_states
962
+
963
+ # generate indices & apply SpecAugment along time axis
964
+ batch_size, sequence_length, hidden_size = hidden_states.size()
965
+
966
+ if mask_time_indices is not None:
967
+ # apply SpecAugment along time axis with given mask_time_indices
968
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
969
+ elif self.config.mask_time_prob > 0 and self.training:
970
+ mask_time_indices = _compute_mask_indices(
971
+ (batch_size, sequence_length),
972
+ mask_prob=self.config.mask_time_prob,
973
+ mask_length=self.config.mask_time_length,
974
+ attention_mask=attention_mask,
975
+ min_masks=self.config.mask_time_min_masks,
976
+ )
977
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
978
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
979
+
980
+ if self.config.mask_feature_prob > 0 and self.training:
981
+ # generate indices & apply SpecAugment along feature axis
982
+ mask_feature_indices = _compute_mask_indices(
983
+ (batch_size, hidden_size),
984
+ mask_prob=self.config.mask_feature_prob,
985
+ mask_length=self.config.mask_feature_length,
986
+ min_masks=self.config.mask_feature_min_masks,
987
+ )
988
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
989
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
990
+ hidden_states[mask_feature_indices] = 0
991
+
992
+ return hidden_states
993
+
994
+ @auto_docstring
995
+ def forward(
996
+ self,
997
+ input_features: torch.Tensor | None,
998
+ attention_mask: torch.Tensor | None = None,
999
+ mask_time_indices: torch.FloatTensor | None = None,
1000
+ output_attentions: bool | None = None,
1001
+ output_hidden_states: bool | None = None,
1002
+ return_dict: bool | None = None,
1003
+ **kwargs,
1004
+ ) -> tuple | Wav2Vec2BertBaseModelOutput:
1005
+ r"""
1006
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1007
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1008
+ masked extracted features in *config.proj_codevector_dim* space.
1009
+ """
1010
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1011
+ output_hidden_states = (
1012
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1013
+ )
1014
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1015
+
1016
+ hidden_states, extract_features = self.feature_projection(input_features)
1017
+ hidden_states = self._mask_hidden_states(
1018
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1019
+ )
1020
+
1021
+ encoder_outputs = self.encoder(
1022
+ hidden_states,
1023
+ attention_mask=attention_mask,
1024
+ output_attentions=output_attentions,
1025
+ output_hidden_states=output_hidden_states,
1026
+ return_dict=return_dict,
1027
+ )
1028
+
1029
+ hidden_states = encoder_outputs[0]
1030
+
1031
+ if self.intermediate_ffn:
1032
+ expanded_hidden_states = self.intermediate_ffn(hidden_states)
1033
+ hidden_states = hidden_states + 0.5 * expanded_hidden_states
1034
+
1035
+ if self.adapter is not None:
1036
+ hidden_states = self.adapter(hidden_states, attention_mask=attention_mask)
1037
+
1038
+ if not return_dict:
1039
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1040
+
1041
+ return Wav2Vec2BertBaseModelOutput(
1042
+ last_hidden_state=hidden_states,
1043
+ extract_features=extract_features,
1044
+ hidden_states=encoder_outputs.hidden_states,
1045
+ attentions=encoder_outputs.attentions,
1046
+ )
1047
+
1048
+
1049
+ _HIDDEN_STATES_START_POSITION = 2
1050
+
1051
+
1052
+ @auto_docstring(
1053
+ custom_intro="""
1054
+ Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1055
+ """
1056
+ )
1057
+ class Wav2Vec2BertForCTC(Wav2Vec2BertPreTrainedModel):
1058
+ def __init__(self, config, target_lang: str | None = None):
1059
+ r"""
1060
+ target_lang (`str`, *optional*):
1061
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1062
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
1063
+ default.
1064
+ """
1065
+ super().__init__(config)
1066
+
1067
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
1068
+ self.dropout = nn.Dropout(config.final_dropout)
1069
+
1070
+ self.target_lang = target_lang
1071
+
1072
+ if config.vocab_size is None:
1073
+ raise ValueError(
1074
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1075
+ "does not define the vocabulary size of the language model head. Please "
1076
+ "instantiate the model as follows: `Wav2Vec2BertForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1077
+ "or define `vocab_size` of your model's configuration."
1078
+ )
1079
+ output_hidden_size = (
1080
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1081
+ )
1082
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1083
+
1084
+ # Initialize weights and apply final processing
1085
+ self.post_init()
1086
+
1087
+ @auto_docstring
1088
+ def forward(
1089
+ self,
1090
+ input_features: torch.Tensor | None,
1091
+ attention_mask: torch.Tensor | None = None,
1092
+ output_attentions: bool | None = None,
1093
+ output_hidden_states: bool | None = None,
1094
+ return_dict: bool | None = None,
1095
+ labels: torch.Tensor | None = None,
1096
+ **kwargs,
1097
+ ) -> tuple | CausalLMOutput:
1098
+ r"""
1099
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1100
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1101
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1102
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1103
+ config.vocab_size - 1]`.
1104
+ """
1105
+ if labels is not None and labels.max() >= self.config.vocab_size:
1106
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1107
+
1108
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1109
+
1110
+ outputs = self.wav2vec2_bert(
1111
+ input_features,
1112
+ attention_mask=attention_mask,
1113
+ output_attentions=output_attentions,
1114
+ output_hidden_states=output_hidden_states,
1115
+ return_dict=return_dict,
1116
+ )
1117
+
1118
+ hidden_states = outputs[0]
1119
+ hidden_states = self.dropout(hidden_states)
1120
+
1121
+ logits = self.lm_head(hidden_states)
1122
+
1123
+ loss = None
1124
+ if labels is not None:
1125
+ # retrieve loss input_lengths from attention_mask
1126
+ attention_mask = (
1127
+ attention_mask
1128
+ if attention_mask is not None
1129
+ else torch.ones(input_features.shape[:2], device=input_features.device, dtype=torch.long)
1130
+ )
1131
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum([-1])).to(torch.long)
1132
+
1133
+ # assuming that padded tokens are filled with -100
1134
+ # when not being attended to
1135
+ labels_mask = labels >= 0
1136
+ target_lengths = labels_mask.sum(-1)
1137
+ flattened_targets = labels.masked_select(labels_mask)
1138
+
1139
+ # ctc_loss doesn't support fp16
1140
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1141
+
1142
+ with torch.backends.cudnn.flags(enabled=False):
1143
+ loss = nn.functional.ctc_loss(
1144
+ log_probs,
1145
+ flattened_targets,
1146
+ input_lengths,
1147
+ target_lengths,
1148
+ blank=self.config.pad_token_id,
1149
+ reduction=self.config.ctc_loss_reduction,
1150
+ zero_infinity=self.config.ctc_zero_infinity,
1151
+ )
1152
+
1153
+ if not return_dict:
1154
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1155
+ return ((loss,) + output) if loss is not None else output
1156
+
1157
+ return CausalLMOutput(
1158
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1159
+ )
1160
+
1161
+
1162
+ @auto_docstring(
1163
+ custom_intro="""
1164
+ Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1165
+ SUPERB Keyword Spotting.
1166
+ """
1167
+ )
1168
+ class Wav2Vec2BertForSequenceClassification(Wav2Vec2BertPreTrainedModel):
1169
+ def __init__(self, config):
1170
+ super().__init__(config)
1171
+
1172
+ if hasattr(config, "add_adapter") and config.add_adapter:
1173
+ raise ValueError(
1174
+ "Sequence classification does not support the use of Wav2Vec2Bert adapters (config.add_adapter=True)"
1175
+ )
1176
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
1177
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1178
+ if config.use_weighted_layer_sum:
1179
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1180
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1181
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1182
+
1183
+ # Initialize weights and apply final processing
1184
+ self.post_init()
1185
+
1186
+ def freeze_base_model(self):
1187
+ """
1188
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1189
+ be updated during training. Only the classification head will be updated.
1190
+ """
1191
+ for param in self.wav2vec2_bert.parameters():
1192
+ param.requires_grad = False
1193
+
1194
+ @auto_docstring
1195
+ def forward(
1196
+ self,
1197
+ input_features: torch.Tensor | None,
1198
+ attention_mask: torch.Tensor | None = None,
1199
+ output_attentions: bool | None = None,
1200
+ output_hidden_states: bool | None = None,
1201
+ return_dict: bool | None = None,
1202
+ labels: torch.Tensor | None = None,
1203
+ **kwargs,
1204
+ ) -> tuple | SequenceClassifierOutput:
1205
+ r"""
1206
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1207
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1208
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1209
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1210
+ """
1211
+
1212
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1213
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1214
+
1215
+ outputs = self.wav2vec2_bert(
1216
+ input_features,
1217
+ attention_mask=attention_mask,
1218
+ output_attentions=output_attentions,
1219
+ output_hidden_states=output_hidden_states,
1220
+ return_dict=return_dict,
1221
+ )
1222
+
1223
+ if self.config.use_weighted_layer_sum:
1224
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1225
+ hidden_states = torch.stack(hidden_states, dim=1)
1226
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1227
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1228
+ else:
1229
+ hidden_states = outputs[0]
1230
+
1231
+ hidden_states = self.projector(hidden_states)
1232
+ if attention_mask is None:
1233
+ pooled_output = hidden_states.mean(dim=1)
1234
+ else:
1235
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1236
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1237
+ hidden_states[~expand_padding_mask] = 0.0
1238
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1239
+
1240
+ logits = self.classifier(pooled_output)
1241
+
1242
+ loss = None
1243
+ if labels is not None:
1244
+ loss_fct = CrossEntropyLoss()
1245
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1246
+
1247
+ if not return_dict:
1248
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1249
+ return ((loss,) + output) if loss is not None else output
1250
+
1251
+ return SequenceClassifierOutput(
1252
+ loss=loss,
1253
+ logits=logits,
1254
+ hidden_states=outputs.hidden_states,
1255
+ attentions=outputs.attentions,
1256
+ )
1257
+
1258
+
1259
+ @auto_docstring
1260
+ class Wav2Vec2BertForAudioFrameClassification(Wav2Vec2BertPreTrainedModel):
1261
+ def __init__(self, config):
1262
+ super().__init__(config)
1263
+
1264
+ if hasattr(config, "add_adapter") and config.add_adapter:
1265
+ raise ValueError(
1266
+ "Audio frame classification does not support the use of Wav2Vec2Bert adapters (config.add_adapter=True)"
1267
+ )
1268
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
1269
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1270
+ if config.use_weighted_layer_sum:
1271
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1272
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1273
+ self.num_labels = config.num_labels
1274
+
1275
+ self.post_init()
1276
+
1277
+ def freeze_base_model(self):
1278
+ """
1279
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1280
+ be updated during training. Only the classification head will be updated.
1281
+ """
1282
+ for param in self.wav2vec2_bert.parameters():
1283
+ param.requires_grad = False
1284
+
1285
+ @auto_docstring
1286
+ def forward(
1287
+ self,
1288
+ input_features: torch.Tensor | None,
1289
+ attention_mask: torch.Tensor | None = None,
1290
+ labels: torch.Tensor | None = None,
1291
+ output_attentions: bool | None = None,
1292
+ output_hidden_states: bool | None = None,
1293
+ return_dict: bool | None = None,
1294
+ **kwargs,
1295
+ ) -> tuple | TokenClassifierOutput:
1296
+ r"""
1297
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1298
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1299
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1300
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1301
+ """
1302
+
1303
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1304
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1305
+
1306
+ outputs = self.wav2vec2_bert(
1307
+ input_features,
1308
+ attention_mask=attention_mask,
1309
+ output_attentions=output_attentions,
1310
+ output_hidden_states=output_hidden_states,
1311
+ return_dict=return_dict,
1312
+ )
1313
+
1314
+ if self.config.use_weighted_layer_sum:
1315
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1316
+ hidden_states = torch.stack(hidden_states, dim=1)
1317
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1318
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1319
+ else:
1320
+ hidden_states = outputs[0]
1321
+
1322
+ logits = self.classifier(hidden_states)
1323
+
1324
+ loss = None
1325
+ if labels is not None:
1326
+ loss_fct = CrossEntropyLoss()
1327
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
1328
+
1329
+ if not return_dict:
1330
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1331
+ return output
1332
+
1333
+ return TokenClassifierOutput(
1334
+ loss=loss,
1335
+ logits=logits,
1336
+ hidden_states=outputs.hidden_states,
1337
+ attentions=outputs.attentions,
1338
+ )
1339
+
1340
+
1341
+ class AMSoftmaxLoss(nn.Module):
1342
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
1343
+ super().__init__()
1344
+ self.scale = scale
1345
+ self.margin = margin
1346
+ self.num_labels = num_labels
1347
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
1348
+ self.loss = nn.CrossEntropyLoss()
1349
+
1350
+ def forward(self, hidden_states, labels):
1351
+ labels = labels.flatten()
1352
+ weight = nn.functional.normalize(self.weight, dim=0)
1353
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
1354
+ cos_theta = torch.mm(hidden_states, weight)
1355
+ psi = cos_theta - self.margin
1356
+
1357
+ onehot = nn.functional.one_hot(labels, self.num_labels)
1358
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
1359
+ loss = self.loss(logits, labels)
1360
+
1361
+ return loss
1362
+
1363
+
1364
+ class TDNNLayer(nn.Module):
1365
+ def __init__(self, config, layer_id=0):
1366
+ super().__init__()
1367
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
1368
+ self.out_conv_dim = config.tdnn_dim[layer_id]
1369
+ self.kernel_size = config.tdnn_kernel[layer_id]
1370
+ self.dilation = config.tdnn_dilation[layer_id]
1371
+
1372
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
1373
+ self.activation = nn.ReLU()
1374
+
1375
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1376
+ if is_peft_available():
1377
+ from peft.tuners.lora import LoraLayer
1378
+
1379
+ if is_peft_available():
1380
+ if isinstance(self.kernel, LoraLayer):
1381
+ warnings.warn(
1382
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
1383
+ "You should exclude TDNNLayer from LoRA's target modules.",
1384
+ )
1385
+
1386
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
1387
+ hidden_states = hidden_states.transpose(1, 2)
1388
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
1389
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
1390
+ hidden_states = hidden_states.transpose(1, 2)
1391
+
1392
+ hidden_states = self.activation(hidden_states)
1393
+ return hidden_states
1394
+
1395
+
1396
+ @auto_docstring(
1397
+ custom_intro="""
1398
+ Wav2Vec2Bert Model with an XVector feature extraction head on top for tasks like Speaker Verification.
1399
+ """
1400
+ )
1401
+ class Wav2Vec2BertForXVector(Wav2Vec2BertPreTrainedModel):
1402
+ def __init__(self, config):
1403
+ super().__init__(config)
1404
+
1405
+ self.wav2vec2_bert = Wav2Vec2BertModel(config)
1406
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1407
+ if config.use_weighted_layer_sum:
1408
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1409
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
1410
+
1411
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
1412
+ self.tdnn = nn.ModuleList(tdnn_layers)
1413
+
1414
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
1415
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
1416
+
1417
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
1418
+
1419
+ self.post_init()
1420
+
1421
+ def freeze_base_model(self):
1422
+ """
1423
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1424
+ be updated during training. Only the classification head will be updated.
1425
+ """
1426
+ for param in self.wav2vec2_bert.parameters():
1427
+ param.requires_grad = False
1428
+
1429
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
1430
+ """
1431
+ Computes the output length of the TDNN layers
1432
+ """
1433
+
1434
+ def _conv_out_length(input_length, kernel_size, stride):
1435
+ # 1D convolutional layer output length formula taken
1436
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1437
+ return (input_length - kernel_size) // stride + 1
1438
+
1439
+ for kernel_size in self.config.tdnn_kernel:
1440
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
1441
+
1442
+ return input_lengths
1443
+
1444
+ @auto_docstring
1445
+ def forward(
1446
+ self,
1447
+ input_features: torch.Tensor | None,
1448
+ attention_mask: torch.Tensor | None = None,
1449
+ output_attentions: bool | None = None,
1450
+ output_hidden_states: bool | None = None,
1451
+ return_dict: bool | None = None,
1452
+ labels: torch.Tensor | None = None,
1453
+ **kwargs,
1454
+ ) -> tuple | XVectorOutput:
1455
+ r"""
1456
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1457
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1458
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1459
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1460
+ """
1461
+
1462
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1463
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1464
+
1465
+ outputs = self.wav2vec2_bert(
1466
+ input_features,
1467
+ attention_mask=attention_mask,
1468
+ output_attentions=output_attentions,
1469
+ output_hidden_states=output_hidden_states,
1470
+ return_dict=return_dict,
1471
+ )
1472
+
1473
+ if self.config.use_weighted_layer_sum:
1474
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1475
+ hidden_states = torch.stack(hidden_states, dim=1)
1476
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1477
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1478
+ else:
1479
+ hidden_states = outputs[0]
1480
+
1481
+ hidden_states = self.projector(hidden_states)
1482
+
1483
+ for tdnn_layer in self.tdnn:
1484
+ hidden_states = tdnn_layer(hidden_states)
1485
+
1486
+ # Statistic Pooling
1487
+ if attention_mask is None:
1488
+ mean_features = hidden_states.mean(dim=1)
1489
+ std_features = hidden_states.std(dim=1)
1490
+ else:
1491
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
1492
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
1493
+ mean_features = []
1494
+ std_features = []
1495
+ for i, length in enumerate(tdnn_output_lengths):
1496
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
1497
+ std_features.append(hidden_states[i, :length].std(dim=0))
1498
+ mean_features = torch.stack(mean_features)
1499
+ std_features = torch.stack(std_features)
1500
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
1501
+
1502
+ output_embeddings = self.feature_extractor(statistic_pooling)
1503
+ logits = self.classifier(output_embeddings)
1504
+
1505
+ loss = None
1506
+ if labels is not None:
1507
+ loss = self.objective(logits, labels)
1508
+
1509
+ if not return_dict:
1510
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
1511
+ return ((loss,) + output) if loss is not None else output
1512
+
1513
+ return XVectorOutput(
1514
+ loss=loss,
1515
+ logits=logits,
1516
+ embeddings=output_embeddings,
1517
+ hidden_states=outputs.hidden_states,
1518
+ attentions=outputs.attentions,
1519
+ )
1520
+
1521
+
1522
+ __all__ = [
1523
+ "Wav2Vec2BertForAudioFrameClassification",
1524
+ "Wav2Vec2BertForCTC",
1525
+ "Wav2Vec2BertForSequenceClassification",
1526
+ "Wav2Vec2BertForXVector",
1527
+ "Wav2Vec2BertModel",
1528
+ "Wav2Vec2BertPreTrainedModel",
1529
+ ]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import CrossEntropyLoss
6
+
7
+ from ... import initialization as init
8
+ from ...activations import ACT2FN
9
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
10
+ from ...integrations.fsdp import is_fsdp_managed_module
11
+ from ...masking_utils import create_bidirectional_mask
12
+ from ...modeling_layers import GradientCheckpointingLayer
13
+ from ...modeling_outputs import (
14
+ BaseModelOutput,
15
+ CausalLMOutput,
16
+ SequenceClassifierOutput,
17
+ TokenClassifierOutput,
18
+ Wav2Vec2BaseModelOutput,
19
+ XVectorOutput,
20
+ )
21
+ from ...modeling_utils import PreTrainedModel
22
+ from ...utils import auto_docstring, logging
23
+ from ..wav2vec2.modeling_wav2vec2 import Wav2Vec2FeedForward, Wav2Vec2ForSequenceClassification, Wav2Vec2Model
24
+ from ..wav2vec2_conformer.modeling_wav2vec2_conformer import (
25
+ Wav2Vec2ConformerForAudioFrameClassification,
26
+ Wav2Vec2ConformerForCTC,
27
+ Wav2Vec2ConformerForXVector,
28
+ Wav2Vec2ConformerRelPositionalEmbedding,
29
+ Wav2Vec2ConformerRotaryPositionalEmbedding,
30
+ Wav2Vec2ConformerSelfAttention,
31
+ )
32
+ from .configuration_wav2vec2_bert import Wav2Vec2BertConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ _HIDDEN_STATES_START_POSITION = 2
39
+
40
+
41
+ # Copied from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2._compute_new_attention_mask
42
+ def _compute_new_attention_mask(hidden_states: torch.Tensor, seq_lens: torch.Tensor):
43
+ """
44
+ Computes an attention mask of the form `(batch, seq_len)` with an attention for each element in the batch that
45
+ stops at the corresponding element in `seq_lens`.
46
+ Args:
47
+ hidden_states (`torch.FloatTensor` of shape `(batch, seq_len, *)`):
48
+ The sequences to mask, where `*` is any number of sequence-specific dimensions including none.
49
+ seq_lens (`torch.Tensor` of shape `(batch)`:
50
+ Each element represents the length of the sequence at the same index in `hidden_states`
51
+ Returns:
52
+ `torch.FloatTensor`: The float attention mask of shape `(batch, seq_len)`
53
+ """
54
+ batch_size, mask_seq_len = hidden_states.shape[:2]
55
+
56
+ indices = torch.arange(mask_seq_len, device=seq_lens.device).expand(batch_size, -1)
57
+
58
+ bool_mask = indices >= seq_lens.unsqueeze(1).expand(-1, mask_seq_len)
59
+
60
+ mask = hidden_states.new_ones((batch_size, mask_seq_len))
61
+
62
+ mask = mask.masked_fill(bool_mask, 0)
63
+
64
+ return mask
65
+
66
+
67
+ class Wav2Vec2BertRotaryPositionalEmbedding(Wav2Vec2ConformerRotaryPositionalEmbedding):
68
+ def __init__(self, config):
69
+ nn.Module.__init__(self)
70
+ dim = config.hidden_size // config.num_attention_heads
71
+ base = config.rotary_embedding_base
72
+
73
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
74
+ # Ignore copy
75
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
76
+ self.cached_sequence_length = None
77
+ self.cached_rotary_positional_embedding = None
78
+
79
+
80
+ class Wav2Vec2BertRelPositionalEmbedding(Wav2Vec2ConformerRelPositionalEmbedding):
81
+ pass
82
+
83
+
84
+ class Wav2Vec2BertFeatureProjection(nn.Module):
85
+ def __init__(self, config):
86
+ super().__init__()
87
+ self.layer_norm = nn.LayerNorm(config.feature_projection_input_dim, eps=config.layer_norm_eps)
88
+ self.projection = nn.Linear(config.feature_projection_input_dim, config.hidden_size)
89
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
90
+
91
+ def forward(self, hidden_states):
92
+ # non-projected hidden states are needed for quantization
93
+ norm_hidden_states = self.layer_norm(hidden_states)
94
+ hidden_states = self.projection(norm_hidden_states)
95
+ hidden_states = self.dropout(hidden_states)
96
+ return hidden_states, norm_hidden_states
97
+
98
+
99
+ class Wav2Vec2BertFeedForward(Wav2Vec2FeedForward):
100
+ def __init__(self, config, act_fn=None, hidden_size=None):
101
+ nn.Module.__init__(self)
102
+ act_fn = act_fn if act_fn is not None else config.hidden_act
103
+ hidden_size = hidden_size if hidden_size is not None else config.hidden_size
104
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
105
+
106
+ self.intermediate_dense = nn.Linear(hidden_size, config.intermediate_size)
107
+ self.intermediate_act_fn = ACT2FN[act_fn] if isinstance(act_fn, str) else act_fn
108
+
109
+ self.output_dense = nn.Linear(config.intermediate_size, hidden_size)
110
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
111
+
112
+
113
+ class Wav2Vec2BertConvolutionModule(nn.Module):
114
+ """Convolution block used in the conformer block"""
115
+
116
+ def __init__(self, config):
117
+ super().__init__()
118
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
119
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
120
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
121
+ self.pointwise_conv1 = nn.Conv1d(
122
+ config.hidden_size,
123
+ 2 * config.hidden_size,
124
+ kernel_size=1,
125
+ stride=1,
126
+ padding=0,
127
+ bias=False,
128
+ )
129
+ self.glu = nn.GLU(dim=1)
130
+ self.depthwise_conv = nn.Conv1d(
131
+ config.hidden_size,
132
+ config.hidden_size,
133
+ config.conv_depthwise_kernel_size,
134
+ stride=1,
135
+ padding=0,
136
+ groups=config.hidden_size,
137
+ bias=False,
138
+ )
139
+
140
+ self.depthwise_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
141
+ self.activation = ACT2FN[config.hidden_act]
142
+ self.pointwise_conv2 = nn.Conv1d(
143
+ config.hidden_size,
144
+ config.hidden_size,
145
+ kernel_size=1,
146
+ stride=1,
147
+ padding=0,
148
+ bias=False,
149
+ )
150
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
151
+
152
+ def forward(self, hidden_states, attention_mask=None):
153
+ hidden_states = self.layer_norm(hidden_states)
154
+
155
+ # Ensure that we do not leak padded positions in depthwise convolution if attention mask is passed.
156
+ # Put 0 where necessary
157
+ if attention_mask is not None:
158
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
159
+
160
+ # exchange the temporal dimension and the feature dimension
161
+ hidden_states = hidden_states.transpose(1, 2)
162
+
163
+ # GLU mechanism
164
+ # => (batch, 2*channel, dim)
165
+ hidden_states = self.pointwise_conv1(hidden_states)
166
+ # => (batch, channel, dim)
167
+ hidden_states = self.glu(hidden_states)
168
+
169
+ # Pad the sequence entirely on the left because of causal convolution.
170
+ hidden_states = torch.nn.functional.pad(hidden_states, (self.depthwise_conv.kernel_size[0] - 1, 0))
171
+
172
+ # 1D Depthwise Conv
173
+ hidden_states = self.depthwise_conv(hidden_states)
174
+
175
+ hidden_states = self.depthwise_layer_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
176
+
177
+ hidden_states = self.activation(hidden_states)
178
+
179
+ hidden_states = self.pointwise_conv2(hidden_states)
180
+ hidden_states = self.dropout(hidden_states)
181
+ hidden_states = hidden_states.transpose(1, 2)
182
+ return hidden_states
183
+
184
+
185
+ class Wav2Vec2BertSelfAttention(Wav2Vec2ConformerSelfAttention, nn.Module):
186
+ """Construct an Wav2Vec2BertSelfAttention object.
187
+ Can be enhanced with rotary or relative position embeddings.
188
+ """
189
+
190
+ def __init__(self, config, is_adapter_attention=False):
191
+ nn.Module.__init__(self)
192
+ hidden_size = config.hidden_size if not is_adapter_attention else config.output_hidden_size
193
+
194
+ self.head_size = hidden_size // config.num_attention_heads
195
+ self.num_heads = config.num_attention_heads
196
+ self.position_embeddings_type = config.position_embeddings_type if not is_adapter_attention else None
197
+
198
+ self.linear_q = nn.Linear(hidden_size, hidden_size)
199
+ self.linear_k = nn.Linear(hidden_size, hidden_size)
200
+ self.linear_v = nn.Linear(hidden_size, hidden_size)
201
+ self.linear_out = nn.Linear(hidden_size, hidden_size)
202
+
203
+ self.dropout = nn.Dropout(p=config.attention_dropout)
204
+
205
+ if self.position_embeddings_type == "relative":
206
+ # linear transformation for positional encoding
207
+ self.linear_pos = nn.Linear(hidden_size, hidden_size, bias=False)
208
+ # these two learnable bias are used in matrix c and matrix d
209
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
210
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
211
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
212
+
213
+ if self.position_embeddings_type == "relative_key":
214
+ self.left_max_position_embeddings = config.left_max_position_embeddings
215
+ self.right_max_position_embeddings = config.right_max_position_embeddings
216
+ num_positions = self.left_max_position_embeddings + self.right_max_position_embeddings + 1
217
+ self.distance_embedding = nn.Embedding(num_positions, self.head_size)
218
+
219
+ def forward(
220
+ self,
221
+ hidden_states: torch.Tensor,
222
+ attention_mask: torch.Tensor | None = None,
223
+ relative_position_embeddings: torch.Tensor | None = None,
224
+ output_attentions: bool = False,
225
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
226
+ # self-attention mechanism
227
+ batch_size, sequence_length, hidden_size = hidden_states.size()
228
+
229
+ # make sure query/key states can be != value states
230
+ query_key_states = hidden_states
231
+ value_states = hidden_states
232
+
233
+ if self.position_embeddings_type == "rotary":
234
+ if relative_position_embeddings is None:
235
+ raise ValueError(
236
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
237
+ )
238
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
239
+
240
+ # project query_key_states and value_states
241
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
242
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
243
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
244
+
245
+ # => (batch, head, time1, d_k)
246
+ query = query.transpose(1, 2)
247
+ key = key.transpose(1, 2)
248
+ value = value.transpose(1, 2)
249
+
250
+ if self.position_embeddings_type == "relative":
251
+ if relative_position_embeddings is None:
252
+ raise ValueError(
253
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
254
+ " 'relative'"
255
+ )
256
+ # apply relative_position_embeddings to qk scores
257
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
258
+ scores = self._apply_relative_embeddings(
259
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
260
+ )
261
+ else:
262
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
263
+
264
+ if self.position_embeddings_type == "relative_key":
265
+ query_length, key_length = query.shape[2], key.shape[2]
266
+
267
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
268
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
269
+ distance = position_ids_r - position_ids_l
270
+ distance = torch.clamp(distance, -self.left_max_position_embeddings, self.right_max_position_embeddings)
271
+
272
+ positional_embedding = self.distance_embedding(distance + self.left_max_position_embeddings)
273
+ positional_embedding = positional_embedding.to(dtype=query.dtype) # fp16 compatibility
274
+
275
+ relative_position_attn_weights = torch.einsum("bhld,lrd->bhlr", query, positional_embedding)
276
+ scores = scores + (relative_position_attn_weights / math.sqrt(self.head_size))
277
+
278
+ # apply attention_mask if necessary
279
+ if attention_mask is not None:
280
+ scores = scores + attention_mask
281
+
282
+ # => (batch, head, time1, time2)
283
+ probs = torch.softmax(scores, dim=-1)
284
+ probs = self.dropout(probs)
285
+
286
+ # => (batch, head, time1, d_k)
287
+ hidden_states = torch.matmul(probs, value)
288
+
289
+ # => (batch, time1, hidden_size)
290
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
291
+ hidden_states = self.linear_out(hidden_states)
292
+
293
+ return hidden_states, probs
294
+
295
+
296
+ class Wav2Vec2BertEncoderLayer(GradientCheckpointingLayer):
297
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
298
+
299
+ def __init__(self, config):
300
+ super().__init__()
301
+ embed_dim = config.hidden_size
302
+ dropout = config.attention_dropout
303
+
304
+ # Feed-forward 1
305
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
306
+ self.ffn1 = Wav2Vec2BertFeedForward(config)
307
+
308
+ # Self-Attention
309
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
310
+ self.self_attn_dropout = nn.Dropout(dropout)
311
+ self.self_attn = Wav2Vec2BertSelfAttention(config)
312
+
313
+ # Conformer Convolution
314
+ self.conv_module = Wav2Vec2BertConvolutionModule(config)
315
+
316
+ # Feed-forward 2
317
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
318
+ self.ffn2 = Wav2Vec2BertFeedForward(config)
319
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
320
+
321
+ def forward(
322
+ self,
323
+ hidden_states,
324
+ attention_mask: torch.Tensor | None = None,
325
+ relative_position_embeddings: torch.Tensor | None = None,
326
+ output_attentions: bool = False,
327
+ conv_attention_mask: torch.Tensor | None = None,
328
+ ):
329
+ # 1. Feed-Forward 1 layer
330
+ residual = hidden_states
331
+ hidden_states = self.ffn1_layer_norm(hidden_states)
332
+ hidden_states = self.ffn1(hidden_states)
333
+ hidden_states = hidden_states * 0.5 + residual
334
+ residual = hidden_states
335
+
336
+ # 2. Self-Attention layer
337
+ hidden_states = self.self_attn_layer_norm(hidden_states)
338
+ hidden_states, attn_weigts = self.self_attn(
339
+ hidden_states=hidden_states,
340
+ attention_mask=attention_mask,
341
+ relative_position_embeddings=relative_position_embeddings,
342
+ output_attentions=output_attentions,
343
+ )
344
+ hidden_states = self.self_attn_dropout(hidden_states)
345
+ hidden_states = hidden_states + residual
346
+
347
+ # 3. Convolutional Layer
348
+ residual = hidden_states
349
+ hidden_states = self.conv_module(hidden_states, attention_mask=conv_attention_mask)
350
+ hidden_states = residual + hidden_states
351
+
352
+ # 4. Feed-Forward 2 Layer
353
+ residual = hidden_states
354
+ hidden_states = self.ffn2_layer_norm(hidden_states)
355
+ hidden_states = self.ffn2(hidden_states)
356
+ hidden_states = hidden_states * 0.5 + residual
357
+ hidden_states = self.final_layer_norm(hidden_states)
358
+
359
+ return hidden_states, attn_weigts
360
+
361
+
362
+ class Wav2Vec2BertEncoder(nn.Module):
363
+ def __init__(self, config):
364
+ super().__init__()
365
+ self.config = config
366
+
367
+ if config.position_embeddings_type == "relative":
368
+ self.embed_positions = Wav2Vec2BertRelPositionalEmbedding(config)
369
+ elif config.position_embeddings_type == "rotary":
370
+ self.embed_positions = Wav2Vec2BertRotaryPositionalEmbedding(config)
371
+ else:
372
+ self.embed_positions = None
373
+
374
+ self.dropout = nn.Dropout(config.hidden_dropout)
375
+ self.layers = nn.ModuleList([Wav2Vec2BertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
376
+ self.gradient_checkpointing = False
377
+
378
+ def forward(
379
+ self,
380
+ hidden_states,
381
+ attention_mask=None,
382
+ output_attentions=False,
383
+ output_hidden_states=False,
384
+ return_dict=True,
385
+ ):
386
+ all_hidden_states = () if output_hidden_states else None
387
+ all_self_attentions = () if output_attentions else None
388
+
389
+ conv_attention_mask = attention_mask
390
+ if attention_mask is not None:
391
+ # make sure padded tokens output 0
392
+ hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0)
393
+
394
+ # extend attention_mask
395
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
396
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
397
+ attention_mask = attention_mask.expand(
398
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
399
+ )
400
+
401
+ hidden_states = self.dropout(hidden_states)
402
+
403
+ if self.embed_positions is not None:
404
+ relative_position_embeddings = self.embed_positions(hidden_states)
405
+ else:
406
+ relative_position_embeddings = None
407
+
408
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
409
+
410
+ for i, layer in enumerate(self.layers):
411
+ if output_hidden_states:
412
+ all_hidden_states = all_hidden_states + (hidden_states,)
413
+
414
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
415
+ dropout_probability = torch.rand([])
416
+
417
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
418
+ if not skip_the_layer or synced_gpus:
419
+ # under fsdp or deepspeed zero3 all gpus must run in sync
420
+ layer_outputs = layer(
421
+ hidden_states,
422
+ attention_mask=attention_mask,
423
+ relative_position_embeddings=relative_position_embeddings,
424
+ output_attentions=output_attentions,
425
+ conv_attention_mask=conv_attention_mask,
426
+ )
427
+ hidden_states = layer_outputs[0]
428
+
429
+ if skip_the_layer:
430
+ layer_outputs = (None, None)
431
+
432
+ if output_attentions:
433
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
434
+
435
+ if output_hidden_states:
436
+ all_hidden_states = all_hidden_states + (hidden_states,)
437
+
438
+ if not return_dict:
439
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
440
+ return BaseModelOutput(
441
+ last_hidden_state=hidden_states,
442
+ hidden_states=all_hidden_states,
443
+ attentions=all_self_attentions,
444
+ )
445
+
446
+
447
+ class Wav2Vec2BertAdapter(nn.Module):
448
+ def __init__(self, config):
449
+ super().__init__()
450
+ # feature dim might need to be down-projected
451
+ if config.output_hidden_size != config.hidden_size:
452
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
453
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size, eps=config.layer_norm_eps)
454
+ else:
455
+ self.proj = self.proj_layer_norm = None
456
+ self.layers = nn.ModuleList(Wav2Vec2BertAdapterLayer(config) for _ in range(config.num_adapter_layers))
457
+ self.layerdrop = config.layerdrop
458
+
459
+ self.kernel_size = config.adapter_kernel_size
460
+ self.stride = config.adapter_stride
461
+
462
+ def _compute_sub_sample_lengths_from_attention_mask(self, seq_lens):
463
+ if seq_lens is None:
464
+ return seq_lens
465
+ pad = self.kernel_size // 2
466
+ seq_lens = ((seq_lens + 2 * pad - self.kernel_size) / self.stride) + 1
467
+ return seq_lens.floor()
468
+
469
+ def forward(self, hidden_states, attention_mask=None):
470
+ # down project hidden_states if necessary
471
+ if self.proj is not None and self.proj_layer_norm is not None:
472
+ hidden_states = self.proj(hidden_states)
473
+ hidden_states = self.proj_layer_norm(hidden_states)
474
+
475
+ sub_sampled_lengths = None
476
+ if attention_mask is not None:
477
+ sub_sampled_lengths = (attention_mask.size(1) - (1 - attention_mask.int()).sum(1)).to(hidden_states.device)
478
+
479
+ for layer in self.layers:
480
+ layerdrop_prob = torch.rand([])
481
+ sub_sampled_lengths = self._compute_sub_sample_lengths_from_attention_mask(sub_sampled_lengths)
482
+ if not self.training or (layerdrop_prob > self.layerdrop):
483
+ hidden_states = layer(
484
+ hidden_states, attention_mask=attention_mask, sub_sampled_lengths=sub_sampled_lengths
485
+ )
486
+
487
+ return hidden_states
488
+
489
+
490
+ class Wav2Vec2BertAdapterLayer(nn.Module):
491
+ def __init__(self, config):
492
+ super().__init__()
493
+ self.config = config
494
+
495
+ embed_dim = config.output_hidden_size
496
+ dropout = config.conformer_conv_dropout
497
+
498
+ self.kernel_size = config.adapter_kernel_size
499
+ self.stride = config.adapter_stride
500
+
501
+ # 1. residual convolution
502
+ self.residual_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
503
+ self.residual_conv = nn.Conv1d(
504
+ embed_dim,
505
+ 2 * embed_dim,
506
+ self.kernel_size,
507
+ stride=self.stride,
508
+ padding=self.stride // 2,
509
+ )
510
+ self.activation = nn.GLU(dim=1)
511
+
512
+ # Self-Attention
513
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
514
+ self.self_attn_conv = nn.Conv1d(
515
+ embed_dim,
516
+ 2 * embed_dim,
517
+ self.kernel_size,
518
+ stride=self.stride,
519
+ padding=self.stride // 2,
520
+ )
521
+ self.self_attn = Wav2Vec2BertSelfAttention(config, is_adapter_attention=True)
522
+ self.self_attn_dropout = nn.Dropout(dropout)
523
+
524
+ # Feed-forward
525
+ self.ffn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
526
+ self.ffn = Wav2Vec2BertFeedForward(config, act_fn=config.adapter_act, hidden_size=embed_dim)
527
+
528
+ def forward(
529
+ self,
530
+ hidden_states,
531
+ attention_mask: torch.Tensor | None = None,
532
+ output_attentions: bool = False,
533
+ sub_sampled_lengths: torch.Tensor | None = None,
534
+ ):
535
+ residual = self.residual_layer_norm(hidden_states)
536
+
537
+ # Apply pooling to the residual to match the sequence length of the
538
+ # multi-head attention output.
539
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
540
+ residual = residual.transpose(1, 2)
541
+ residual = self.residual_conv(residual)
542
+ residual = self.activation(residual)
543
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
544
+ residual = residual.transpose(1, 2)
545
+
546
+ hidden_states = self.self_attn_layer_norm(hidden_states)
547
+ # Apply pooling before feeding to the multihead-attention layer.
548
+ # (batch, seq_len, feature_dim) -> (batch, feature_dim, seq_len)
549
+ hidden_states = hidden_states.transpose(1, 2)
550
+ hidden_states = self.self_attn_conv(hidden_states)
551
+ hidden_states = self.activation(hidden_states)
552
+ # (batch, feature_dim, seq_len) -> (batch, seq_len, feature_dim)
553
+ hidden_states = hidden_states.transpose(1, 2)
554
+
555
+ if attention_mask is not None:
556
+ attention_mask = _compute_new_attention_mask(hidden_states=hidden_states, seq_lens=sub_sampled_lengths)
557
+ attention_mask = create_bidirectional_mask(
558
+ config=self.config,
559
+ inputs_embeds=hidden_states,
560
+ attention_mask=attention_mask,
561
+ )
562
+
563
+ # The rest of the computation is identical to a vanilla Transformer
564
+ # encoder layer.
565
+ hidden_states, attn_weights = self.self_attn(
566
+ hidden_states,
567
+ attention_mask=attention_mask,
568
+ output_attentions=output_attentions,
569
+ )
570
+ hidden_states = self.self_attn_dropout(hidden_states)
571
+ hidden_states = hidden_states + residual
572
+
573
+ residual = hidden_states
574
+
575
+ hidden_states = self.ffn_layer_norm(hidden_states)
576
+ hidden_states = self.ffn(hidden_states) + residual
577
+
578
+ return hidden_states
579
+
580
+
581
+ @auto_docstring
582
+ class Wav2Vec2BertPreTrainedModel(PreTrainedModel):
583
+ config: Wav2Vec2BertConfig
584
+ base_model_prefix = "wav2vec2_bert"
585
+ main_input_name = "input_features"
586
+ input_modalities = "audio"
587
+ supports_gradient_checkpointing = True
588
+
589
+ @torch.no_grad()
590
+ def _init_weights(self, module):
591
+ """Initialize the weights"""
592
+ if isinstance(module, Wav2Vec2BertSelfAttention):
593
+ if hasattr(module, "pos_bias_u"):
594
+ init.xavier_uniform_(module.pos_bias_u)
595
+ if hasattr(module, "pos_bias_v"):
596
+ init.xavier_uniform_(module.pos_bias_v)
597
+ elif isinstance(module, Wav2Vec2BertFeatureProjection):
598
+ k = math.sqrt(1 / module.projection.in_features)
599
+ init.uniform_(module.projection.weight, a=-k, b=k)
600
+ init.uniform_(module.projection.bias, a=-k, b=k)
601
+ elif isinstance(module, nn.Linear):
602
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
603
+
604
+ if module.bias is not None:
605
+ init.zeros_(module.bias)
606
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
607
+ init.zeros_(module.bias)
608
+ init.ones_(module.weight)
609
+ elif isinstance(module, nn.Conv1d):
610
+ init.kaiming_normal_(module.weight)
611
+
612
+ if module.bias is not None:
613
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
614
+ init.uniform_(module.bias, a=-k, b=k)
615
+ elif isinstance(module, Wav2Vec2BertModel):
616
+ if hasattr(module, "masked_spec_embed"):
617
+ init.uniform_(module.masked_spec_embed)
618
+ elif isinstance(
619
+ module,
620
+ (Wav2Vec2BertForSequenceClassification, Wav2Vec2BertForAudioFrameClassification, Wav2Vec2BertForXVector),
621
+ ):
622
+ if hasattr(module, "layer_weights"):
623
+ init.constant_(module.layer_weights, 1.0 / (self.config.num_hidden_layers + 1))
624
+ elif isinstance(module, AMSoftmaxLoss): # noqa: F821
625
+ init.normal_(module.weight)
626
+ elif isinstance(module, Wav2Vec2BertRotaryPositionalEmbedding):
627
+ dim = self.config.hidden_size // self.config.num_attention_heads
628
+ base = self.config.rotary_embedding_base
629
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
630
+ init.copy_(module.inv_freq, inv_freq)
631
+ elif isinstance(module, Wav2Vec2BertRelPositionalEmbedding):
632
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
633
+
634
+ # Ignore copy
635
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
636
+ """
637
+ Computes the output length of the convolutional layers
638
+ """
639
+
640
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
641
+
642
+ def _conv_out_length(input_length, kernel_size, stride, padding):
643
+ # 1D convolutional layer output length formula taken
644
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
645
+ return torch.div(input_length + 2 * padding - kernel_size, stride, rounding_mode="floor") + 1
646
+
647
+ if add_adapter:
648
+ padding = self.config.adapter_kernel_size // 2
649
+ for _ in range(self.config.num_adapter_layers):
650
+ input_lengths = _conv_out_length(
651
+ input_lengths, self.config.adapter_kernel_size, self.config.adapter_stride, padding
652
+ )
653
+
654
+ return input_lengths
655
+
656
+ def _get_feature_vector_attention_mask(
657
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
658
+ ):
659
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
660
+ # on inference mode.
661
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
662
+
663
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
664
+ output_lengths = output_lengths.to(torch.long)
665
+
666
+ batch_size = attention_mask.shape[0]
667
+
668
+ attention_mask = torch.zeros(
669
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
670
+ )
671
+ # these two operations makes sure that all values before the output lengths idxs are attended to
672
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
673
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
674
+ return attention_mask
675
+
676
+
677
+ Wav2Vec2BertBaseModelOutput = Wav2Vec2BaseModelOutput
678
+
679
+
680
+ class Wav2Vec2BertModel(Wav2Vec2Model, Wav2Vec2BertPreTrainedModel):
681
+ def __init__(self, config: Wav2Vec2BertConfig):
682
+ Wav2Vec2BertPreTrainedModel.__init__(self, config)
683
+ self.config = config
684
+ self.feature_projection = Wav2Vec2BertFeatureProjection(config)
685
+
686
+ # model only needs masking vector if mask prob is > 0.0
687
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
688
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
689
+
690
+ self.encoder = Wav2Vec2BertEncoder(config)
691
+
692
+ self.adapter = Wav2Vec2BertAdapter(config) if config.add_adapter else None
693
+
694
+ self.intermediate_ffn = None
695
+ if config.use_intermediate_ffn_before_adapter:
696
+ self.intermediate_ffn = Wav2Vec2BertFeedForward(config, act_fn="relu")
697
+
698
+ # Initialize weights and apply final processing
699
+ self.post_init()
700
+
701
+ def freeze_feature_encoder(self):
702
+ raise AttributeError("Not needed for Wav2Vec2Bert")
703
+
704
+ def forward(
705
+ self,
706
+ input_features: torch.Tensor | None,
707
+ attention_mask: torch.Tensor | None = None,
708
+ mask_time_indices: torch.FloatTensor | None = None,
709
+ output_attentions: bool | None = None,
710
+ output_hidden_states: bool | None = None,
711
+ return_dict: bool | None = None,
712
+ **kwargs,
713
+ ) -> tuple | Wav2Vec2BertBaseModelOutput:
714
+ r"""
715
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
716
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
717
+ masked extracted features in *config.proj_codevector_dim* space.
718
+ """
719
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
720
+ output_hidden_states = (
721
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
722
+ )
723
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
724
+
725
+ hidden_states, extract_features = self.feature_projection(input_features)
726
+ hidden_states = self._mask_hidden_states(
727
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
728
+ )
729
+
730
+ encoder_outputs = self.encoder(
731
+ hidden_states,
732
+ attention_mask=attention_mask,
733
+ output_attentions=output_attentions,
734
+ output_hidden_states=output_hidden_states,
735
+ return_dict=return_dict,
736
+ )
737
+
738
+ hidden_states = encoder_outputs[0]
739
+
740
+ if self.intermediate_ffn:
741
+ expanded_hidden_states = self.intermediate_ffn(hidden_states)
742
+ hidden_states = hidden_states + 0.5 * expanded_hidden_states
743
+
744
+ if self.adapter is not None:
745
+ hidden_states = self.adapter(hidden_states, attention_mask=attention_mask)
746
+
747
+ if not return_dict:
748
+ return (hidden_states, extract_features) + encoder_outputs[1:]
749
+
750
+ return Wav2Vec2BertBaseModelOutput(
751
+ last_hidden_state=hidden_states,
752
+ extract_features=extract_features,
753
+ hidden_states=encoder_outputs.hidden_states,
754
+ attentions=encoder_outputs.attentions,
755
+ )
756
+
757
+
758
+ class Wav2Vec2BertForCTC(Wav2Vec2ConformerForCTC):
759
+ def __init__(self, config, target_lang: str | None = None):
760
+ r"""
761
+ target_lang (`str`, *optional*):
762
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
763
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
764
+ default.
765
+ """
766
+ super().__init__(config)
767
+
768
+ def freeze_feature_encoder(self):
769
+ raise AttributeError("Not needed for Wav2Vec2Bert")
770
+
771
+ def forward(
772
+ self,
773
+ input_features: torch.Tensor | None,
774
+ attention_mask: torch.Tensor | None = None,
775
+ output_attentions: bool | None = None,
776
+ output_hidden_states: bool | None = None,
777
+ return_dict: bool | None = None,
778
+ labels: torch.Tensor | None = None,
779
+ **kwargs,
780
+ ) -> tuple | CausalLMOutput:
781
+ r"""
782
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
783
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
784
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
785
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
786
+ config.vocab_size - 1]`.
787
+ """
788
+ if labels is not None and labels.max() >= self.config.vocab_size:
789
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
790
+
791
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
792
+
793
+ outputs = self.wav2vec2_bert(
794
+ input_features,
795
+ attention_mask=attention_mask,
796
+ output_attentions=output_attentions,
797
+ output_hidden_states=output_hidden_states,
798
+ return_dict=return_dict,
799
+ )
800
+
801
+ hidden_states = outputs[0]
802
+ hidden_states = self.dropout(hidden_states)
803
+
804
+ logits = self.lm_head(hidden_states)
805
+
806
+ loss = None
807
+ if labels is not None:
808
+ # retrieve loss input_lengths from attention_mask
809
+ attention_mask = (
810
+ attention_mask
811
+ if attention_mask is not None
812
+ else torch.ones(input_features.shape[:2], device=input_features.device, dtype=torch.long)
813
+ )
814
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum([-1])).to(torch.long)
815
+
816
+ # assuming that padded tokens are filled with -100
817
+ # when not being attended to
818
+ labels_mask = labels >= 0
819
+ target_lengths = labels_mask.sum(-1)
820
+ flattened_targets = labels.masked_select(labels_mask)
821
+
822
+ # ctc_loss doesn't support fp16
823
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
824
+
825
+ with torch.backends.cudnn.flags(enabled=False):
826
+ loss = nn.functional.ctc_loss(
827
+ log_probs,
828
+ flattened_targets,
829
+ input_lengths,
830
+ target_lengths,
831
+ blank=self.config.pad_token_id,
832
+ reduction=self.config.ctc_loss_reduction,
833
+ zero_infinity=self.config.ctc_zero_infinity,
834
+ )
835
+
836
+ if not return_dict:
837
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
838
+ return ((loss,) + output) if loss is not None else output
839
+
840
+ return CausalLMOutput(
841
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
842
+ )
843
+
844
+
845
+ class Wav2Vec2BertForSequenceClassification(Wav2Vec2ForSequenceClassification):
846
+ def __init__(self, config):
847
+ super().__init__(config)
848
+
849
+ def freeze_feature_encoder(self):
850
+ raise AttributeError("Not needed for Wav2Vec2Bert")
851
+
852
+ def freeze_base_model(self):
853
+ """
854
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
855
+ be updated during training. Only the classification head will be updated.
856
+ """
857
+ for param in self.wav2vec2_bert.parameters():
858
+ param.requires_grad = False
859
+
860
+ def forward(
861
+ self,
862
+ input_features: torch.Tensor | None,
863
+ attention_mask: torch.Tensor | None = None,
864
+ output_attentions: bool | None = None,
865
+ output_hidden_states: bool | None = None,
866
+ return_dict: bool | None = None,
867
+ labels: torch.Tensor | None = None,
868
+ **kwargs,
869
+ ) -> tuple | SequenceClassifierOutput:
870
+ r"""
871
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
872
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
873
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
874
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
875
+ """
876
+
877
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
878
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
879
+
880
+ outputs = self.wav2vec2_bert(
881
+ input_features,
882
+ attention_mask=attention_mask,
883
+ output_attentions=output_attentions,
884
+ output_hidden_states=output_hidden_states,
885
+ return_dict=return_dict,
886
+ )
887
+
888
+ if self.config.use_weighted_layer_sum:
889
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
890
+ hidden_states = torch.stack(hidden_states, dim=1)
891
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
892
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
893
+ else:
894
+ hidden_states = outputs[0]
895
+
896
+ hidden_states = self.projector(hidden_states)
897
+ if attention_mask is None:
898
+ pooled_output = hidden_states.mean(dim=1)
899
+ else:
900
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
901
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
902
+ hidden_states[~expand_padding_mask] = 0.0
903
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
904
+
905
+ logits = self.classifier(pooled_output)
906
+
907
+ loss = None
908
+ if labels is not None:
909
+ loss_fct = CrossEntropyLoss()
910
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
911
+
912
+ if not return_dict:
913
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
914
+ return ((loss,) + output) if loss is not None else output
915
+
916
+ return SequenceClassifierOutput(
917
+ loss=loss,
918
+ logits=logits,
919
+ hidden_states=outputs.hidden_states,
920
+ attentions=outputs.attentions,
921
+ )
922
+
923
+
924
+ class Wav2Vec2BertForAudioFrameClassification(Wav2Vec2ConformerForAudioFrameClassification):
925
+ def __init__(self, config):
926
+ super().__init__(config)
927
+
928
+ def freeze_feature_encoder(self):
929
+ raise AttributeError("Not needed for Wav2Vec2Bert")
930
+
931
+ def forward(
932
+ self,
933
+ input_features: torch.Tensor | None,
934
+ attention_mask: torch.Tensor | None = None,
935
+ labels: torch.Tensor | None = None,
936
+ output_attentions: bool | None = None,
937
+ output_hidden_states: bool | None = None,
938
+ return_dict: bool | None = None,
939
+ **kwargs,
940
+ ) -> tuple | TokenClassifierOutput:
941
+ r"""
942
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
943
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
944
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
945
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
946
+ """
947
+
948
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
949
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
950
+
951
+ outputs = self.wav2vec2_bert(
952
+ input_features,
953
+ attention_mask=attention_mask,
954
+ output_attentions=output_attentions,
955
+ output_hidden_states=output_hidden_states,
956
+ return_dict=return_dict,
957
+ )
958
+
959
+ if self.config.use_weighted_layer_sum:
960
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
961
+ hidden_states = torch.stack(hidden_states, dim=1)
962
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
963
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
964
+ else:
965
+ hidden_states = outputs[0]
966
+
967
+ logits = self.classifier(hidden_states)
968
+
969
+ loss = None
970
+ if labels is not None:
971
+ loss_fct = CrossEntropyLoss()
972
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
973
+
974
+ if not return_dict:
975
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
976
+ return output
977
+
978
+ return TokenClassifierOutput(
979
+ loss=loss,
980
+ logits=logits,
981
+ hidden_states=outputs.hidden_states,
982
+ attentions=outputs.attentions,
983
+ )
984
+
985
+
986
+ class Wav2Vec2BertForXVector(Wav2Vec2ConformerForXVector):
987
+ def __init__(self, config):
988
+ super().__init__(config)
989
+
990
+ def freeze_feature_encoder(self):
991
+ raise AttributeError("Not needed for Wav2Vec2Bert")
992
+
993
+ def forward(
994
+ self,
995
+ input_features: torch.Tensor | None,
996
+ attention_mask: torch.Tensor | None = None,
997
+ output_attentions: bool | None = None,
998
+ output_hidden_states: bool | None = None,
999
+ return_dict: bool | None = None,
1000
+ labels: torch.Tensor | None = None,
1001
+ **kwargs,
1002
+ ) -> tuple | XVectorOutput:
1003
+ r"""
1004
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1005
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1006
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1007
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1008
+ """
1009
+
1010
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1011
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1012
+
1013
+ outputs = self.wav2vec2_bert(
1014
+ input_features,
1015
+ attention_mask=attention_mask,
1016
+ output_attentions=output_attentions,
1017
+ output_hidden_states=output_hidden_states,
1018
+ return_dict=return_dict,
1019
+ )
1020
+
1021
+ if self.config.use_weighted_layer_sum:
1022
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1023
+ hidden_states = torch.stack(hidden_states, dim=1)
1024
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1025
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1026
+ else:
1027
+ hidden_states = outputs[0]
1028
+
1029
+ hidden_states = self.projector(hidden_states)
1030
+
1031
+ for tdnn_layer in self.tdnn:
1032
+ hidden_states = tdnn_layer(hidden_states)
1033
+
1034
+ # Statistic Pooling
1035
+ if attention_mask is None:
1036
+ mean_features = hidden_states.mean(dim=1)
1037
+ std_features = hidden_states.std(dim=1)
1038
+ else:
1039
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
1040
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
1041
+ mean_features = []
1042
+ std_features = []
1043
+ for i, length in enumerate(tdnn_output_lengths):
1044
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
1045
+ std_features.append(hidden_states[i, :length].std(dim=0))
1046
+ mean_features = torch.stack(mean_features)
1047
+ std_features = torch.stack(std_features)
1048
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
1049
+
1050
+ output_embeddings = self.feature_extractor(statistic_pooling)
1051
+ logits = self.classifier(output_embeddings)
1052
+
1053
+ loss = None
1054
+ if labels is not None:
1055
+ loss = self.objective(logits, labels)
1056
+
1057
+ if not return_dict:
1058
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
1059
+ return ((loss,) + output) if loss is not None else output
1060
+
1061
+ return XVectorOutput(
1062
+ loss=loss,
1063
+ logits=logits,
1064
+ embeddings=output_embeddings,
1065
+ hidden_states=outputs.hidden_states,
1066
+ attentions=outputs.attentions,
1067
+ )
1068
+
1069
+
1070
+ __all__ = [
1071
+ "Wav2Vec2BertForAudioFrameClassification",
1072
+ "Wav2Vec2BertForCTC",
1073
+ "Wav2Vec2BertForSequenceClassification",
1074
+ "Wav2Vec2BertForXVector",
1075
+ "Wav2Vec2BertModel",
1076
+ "Wav2Vec2BertPreTrainedModel",
1077
+ ]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Speech processor class for Wav2Vec2-BERT
16
+ """
17
+
18
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
19
+ from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ class Wav2Vec2BertProcessorKwargs(ProcessingKwargs, total=False):
24
+ _defaults = {}
25
+
26
+
27
+ @auto_docstring
28
+ class Wav2Vec2BertProcessor(ProcessorMixin):
29
+ def __init__(self, feature_extractor, tokenizer):
30
+ super().__init__(feature_extractor, tokenizer)
31
+
32
+ @auto_docstring
33
+ def __call__(
34
+ self,
35
+ audio: AudioInput | None = None,
36
+ text: str | list[str] | TextInput | PreTokenizedInput | None = None,
37
+ **kwargs: Unpack[Wav2Vec2BertProcessorKwargs],
38
+ ):
39
+ r"""
40
+ Returns:
41
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
42
+ - **input_features** -- Audio input features to be fed to a model. Returned when `audio` is not `None`.
43
+ - **attention_mask** -- List of indices specifying which timestamps should be attended to by the model when `audio` is not `None`.
44
+ When only `text` is specified, returns the token attention mask.
45
+ - **labels** -- List of token ids to be fed to a model. Returned when both `text` and `audio` are not `None`.
46
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None` and `audio` is `None`.
47
+ """
48
+
49
+ if audio is None and text is None:
50
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
51
+ output_kwargs = self._merge_kwargs(
52
+ Wav2Vec2BertProcessorKwargs,
53
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
54
+ **kwargs,
55
+ )
56
+
57
+ if audio is not None:
58
+ inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
59
+ if text is not None:
60
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
61
+
62
+ if text is None:
63
+ return inputs
64
+ elif audio is None:
65
+ return encodings
66
+ else:
67
+ inputs["labels"] = encodings["input_ids"]
68
+ return inputs
69
+
70
+ def pad(self, input_features=None, labels=None, **kwargs):
71
+ """
72
+ If `input_features` is not `None`, this method forwards the `input_features` and `kwargs` arguments to SeamlessM4TFeatureExtractor's [`~SeamlessM4TFeatureExtractor.pad`] to pad the input features.
73
+ If `labels` is not `None`, this method forwards the `labels` and `kwargs` arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.pad`] to pad the label(s).
74
+ Please refer to the docstring of the above two methods for more information.
75
+ """
76
+ if input_features is None and labels is None:
77
+ raise ValueError("You need to specify either an `input_features` or `labels` input to pad.")
78
+
79
+ if input_features is not None:
80
+ input_features = self.feature_extractor.pad(input_features, **kwargs)
81
+ if labels is not None:
82
+ labels = self.tokenizer.pad(labels, **kwargs)
83
+
84
+ if labels is None:
85
+ return input_features
86
+ elif input_features is None:
87
+ return labels
88
+ else:
89
+ input_features["labels"] = labels["input_ids"]
90
+ return input_features
91
+
92
+ @property
93
+ def model_input_names(self):
94
+ # The processor doesn't return text ids and the model seems to not need them
95
+ feature_extractor_input_names = self.feature_extractor.model_input_names
96
+ return feature_extractor_input_names + ["labels"]
97
+
98
+
99
+ __all__ = ["Wav2Vec2BertProcessor"]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_wav2vec2_conformer import *
22
+ from .modeling_wav2vec2_conformer import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (702 Bytes). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/configuration_wav2vec2_conformer.cpython-312.pyc ADDED
Binary file (16.5 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modeling_wav2vec2_conformer.cpython-312.pyc ADDED
Binary file (98.1 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/__pycache__/modular_wav2vec2_conformer.cpython-312.pyc ADDED
Binary file (39.6 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Wav2Vec2Conformer model configuration"""
15
+
16
+ import functools
17
+ import operator
18
+
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...utils import auto_docstring
23
+
24
+
25
+ @auto_docstring(checkpoint="facebook/wav2vec2-conformer-rel-pos-large")
26
+ @strict
27
+ class Wav2Vec2ConformerConfig(PreTrainedConfig):
28
+ r"""
29
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
30
+ The dropout probability for output of the feature encoder.
31
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
32
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
33
+ final_dropout (`float`, *optional*, defaults to 0.1):
34
+ The dropout probability for the final projection layer of [`Wav2Vec2ConformerForCTC`].
35
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
36
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
37
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
38
+ convolutional layers.
39
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
40
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
41
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
42
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
43
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
44
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
45
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
46
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
47
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
48
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
49
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
50
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
51
+ *conv_dim*.
52
+ conv_bias (`bool`, *optional*, defaults to `False`):
53
+ Whether the 1D convolutional layers have a bias.
54
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
55
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
56
+ embeddings layer.
57
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
58
+ Number of groups of 1D convolutional positional embeddings layer.
59
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
60
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
61
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
62
+ Recognition](https://huggingface.co/papers/1904.08779).
63
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
64
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
65
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
66
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
67
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
68
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
69
+ mask_time_length (`int`, *optional*, defaults to 10):
70
+ Length of vector span along the time axis.
71
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
72
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
73
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
74
+ mask_time_min_masks''
75
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
76
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
77
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
78
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
79
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
80
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
81
+ True`.
82
+ mask_feature_length (`int`, *optional*, defaults to 10):
83
+ Length of vector span along the feature axis.
84
+ mask_feature_min_masks (`int`, *optional*, defaults to 0),:
85
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
86
+ step, irrespectively of `mask_feature_prob`. Only relevant if
87
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
88
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
89
+ Number of entries in each quantization codebook (group).
90
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
91
+ Number of entries in each quantization codebook (group).
92
+ num_codevector_groups (`int`, *optional*, defaults to 2):
93
+ Number of codevector groups for product codevector quantization.
94
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
95
+ The temperature *kappa* in the contrastive loss.
96
+ num_negatives (`int`, *optional*, defaults to 100):
97
+ Number of negative samples for the contrastive loss.
98
+ codevector_dim (`int`, *optional*, defaults to 256):
99
+ Dimensionality of the quantized feature vectors.
100
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
101
+ Dimensionality of the final projection of both the quantized and the transformer features.
102
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
103
+ The weight of the codebook diversity loss component.
104
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
105
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
106
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
107
+ of [`Wav2Vec2ConformerForCTC`].
108
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
109
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
110
+ instance of [`Wav2Vec2ConformerForSequenceClassification`].
111
+ classifier_proj_size (`int`, *optional*, defaults to 256):
112
+ Dimensionality of the projection before token mean-pooling for classification.
113
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
114
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
115
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
116
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
117
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
118
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
119
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
120
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
121
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
122
+ xvector_output_dim (`int`, *optional*, defaults to 512):
123
+ Dimensionality of the *XVector* embedding vectors.
124
+ add_adapter (`bool`, *optional*, defaults to `False`):
125
+ Whether a convolutional network should be stacked on top of the Wav2Vec2Conformer Encoder. Can be very
126
+ useful for warm-starting Wav2Vec2Conformer for SpeechEncoderDecoder models.
127
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
128
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
129
+ adapter_stride (`int`, *optional*, defaults to 2):
130
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
131
+ num_adapter_layers (`int`, *optional*, defaults to 3):
132
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
133
+ True`.
134
+ output_hidden_size (`int`, *optional*):
135
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
136
+ if `add_adapter is True`.
137
+ position_embeddings_type (`str`, *optional*, defaults to `"relative"`):
138
+ Can be specified to `relative` or `rotary` for relative or rotary position embeddings respectively. If left
139
+ `None` no relative position embedding is applied.
140
+ rotary_embedding_base (`int`, *optional*, defaults to 10000):
141
+ If `"rotary"` position embeddings are used, defines the size of the embedding base.
142
+ max_source_positions (`int`, *optional*, defaults to 5000):
143
+ if `"relative"` position embeddings are used, defines the maximum source input positions.
144
+ conv_depthwise_kernel_size (`int`, *optional*, defaults to 31):
145
+ Kernel size of convolutional depthwise 1D layer in Conformer blocks.
146
+ conformer_conv_dropout (`float`, *optional*, defaults to 0.1):
147
+ The dropout probability for all convolutional layers in Conformer blocks.
148
+
149
+ Example:
150
+
151
+ ```python
152
+ >>> from transformers import Wav2Vec2ConformerConfig, Wav2Vec2ConformerModel
153
+
154
+ >>> # Initializing a Wav2Vec2Conformer facebook/wav2vec2-conformer-rel-pos-large style configuration
155
+ >>> configuration = Wav2Vec2ConformerConfig()
156
+
157
+ >>> # Initializing a model (with random weights) from the facebook/wav2vec2-conformer-rel-pos-large style configuration
158
+ >>> model = Wav2Vec2ConformerModel(configuration)
159
+
160
+ >>> # Accessing the model configuration
161
+ >>> configuration = model.config
162
+ ```"""
163
+
164
+ model_type = "wav2vec2-conformer"
165
+
166
+ vocab_size: int | None = None
167
+ hidden_size: int = 768
168
+ num_hidden_layers: int = 12
169
+ num_attention_heads: int = 12
170
+ intermediate_size: int = 3072
171
+ hidden_act: str = "gelu"
172
+ hidden_dropout: float | int = 0.1
173
+ activation_dropout: float | int = 0.1
174
+ attention_dropout: float | int = 0.1
175
+ feat_proj_dropout: float | int = 0.0
176
+ feat_quantizer_dropout: float | int = 0.0
177
+ final_dropout: float | int = 0.1
178
+ layerdrop: float | int = 0.1
179
+ initializer_range: float = 0.02
180
+ layer_norm_eps: float = 1e-5
181
+ feat_extract_norm: str = "group"
182
+ feat_extract_activation: str = "gelu"
183
+ conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
184
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
185
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
186
+ conv_bias: bool = False
187
+ num_conv_pos_embeddings: int = 128
188
+ num_conv_pos_embedding_groups: int = 16
189
+ apply_spec_augment: bool = True
190
+ mask_time_prob: float | int = 0.05
191
+ mask_time_length: int = 10
192
+ mask_time_min_masks: int = 2
193
+ mask_feature_prob: float | int = 0.0
194
+ mask_feature_length: int = 10
195
+ mask_feature_min_masks: int = 0
196
+ num_codevectors_per_group: int = 320
197
+ num_codevector_groups: int = 2
198
+ contrastive_logits_temperature: float = 0.1
199
+ num_negatives: int = 100
200
+ codevector_dim: int = 256
201
+ proj_codevector_dim: int = 256
202
+ diversity_loss_weight: float = 0.1
203
+ ctc_loss_reduction: str = "sum"
204
+ ctc_zero_infinity: bool = False
205
+ use_weighted_layer_sum: bool = False
206
+ classifier_proj_size: int = 256
207
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
208
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
209
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
210
+ xvector_output_dim: int = 512
211
+ pad_token_id: int | None = 0
212
+ bos_token_id: int | None = 1
213
+ eos_token_id: int | list[int] | None = 2
214
+ add_adapter: bool = False
215
+ adapter_kernel_size: int = 3
216
+ adapter_stride: int = 2
217
+ num_adapter_layers: int = 3
218
+ output_hidden_size: int | None = None
219
+ position_embeddings_type: str | None = "relative"
220
+ rotary_embedding_base: int = 10000
221
+ max_source_positions: int = 5000
222
+ conv_depthwise_kernel_size: int = 31
223
+ conformer_conv_dropout: float | int = 0.1
224
+
225
+ def __post_init__(self, **kwargs):
226
+ self.num_feat_extract_layers = len(self.conv_dim)
227
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
228
+ super().__post_init__(**kwargs)
229
+
230
+ def validate_architecture(self):
231
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
232
+ if (
233
+ (len(self.conv_stride) != self.num_feat_extract_layers)
234
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
235
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
236
+ ):
237
+ raise ValueError(
238
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
239
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
240
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
241
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
242
+ )
243
+
244
+ @property
245
+ def inputs_to_logits_ratio(self):
246
+ return functools.reduce(operator.mul, self.conv_stride, 1)
247
+
248
+
249
+ __all__ = ["Wav2Vec2ConformerConfig"]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py ADDED
@@ -0,0 +1,1942 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_wav2vec2_conformer.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ import math
8
+ import warnings
9
+ from dataclasses import dataclass
10
+
11
+ import numpy as np
12
+ import torch
13
+ from torch import nn
14
+ from torch.nn import CrossEntropyLoss
15
+
16
+ from ... import initialization as init
17
+ from ...activations import ACT2FN
18
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
19
+ from ...integrations.fsdp import is_fsdp_managed_module
20
+ from ...modeling_layers import GradientCheckpointingLayer
21
+ from ...modeling_outputs import (
22
+ BaseModelOutput,
23
+ CausalLMOutput,
24
+ SequenceClassifierOutput,
25
+ TokenClassifierOutput,
26
+ Wav2Vec2BaseModelOutput,
27
+ XVectorOutput,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import ModelOutput, auto_docstring, is_peft_available
31
+ from .configuration_wav2vec2_conformer import Wav2Vec2ConformerConfig
32
+
33
+
34
+ @auto_docstring(
35
+ custom_intro="""
36
+ Output type of [`Wav2Vec2ConformerForPreTraining`], with potential hidden states and attentions.
37
+ """
38
+ )
39
+ @dataclass
40
+ class Wav2Vec2ConformerForPreTrainingOutput(ModelOutput):
41
+ r"""
42
+ loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
43
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
44
+ paper](https://huggingface.co/papers/2006.11477).
45
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
46
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
47
+ projected quantized states.
48
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
49
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
50
+ target vectors for contrastive loss.
51
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
52
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
53
+ contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
54
+ The contrastive loss (L_m) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
55
+ diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
56
+ The diversity loss (L_d) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
57
+ """
58
+
59
+ loss: torch.FloatTensor | None = None
60
+ projected_states: torch.FloatTensor | None = None
61
+ projected_quantized_states: torch.FloatTensor | None = None
62
+ codevector_perplexity: torch.FloatTensor | None = None
63
+ hidden_states: tuple[torch.FloatTensor] | None = None
64
+ attentions: tuple[torch.FloatTensor] | None = None
65
+ contrastive_loss: torch.FloatTensor | None = None
66
+ diversity_loss: torch.FloatTensor | None = None
67
+
68
+
69
+ class Wav2Vec2ConformerSamePadLayer(nn.Module):
70
+ def __init__(self, num_conv_pos_embeddings):
71
+ super().__init__()
72
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
73
+
74
+ def forward(self, hidden_states):
75
+ if self.num_pad_remove > 0:
76
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
77
+ return hidden_states
78
+
79
+
80
+ class Wav2Vec2ConformerPositionalConvEmbedding(nn.Module):
81
+ def __init__(self, config):
82
+ super().__init__()
83
+ self.conv = nn.Conv1d(
84
+ config.hidden_size,
85
+ config.hidden_size,
86
+ kernel_size=config.num_conv_pos_embeddings,
87
+ padding=config.num_conv_pos_embeddings // 2,
88
+ groups=config.num_conv_pos_embedding_groups,
89
+ )
90
+
91
+ weight_norm = nn.utils.weight_norm
92
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
93
+ weight_norm = nn.utils.parametrizations.weight_norm
94
+
95
+ if is_deepspeed_zero3_enabled():
96
+ import deepspeed
97
+
98
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
99
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
100
+ if hasattr(self.conv, "parametrizations"):
101
+ weight_g = self.conv.parametrizations.weight.original0
102
+ weight_v = self.conv.parametrizations.weight.original1
103
+ else:
104
+ weight_g = self.conv.weight_g
105
+ weight_v = self.conv.weight_v
106
+ deepspeed.zero.register_external_parameter(self, weight_v)
107
+ deepspeed.zero.register_external_parameter(self, weight_g)
108
+ else:
109
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
110
+
111
+ self.padding = Wav2Vec2ConformerSamePadLayer(config.num_conv_pos_embeddings)
112
+ self.activation = ACT2FN[config.feat_extract_activation]
113
+
114
+ def forward(self, hidden_states):
115
+ hidden_states = hidden_states.transpose(1, 2)
116
+
117
+ hidden_states = self.conv(hidden_states)
118
+ hidden_states = self.padding(hidden_states)
119
+ hidden_states = self.activation(hidden_states)
120
+
121
+ hidden_states = hidden_states.transpose(1, 2)
122
+ return hidden_states
123
+
124
+
125
+ class Wav2Vec2ConformerRotaryPositionalEmbedding(nn.Module):
126
+ """Rotary positional embedding
127
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://huggingface.co/papers/2104.09864
128
+ """
129
+
130
+ def __init__(self, config):
131
+ super().__init__()
132
+ dim = config.hidden_size // config.num_attention_heads
133
+ base = config.rotary_embedding_base
134
+
135
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
136
+ self.register_buffer("inv_freq", inv_freq)
137
+ self.cached_sequence_length = None
138
+ self.cached_rotary_positional_embedding = None
139
+
140
+ def forward(self, hidden_states):
141
+ sequence_length = hidden_states.shape[1]
142
+
143
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
144
+ return self.cached_rotary_positional_embedding
145
+
146
+ self.cached_sequence_length = sequence_length
147
+ # Embeddings are computed in the dtype of the inv_freq constant
148
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
149
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
150
+ embeddings = torch.cat((freqs, freqs), dim=-1)
151
+
152
+ cos_embeddings = embeddings.cos()[:, None, None, :]
153
+ sin_embeddings = embeddings.sin()[:, None, None, :]
154
+ # Computed embeddings are cast to the dtype of the hidden state inputs
155
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
156
+ return self.cached_rotary_positional_embedding
157
+
158
+
159
+ class Wav2Vec2ConformerRelPositionalEmbedding(nn.Module):
160
+ """Relative positional encoding module."""
161
+
162
+ def __init__(self, config):
163
+ super().__init__()
164
+ self.max_len = config.max_source_positions
165
+ self.d_model = config.hidden_size
166
+ self.register_buffer("pe", self.extend_pe(torch.tensor(0.0).expand(1, self.max_len)), persistent=False)
167
+
168
+ def extend_pe(self, x, pe=None):
169
+ # Reset the positional encodings
170
+ if pe is not None:
171
+ # self.pe contains both positive and negative parts
172
+ # the length of self.pe is 2 * input_len - 1
173
+ if pe.size(1) >= x.size(1) * 2 - 1:
174
+ if pe.dtype != x.dtype or pe.device != x.device:
175
+ pe = pe.to(dtype=x.dtype, device=x.device)
176
+ return pe
177
+ # Suppose `i` is the position of query vector and `j` is the
178
+ # position of key vector. We use positive relative positions when keys
179
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
180
+ pe_positive = torch.zeros(x.size(1), self.d_model)
181
+ pe_negative = torch.zeros(x.size(1), self.d_model)
182
+ position = torch.arange(0, x.size(1), dtype=torch.int64).float().unsqueeze(1)
183
+ div_term = torch.exp(
184
+ torch.arange(0, self.d_model, 2, dtype=torch.int64).float() * -(math.log(10000.0) / self.d_model)
185
+ )
186
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
187
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
188
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
189
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
190
+
191
+ # Reverse the order of positive indices and concat both positive and
192
+ # negative indices. This is used to support the shifting trick
193
+ # as in https://huggingface.co/papers/1901.02860
194
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
195
+ pe_negative = pe_negative[1:].unsqueeze(0)
196
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
197
+ return pe.to(device=x.device, dtype=x.dtype)
198
+
199
+ def forward(self, hidden_states: torch.Tensor):
200
+ self.pe = self.extend_pe(hidden_states, self.pe)
201
+ start_idx = self.pe.size(1) // 2 - hidden_states.size(1) + 1
202
+ end_idx = self.pe.size(1) // 2 + hidden_states.size(1)
203
+ relative_position_embeddings = self.pe[:, start_idx:end_idx]
204
+
205
+ return relative_position_embeddings
206
+
207
+
208
+ class Wav2Vec2ConformerNoLayerNormConvLayer(GradientCheckpointingLayer):
209
+ def __init__(self, config, layer_id=0):
210
+ super().__init__()
211
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
212
+ self.out_conv_dim = config.conv_dim[layer_id]
213
+
214
+ self.conv = nn.Conv1d(
215
+ self.in_conv_dim,
216
+ self.out_conv_dim,
217
+ kernel_size=config.conv_kernel[layer_id],
218
+ stride=config.conv_stride[layer_id],
219
+ bias=config.conv_bias,
220
+ )
221
+ self.activation = ACT2FN[config.feat_extract_activation]
222
+
223
+ def forward(self, hidden_states):
224
+ hidden_states = self.conv(hidden_states)
225
+ hidden_states = self.activation(hidden_states)
226
+ return hidden_states
227
+
228
+
229
+ class Wav2Vec2ConformerLayerNormConvLayer(GradientCheckpointingLayer):
230
+ def __init__(self, config, layer_id=0):
231
+ super().__init__()
232
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
233
+ self.out_conv_dim = config.conv_dim[layer_id]
234
+
235
+ self.conv = nn.Conv1d(
236
+ self.in_conv_dim,
237
+ self.out_conv_dim,
238
+ kernel_size=config.conv_kernel[layer_id],
239
+ stride=config.conv_stride[layer_id],
240
+ bias=config.conv_bias,
241
+ )
242
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
243
+ self.activation = ACT2FN[config.feat_extract_activation]
244
+
245
+ def forward(self, hidden_states):
246
+ hidden_states = self.conv(hidden_states)
247
+
248
+ hidden_states = hidden_states.transpose(-2, -1)
249
+ hidden_states = self.layer_norm(hidden_states)
250
+ hidden_states = hidden_states.transpose(-2, -1)
251
+
252
+ hidden_states = self.activation(hidden_states)
253
+ return hidden_states
254
+
255
+
256
+ class Wav2Vec2ConformerGroupNormConvLayer(GradientCheckpointingLayer):
257
+ def __init__(self, config, layer_id=0):
258
+ super().__init__()
259
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
260
+ self.out_conv_dim = config.conv_dim[layer_id]
261
+
262
+ self.conv = nn.Conv1d(
263
+ self.in_conv_dim,
264
+ self.out_conv_dim,
265
+ kernel_size=config.conv_kernel[layer_id],
266
+ stride=config.conv_stride[layer_id],
267
+ bias=config.conv_bias,
268
+ )
269
+ self.activation = ACT2FN[config.feat_extract_activation]
270
+
271
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
272
+
273
+ def forward(self, hidden_states):
274
+ hidden_states = self.conv(hidden_states)
275
+ hidden_states = self.layer_norm(hidden_states)
276
+ hidden_states = self.activation(hidden_states)
277
+ return hidden_states
278
+
279
+
280
+ class Wav2Vec2ConformerFeatureEncoder(nn.Module):
281
+ """Construct the features from raw audio waveform"""
282
+
283
+ def __init__(self, config):
284
+ super().__init__()
285
+
286
+ if config.feat_extract_norm == "group":
287
+ conv_layers = [Wav2Vec2ConformerGroupNormConvLayer(config, layer_id=0)] + [
288
+ Wav2Vec2ConformerNoLayerNormConvLayer(config, layer_id=i + 1)
289
+ for i in range(config.num_feat_extract_layers - 1)
290
+ ]
291
+ elif config.feat_extract_norm == "layer":
292
+ conv_layers = [
293
+ Wav2Vec2ConformerLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
294
+ ]
295
+ else:
296
+ raise ValueError(
297
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
298
+ )
299
+ self.conv_layers = nn.ModuleList(conv_layers)
300
+ self.gradient_checkpointing = False
301
+ self._requires_grad = True
302
+
303
+ def _freeze_parameters(self):
304
+ for param in self.parameters():
305
+ param.requires_grad = False
306
+ self._requires_grad = False
307
+
308
+ def forward(self, input_values):
309
+ hidden_states = input_values[:, None]
310
+
311
+ # make sure hidden_states require grad for gradient_checkpointing
312
+ if self._requires_grad and self.training:
313
+ hidden_states.requires_grad = True
314
+
315
+ for conv_layer in self.conv_layers:
316
+ hidden_states = conv_layer(hidden_states)
317
+
318
+ return hidden_states
319
+
320
+
321
+ class Wav2Vec2ConformerFeatureProjection(nn.Module):
322
+ def __init__(self, config):
323
+ super().__init__()
324
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
325
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
326
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
327
+
328
+ def forward(self, hidden_states):
329
+ # non-projected hidden states are needed for quantization
330
+ norm_hidden_states = self.layer_norm(hidden_states)
331
+ hidden_states = self.projection(norm_hidden_states)
332
+ hidden_states = self.dropout(hidden_states)
333
+ return hidden_states, norm_hidden_states
334
+
335
+
336
+ class Wav2Vec2ConformerFeedForward(nn.Module):
337
+ def __init__(self, config):
338
+ super().__init__()
339
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
340
+
341
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
342
+ if isinstance(config.hidden_act, str):
343
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
344
+ else:
345
+ self.intermediate_act_fn = config.hidden_act
346
+
347
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
348
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
349
+
350
+ def forward(self, hidden_states):
351
+ hidden_states = self.intermediate_dense(hidden_states)
352
+ hidden_states = self.intermediate_act_fn(hidden_states)
353
+ hidden_states = self.intermediate_dropout(hidden_states)
354
+
355
+ hidden_states = self.output_dense(hidden_states)
356
+ hidden_states = self.output_dropout(hidden_states)
357
+ return hidden_states
358
+
359
+
360
+ class Wav2Vec2ConformerConvolutionModule(nn.Module):
361
+ """Convolution block used in the conformer block"""
362
+
363
+ def __init__(self, config):
364
+ super().__init__()
365
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
366
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
367
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
368
+ self.pointwise_conv1 = nn.Conv1d(
369
+ config.hidden_size,
370
+ 2 * config.hidden_size,
371
+ kernel_size=1,
372
+ stride=1,
373
+ padding=0,
374
+ bias=False,
375
+ )
376
+ self.glu = nn.GLU(dim=1)
377
+ self.depthwise_conv = nn.Conv1d(
378
+ config.hidden_size,
379
+ config.hidden_size,
380
+ config.conv_depthwise_kernel_size,
381
+ stride=1,
382
+ padding=(config.conv_depthwise_kernel_size - 1) // 2,
383
+ groups=config.hidden_size,
384
+ bias=False,
385
+ )
386
+ self.batch_norm = nn.BatchNorm1d(config.hidden_size)
387
+ self.activation = ACT2FN[config.hidden_act]
388
+ self.pointwise_conv2 = nn.Conv1d(
389
+ config.hidden_size,
390
+ config.hidden_size,
391
+ kernel_size=1,
392
+ stride=1,
393
+ padding=0,
394
+ bias=False,
395
+ )
396
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
397
+
398
+ def forward(self, hidden_states):
399
+ hidden_states = self.layer_norm(hidden_states)
400
+ # exchange the temporal dimension and the feature dimension
401
+ hidden_states = hidden_states.transpose(1, 2)
402
+
403
+ # GLU mechanism
404
+ # => (batch, 2*channel, dim)
405
+ hidden_states = self.pointwise_conv1(hidden_states)
406
+ # => (batch, channel, dim)
407
+ hidden_states = self.glu(hidden_states)
408
+
409
+ # 1D Depthwise Conv
410
+ hidden_states = self.depthwise_conv(hidden_states)
411
+ hidden_states = self.batch_norm(hidden_states)
412
+ hidden_states = self.activation(hidden_states)
413
+
414
+ hidden_states = self.pointwise_conv2(hidden_states)
415
+ hidden_states = self.dropout(hidden_states)
416
+ hidden_states = hidden_states.transpose(1, 2)
417
+ return hidden_states
418
+
419
+
420
+ class Wav2Vec2ConformerSelfAttention(nn.Module):
421
+ """Construct an Wav2Vec2ConformerSelfAttention object.
422
+ Can be enhanced with rotary or relative position embeddings.
423
+ """
424
+
425
+ def __init__(self, config):
426
+ super().__init__()
427
+
428
+ self.head_size = config.hidden_size // config.num_attention_heads
429
+ self.num_heads = config.num_attention_heads
430
+ self.position_embeddings_type = config.position_embeddings_type
431
+
432
+ self.linear_q = nn.Linear(config.hidden_size, config.hidden_size)
433
+ self.linear_k = nn.Linear(config.hidden_size, config.hidden_size)
434
+ self.linear_v = nn.Linear(config.hidden_size, config.hidden_size)
435
+ self.linear_out = nn.Linear(config.hidden_size, config.hidden_size)
436
+
437
+ self.dropout = nn.Dropout(p=config.attention_dropout)
438
+
439
+ if self.position_embeddings_type == "relative":
440
+ # linear transformation for positional encoding
441
+ self.linear_pos = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
442
+ # these two learnable bias are used in matrix c and matrix d
443
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
444
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
445
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
446
+
447
+ def forward(
448
+ self,
449
+ hidden_states: torch.Tensor,
450
+ attention_mask: torch.Tensor | None = None,
451
+ relative_position_embeddings: torch.Tensor | None = None,
452
+ output_attentions: bool = False,
453
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
454
+ # self-attention mechanism
455
+ batch_size, sequence_length, hidden_size = hidden_states.size()
456
+
457
+ # make sure query/key states can be != value states
458
+ query_key_states = hidden_states
459
+ value_states = hidden_states
460
+
461
+ if self.position_embeddings_type == "rotary":
462
+ if relative_position_embeddings is None:
463
+ raise ValueError(
464
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
465
+ )
466
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
467
+
468
+ # project query_key_states and value_states
469
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
470
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
471
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
472
+
473
+ # => (batch, head, time1, d_k)
474
+ query = query.transpose(1, 2)
475
+ key = key.transpose(1, 2)
476
+ value = value.transpose(1, 2)
477
+
478
+ if self.position_embeddings_type == "relative":
479
+ if relative_position_embeddings is None:
480
+ raise ValueError(
481
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
482
+ " 'relative'"
483
+ )
484
+ # apply relative_position_embeddings to qk scores
485
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
486
+ scores = self._apply_relative_embeddings(
487
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
488
+ )
489
+ else:
490
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
491
+
492
+ # apply attention_mask if necessary
493
+ if attention_mask is not None:
494
+ scores = scores + attention_mask
495
+
496
+ # => (batch, head, time1, time2)
497
+ probs = torch.softmax(scores, dim=-1)
498
+ probs = self.dropout(probs)
499
+
500
+ # => (batch, head, time1, d_k)
501
+ hidden_states = torch.matmul(probs, value)
502
+
503
+ # => (batch, time1, hidden_size)
504
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
505
+ hidden_states = self.linear_out(hidden_states)
506
+
507
+ return hidden_states, probs
508
+
509
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
510
+ batch_size, sequence_length, hidden_size = hidden_states.size()
511
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
512
+
513
+ cos = relative_position_embeddings[0, :sequence_length, ...]
514
+ sin = relative_position_embeddings[1, :sequence_length, ...]
515
+
516
+ # rotate hidden_states with rotary embeddings
517
+ hidden_states = hidden_states.transpose(0, 1)
518
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
519
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
520
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
521
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
522
+ hidden_states = hidden_states.transpose(0, 1)
523
+
524
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
525
+
526
+ return hidden_states
527
+
528
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
529
+ # 1. project positional embeddings
530
+ # => (batch, head, 2*time1-1, d_k)
531
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
532
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
533
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size
534
+ )
535
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)
536
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)
537
+
538
+ # 2. Add bias to query
539
+ # => (batch, head, time1, d_k)
540
+ query = query.transpose(1, 2)
541
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
542
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
543
+
544
+ # 3. attention score: first compute matrix a and matrix c
545
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
546
+ # => (batch, head, time1, time2)
547
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
548
+
549
+ # 4. then compute matrix b and matrix d
550
+ # => (batch, head, time1, 2*time1-1)
551
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
552
+
553
+ # 5. shift matrix b and matrix d
554
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
555
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
556
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
557
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
558
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
559
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
560
+
561
+ # 6. sum matrices
562
+ # => (batch, head, time1, time2)
563
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
564
+
565
+ return scores
566
+
567
+
568
+ class Wav2Vec2ConformerEncoderLayer(GradientCheckpointingLayer):
569
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
570
+
571
+ def __init__(self, config):
572
+ super().__init__()
573
+ embed_dim = config.hidden_size
574
+ dropout = config.attention_dropout
575
+
576
+ # Feed-forward 1
577
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim)
578
+ self.ffn1 = Wav2Vec2ConformerFeedForward(config)
579
+
580
+ # Self-Attention
581
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim)
582
+ self.self_attn_dropout = nn.Dropout(dropout)
583
+ self.self_attn = Wav2Vec2ConformerSelfAttention(config)
584
+
585
+ # Conformer Convolution
586
+ self.conv_module = Wav2Vec2ConformerConvolutionModule(config)
587
+
588
+ # Feed-forward 2
589
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim)
590
+ self.ffn2 = Wav2Vec2ConformerFeedForward(config)
591
+ self.final_layer_norm = nn.LayerNorm(embed_dim)
592
+
593
+ def forward(
594
+ self,
595
+ hidden_states,
596
+ attention_mask: torch.Tensor | None = None,
597
+ relative_position_embeddings: torch.Tensor | None = None,
598
+ output_attentions: bool = False,
599
+ ):
600
+ # 1. Feed-Forward 1 layer
601
+ residual = hidden_states
602
+ hidden_states = self.ffn1_layer_norm(hidden_states)
603
+ hidden_states = self.ffn1(hidden_states)
604
+ hidden_states = hidden_states * 0.5 + residual
605
+ residual = hidden_states
606
+
607
+ # 2. Self-Attention layer
608
+ hidden_states = self.self_attn_layer_norm(hidden_states)
609
+ hidden_states, attn_weigts = self.self_attn(
610
+ hidden_states=hidden_states,
611
+ attention_mask=attention_mask,
612
+ relative_position_embeddings=relative_position_embeddings,
613
+ output_attentions=output_attentions,
614
+ )
615
+ hidden_states = self.self_attn_dropout(hidden_states)
616
+ hidden_states = hidden_states + residual
617
+
618
+ # 3. Convolutional Layer
619
+ residual = hidden_states
620
+ hidden_states = self.conv_module(hidden_states)
621
+ hidden_states = residual + hidden_states
622
+
623
+ # 4. Feed-Forward 2 Layer
624
+ residual = hidden_states
625
+ hidden_states = self.ffn2_layer_norm(hidden_states)
626
+ hidden_states = self.ffn2(hidden_states)
627
+ hidden_states = hidden_states * 0.5 + residual
628
+ hidden_states = self.final_layer_norm(hidden_states)
629
+
630
+ return hidden_states, attn_weigts
631
+
632
+
633
+ class Wav2Vec2ConformerEncoder(nn.Module):
634
+ def __init__(self, config):
635
+ super().__init__()
636
+ self.config = config
637
+
638
+ if config.position_embeddings_type == "relative":
639
+ self.embed_positions = Wav2Vec2ConformerRelPositionalEmbedding(config)
640
+ elif config.position_embeddings_type == "rotary":
641
+ self.embed_positions = Wav2Vec2ConformerRotaryPositionalEmbedding(config)
642
+ else:
643
+ self.embed_positions = None
644
+
645
+ self.pos_conv_embed = Wav2Vec2ConformerPositionalConvEmbedding(config)
646
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
647
+ self.dropout = nn.Dropout(config.hidden_dropout)
648
+ self.layers = nn.ModuleList([Wav2Vec2ConformerEncoderLayer(config) for _ in range(config.num_hidden_layers)])
649
+ self.gradient_checkpointing = False
650
+
651
+ def forward(
652
+ self,
653
+ hidden_states,
654
+ attention_mask=None,
655
+ output_attentions=False,
656
+ output_hidden_states=False,
657
+ return_dict=True,
658
+ ):
659
+ all_hidden_states = () if output_hidden_states else None
660
+ all_self_attentions = () if output_attentions else None
661
+
662
+ if attention_mask is not None:
663
+ # make sure padded tokens output 0
664
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
665
+ hidden_states[~expand_attention_mask] = 0.0
666
+
667
+ # extend attention_mask
668
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
669
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
670
+ attention_mask = attention_mask.expand(
671
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
672
+ )
673
+
674
+ hidden_states = self.dropout(hidden_states)
675
+
676
+ if self.embed_positions is not None:
677
+ relative_position_embeddings = self.embed_positions(hidden_states)
678
+ else:
679
+ relative_position_embeddings = None
680
+
681
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
682
+
683
+ for i, layer in enumerate(self.layers):
684
+ if output_hidden_states:
685
+ all_hidden_states = all_hidden_states + (hidden_states,)
686
+
687
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
688
+ dropout_probability = torch.rand([])
689
+
690
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
691
+ if not skip_the_layer or synced_gpus:
692
+ # under fsdp or deepspeed zero3 all gpus must run in sync
693
+ layer_outputs = layer(
694
+ hidden_states,
695
+ attention_mask=attention_mask,
696
+ relative_position_embeddings=relative_position_embeddings,
697
+ output_attentions=output_attentions,
698
+ )
699
+ hidden_states = layer_outputs[0]
700
+
701
+ if skip_the_layer:
702
+ layer_outputs = (None, None)
703
+
704
+ if output_attentions:
705
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
706
+
707
+ hidden_states = self.layer_norm(hidden_states)
708
+ if output_hidden_states:
709
+ all_hidden_states = all_hidden_states + (hidden_states,)
710
+
711
+ if not return_dict:
712
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
713
+ return BaseModelOutput(
714
+ last_hidden_state=hidden_states,
715
+ hidden_states=all_hidden_states,
716
+ attentions=all_self_attentions,
717
+ )
718
+
719
+
720
+ class Wav2Vec2ConformerGumbelVectorQuantizer(nn.Module):
721
+ """
722
+ Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
723
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
724
+ """
725
+
726
+ def __init__(self, config):
727
+ super().__init__()
728
+ self.num_groups = config.num_codevector_groups
729
+ self.num_vars = config.num_codevectors_per_group
730
+
731
+ if config.codevector_dim % self.num_groups != 0:
732
+ raise ValueError(
733
+ f"`config.codevector_dim {config.codevector_dim} must be divisible "
734
+ f"by `config.num_codevector_groups` {self.num_groups} for concatenation"
735
+ )
736
+
737
+ # storage for codebook variables (codewords)
738
+ self.codevectors = nn.Parameter(
739
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
740
+ )
741
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
742
+
743
+ # can be decayed for training
744
+ self.temperature = 2
745
+
746
+ @staticmethod
747
+ def _compute_perplexity(probs, mask=None):
748
+ if mask is not None:
749
+ mask_extended = mask.flatten()[:, None, None].expand(probs.shape)
750
+ probs = torch.where(mask_extended, probs, torch.zeros_like(probs))
751
+ marginal_probs = probs.sum(dim=0) / mask.sum()
752
+ else:
753
+ marginal_probs = probs.mean(dim=0)
754
+
755
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
756
+ return perplexity
757
+
758
+ def forward(self, hidden_states, mask_time_indices=None):
759
+ batch_size, sequence_length, hidden_size = hidden_states.shape
760
+
761
+ # project to codevector dim
762
+ hidden_states = self.weight_proj(hidden_states)
763
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
764
+
765
+ if self.training:
766
+ # sample code vector probs via gumbel in differentiateable way
767
+ codevector_probs = nn.functional.gumbel_softmax(
768
+ hidden_states.float(), tau=self.temperature, hard=True
769
+ ).type_as(hidden_states)
770
+
771
+ # compute perplexity
772
+ codevector_soft_dist = torch.softmax(
773
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
774
+ )
775
+ perplexity = self._compute_perplexity(codevector_soft_dist, mask_time_indices)
776
+ else:
777
+ # take argmax in non-differentiable way
778
+ # comptute hard codevector distribution (one hot)
779
+ codevector_idx = hidden_states.argmax(dim=-1)
780
+ codevector_probs = hidden_states.new_zeros(hidden_states.shape).scatter_(
781
+ -1, codevector_idx.view(-1, 1), 1.0
782
+ )
783
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
784
+
785
+ perplexity = self._compute_perplexity(codevector_probs, mask_time_indices)
786
+
787
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
788
+ # use probs to retrieve codevectors
789
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
790
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
791
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
792
+
793
+ return codevectors, perplexity
794
+
795
+
796
+ class Wav2Vec2ConformerAdapter(nn.Module):
797
+ def __init__(self, config):
798
+ super().__init__()
799
+
800
+ # feature dim might need to be down-projected
801
+ if config.output_hidden_size != config.hidden_size:
802
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
803
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)
804
+ else:
805
+ self.proj = self.proj_layer_norm = None
806
+
807
+ self.layers = nn.ModuleList(Wav2Vec2ConformerAdapterLayer(config) for _ in range(config.num_adapter_layers))
808
+ self.layerdrop = config.layerdrop
809
+
810
+ def forward(self, hidden_states):
811
+ # down project hidden_states if necessary
812
+ if self.proj is not None and self.proj_layer_norm is not None:
813
+ hidden_states = self.proj(hidden_states)
814
+ hidden_states = self.proj_layer_norm(hidden_states)
815
+
816
+ hidden_states = hidden_states.transpose(1, 2)
817
+
818
+ for layer in self.layers:
819
+ layerdrop_prob = np.random.random()
820
+ if not self.training or (layerdrop_prob > self.layerdrop):
821
+ hidden_states = layer(hidden_states)
822
+
823
+ hidden_states = hidden_states.transpose(1, 2)
824
+ return hidden_states
825
+
826
+
827
+ class Wav2Vec2ConformerAdapterLayer(nn.Module):
828
+ def __init__(self, config):
829
+ super().__init__()
830
+ self.conv = nn.Conv1d(
831
+ config.output_hidden_size,
832
+ 2 * config.output_hidden_size,
833
+ config.adapter_kernel_size,
834
+ stride=config.adapter_stride,
835
+ padding=1,
836
+ )
837
+
838
+ def forward(self, hidden_states):
839
+ hidden_states = self.conv(hidden_states)
840
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
841
+
842
+ return hidden_states
843
+
844
+
845
+ @auto_docstring
846
+ class Wav2Vec2ConformerPreTrainedModel(PreTrainedModel):
847
+ config: Wav2Vec2ConformerConfig
848
+ base_model_prefix = "wav2vec2_conformer"
849
+ main_input_name = "input_values"
850
+ input_modalities = "audio"
851
+ supports_gradient_checkpointing = True
852
+
853
+ @torch.no_grad()
854
+ def _init_weights(self, module):
855
+ """Initialize the weights"""
856
+ # Wav2Vec2ForPreTraining last 2 linear layers need standard Linear init.
857
+ if isinstance(module, Wav2Vec2ConformerForPreTraining):
858
+ module.project_hid.reset_parameters()
859
+ module.project_q.reset_parameters()
860
+ # gumbel softmax requires special init
861
+ elif isinstance(module, Wav2Vec2ConformerGumbelVectorQuantizer):
862
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
863
+ init.zeros_(module.weight_proj.bias)
864
+ init.uniform_(module.codevectors)
865
+ elif isinstance(module, Wav2Vec2ConformerSelfAttention):
866
+ if hasattr(module, "pos_bias_u"):
867
+ init.xavier_uniform_(module.pos_bias_u)
868
+ if hasattr(module, "pos_bias_v"):
869
+ init.xavier_uniform_(module.pos_bias_v)
870
+ elif isinstance(module, Wav2Vec2ConformerPositionalConvEmbedding):
871
+ init.normal_(
872
+ module.conv.weight,
873
+ mean=0,
874
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
875
+ )
876
+ init.constant_(module.conv.bias, 0)
877
+ elif isinstance(module, Wav2Vec2ConformerFeatureProjection):
878
+ k = math.sqrt(1 / module.projection.in_features)
879
+ init.uniform_(module.projection.weight, a=-k, b=k)
880
+ init.uniform_(module.projection.bias, a=-k, b=k)
881
+ elif isinstance(module, nn.Linear):
882
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
883
+
884
+ if module.bias is not None:
885
+ init.zeros_(module.bias)
886
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm1d)):
887
+ init.zeros_(module.bias)
888
+ init.ones_(module.weight)
889
+ if getattr(module, "running_mean", None) is not None:
890
+ init.zeros_(module.running_mean)
891
+ init.ones_(module.running_var)
892
+ init.zeros_(module.num_batches_tracked)
893
+ elif isinstance(module, nn.Conv1d):
894
+ init.kaiming_normal_(module.weight)
895
+
896
+ if module.bias is not None:
897
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
898
+ init.uniform_(module.bias, a=-k, b=k)
899
+ elif isinstance(module, Wav2Vec2ConformerRotaryPositionalEmbedding):
900
+ dim = self.config.hidden_size // self.config.num_attention_heads
901
+ base = self.config.rotary_embedding_base
902
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
903
+ init.copy_(module.inv_freq, inv_freq)
904
+ elif isinstance(module, Wav2Vec2ConformerRelPositionalEmbedding):
905
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
906
+
907
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
908
+ """
909
+ Computes the output length of the convolutional layers
910
+ """
911
+
912
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
913
+
914
+ def _conv_out_length(input_length, kernel_size, stride):
915
+ # 1D convolutional layer output length formula taken
916
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
917
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
918
+
919
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
920
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
921
+
922
+ if add_adapter:
923
+ for _ in range(self.config.num_adapter_layers):
924
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
925
+
926
+ return input_lengths
927
+
928
+ def _get_feature_vector_attention_mask(
929
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
930
+ ):
931
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
932
+ # on inference mode.
933
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
934
+
935
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
936
+ output_lengths = output_lengths.to(torch.long)
937
+
938
+ batch_size = attention_mask.shape[0]
939
+
940
+ attention_mask = torch.zeros(
941
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
942
+ )
943
+ # these two operations makes sure that all values before the output lengths idxs are attended to
944
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
945
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
946
+ return attention_mask
947
+
948
+
949
+ def _compute_mask_indices(
950
+ shape: tuple[int, int],
951
+ mask_prob: float,
952
+ mask_length: int,
953
+ attention_mask: torch.LongTensor | None = None,
954
+ min_masks: int = 0,
955
+ ) -> np.ndarray:
956
+ """
957
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
958
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
959
+ CPU as part of the preprocessing during training.
960
+
961
+ Args:
962
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
963
+ the first element is the batch size and the second element is the length of the axis to span.
964
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
965
+ independently generated mask spans of length `mask_length` is computed by
966
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
967
+ actual percentage will be smaller.
968
+ mask_length: size of the mask
969
+ min_masks: minimum number of masked spans
970
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
971
+ each batch dimension.
972
+ """
973
+ batch_size, sequence_length = shape
974
+
975
+ if mask_length < 1:
976
+ raise ValueError("`mask_length` has to be bigger than 0.")
977
+
978
+ if mask_length > sequence_length:
979
+ raise ValueError(
980
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
981
+ f" and `sequence_length`: {sequence_length}`"
982
+ )
983
+
984
+ # epsilon is used for probabilistic rounding
985
+ epsilon = np.random.rand(1).item()
986
+
987
+ def compute_num_masked_span(input_length):
988
+ """Given input length, compute how many spans should be masked"""
989
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
990
+ num_masked_span = max(num_masked_span, min_masks)
991
+
992
+ # make sure num masked span <= sequence_length
993
+ if num_masked_span * mask_length > sequence_length:
994
+ num_masked_span = sequence_length // mask_length
995
+
996
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
997
+ if input_length - (mask_length - 1) < num_masked_span:
998
+ num_masked_span = max(input_length - (mask_length - 1), 0)
999
+
1000
+ return num_masked_span
1001
+
1002
+ # compute number of masked spans in batch
1003
+ input_lengths = (
1004
+ attention_mask.detach().sum(-1).tolist()
1005
+ if attention_mask is not None
1006
+ else [sequence_length for _ in range(batch_size)]
1007
+ )
1008
+
1009
+ # SpecAugment mask to fill
1010
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
1011
+ spec_aug_mask_idxs = []
1012
+
1013
+ max_num_masked_span = compute_num_masked_span(sequence_length)
1014
+
1015
+ if max_num_masked_span == 0:
1016
+ return spec_aug_mask
1017
+
1018
+ for input_length in input_lengths:
1019
+ # compute num of masked spans for this input
1020
+ num_masked_span = compute_num_masked_span(input_length)
1021
+
1022
+ # get random indices to mask
1023
+ spec_aug_mask_idx = np.random.choice(
1024
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
1025
+ )
1026
+
1027
+ # pick first sampled index that will serve as a dummy index to pad vector
1028
+ # to ensure same dimension for all batches due to probabilistic rounding
1029
+ # Picking first sample just pads those vectors twice.
1030
+ if len(spec_aug_mask_idx) == 0:
1031
+ # this case can only happen if `input_length` is strictly smaller then
1032
+ # `sequence_length` in which case the last token has to be a padding
1033
+ # token which we can use as a dummy mask id
1034
+ dummy_mask_idx = sequence_length - 1
1035
+ else:
1036
+ dummy_mask_idx = spec_aug_mask_idx[0]
1037
+
1038
+ spec_aug_mask_idx = np.concatenate(
1039
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
1040
+ )
1041
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
1042
+
1043
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
1044
+
1045
+ # expand masked indices to masked spans
1046
+ spec_aug_mask_idxs = np.broadcast_to(
1047
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
1048
+ )
1049
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
1050
+
1051
+ # add offset to the starting indexes so that indexes now create a span
1052
+ offsets = np.arange(mask_length)[None, None, :]
1053
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
1054
+ batch_size, max_num_masked_span * mask_length
1055
+ )
1056
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
1057
+
1058
+ # ensure that we cannot have indices larger than sequence_length
1059
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
1060
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
1061
+
1062
+ # scatter indices to mask
1063
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
1064
+
1065
+ return spec_aug_mask
1066
+
1067
+
1068
+ Wav2Vec2ConformerBaseModelOutput = Wav2Vec2BaseModelOutput
1069
+
1070
+
1071
+ @auto_docstring
1072
+ class Wav2Vec2ConformerModel(Wav2Vec2ConformerPreTrainedModel):
1073
+ def __init__(self, config: Wav2Vec2ConformerConfig):
1074
+ super().__init__(config)
1075
+ self.config = config
1076
+ self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config)
1077
+ self.feature_projection = Wav2Vec2ConformerFeatureProjection(config)
1078
+
1079
+ # model only needs masking vector if mask prob is > 0.0
1080
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
1081
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
1082
+
1083
+ self.encoder = Wav2Vec2ConformerEncoder(config)
1084
+
1085
+ self.adapter = Wav2Vec2ConformerAdapter(config) if config.add_adapter else None
1086
+
1087
+ # Initialize weights and apply final processing
1088
+ self.post_init()
1089
+
1090
+ def freeze_feature_encoder(self):
1091
+ """
1092
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1093
+ not be updated during training.
1094
+ """
1095
+ self.feature_extractor._freeze_parameters()
1096
+
1097
+ def _mask_hidden_states(
1098
+ self,
1099
+ hidden_states: torch.FloatTensor,
1100
+ mask_time_indices: torch.FloatTensor | None = None,
1101
+ attention_mask: torch.LongTensor | None = None,
1102
+ ):
1103
+ """
1104
+ Masks extracted features along time axis and/or along feature axis according to
1105
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
1106
+ """
1107
+
1108
+ # `config.apply_spec_augment` can set masking to False
1109
+ if not getattr(self.config, "apply_spec_augment", True):
1110
+ return hidden_states
1111
+
1112
+ # generate indices & apply SpecAugment along time axis
1113
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1114
+
1115
+ if mask_time_indices is not None:
1116
+ # apply SpecAugment along time axis with given mask_time_indices
1117
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1118
+ elif self.config.mask_time_prob > 0 and self.training:
1119
+ mask_time_indices = _compute_mask_indices(
1120
+ (batch_size, sequence_length),
1121
+ mask_prob=self.config.mask_time_prob,
1122
+ mask_length=self.config.mask_time_length,
1123
+ attention_mask=attention_mask,
1124
+ min_masks=self.config.mask_time_min_masks,
1125
+ )
1126
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1127
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1128
+
1129
+ if self.config.mask_feature_prob > 0 and self.training:
1130
+ # generate indices & apply SpecAugment along feature axis
1131
+ mask_feature_indices = _compute_mask_indices(
1132
+ (batch_size, hidden_size),
1133
+ mask_prob=self.config.mask_feature_prob,
1134
+ mask_length=self.config.mask_feature_length,
1135
+ min_masks=self.config.mask_feature_min_masks,
1136
+ )
1137
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1138
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1139
+ hidden_states[mask_feature_indices] = 0
1140
+
1141
+ return hidden_states
1142
+
1143
+ @auto_docstring
1144
+ def forward(
1145
+ self,
1146
+ input_values: torch.Tensor | None,
1147
+ attention_mask: torch.Tensor | None = None,
1148
+ mask_time_indices: torch.FloatTensor | None = None,
1149
+ output_attentions: bool | None = None,
1150
+ output_hidden_states: bool | None = None,
1151
+ return_dict: bool | None = None,
1152
+ **kwargs,
1153
+ ) -> tuple | Wav2Vec2ConformerBaseModelOutput:
1154
+ r"""
1155
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1156
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1157
+ masked extracted features in *config.proj_codevector_dim* space.
1158
+ """
1159
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1160
+ output_hidden_states = (
1161
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1162
+ )
1163
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1164
+
1165
+ extract_features = self.feature_extractor(input_values)
1166
+ extract_features = extract_features.transpose(1, 2)
1167
+
1168
+ if attention_mask is not None:
1169
+ # compute reduced attention_mask corresponding to feature vectors
1170
+ attention_mask = self._get_feature_vector_attention_mask(
1171
+ extract_features.shape[1], attention_mask, add_adapter=False
1172
+ )
1173
+
1174
+ hidden_states, extract_features = self.feature_projection(extract_features)
1175
+ hidden_states = self._mask_hidden_states(
1176
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1177
+ )
1178
+
1179
+ encoder_outputs = self.encoder(
1180
+ hidden_states,
1181
+ attention_mask=attention_mask,
1182
+ output_attentions=output_attentions,
1183
+ output_hidden_states=output_hidden_states,
1184
+ return_dict=return_dict,
1185
+ )
1186
+
1187
+ hidden_states = encoder_outputs[0]
1188
+
1189
+ if self.adapter is not None:
1190
+ hidden_states = self.adapter(hidden_states)
1191
+
1192
+ if not return_dict:
1193
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1194
+
1195
+ return Wav2Vec2ConformerBaseModelOutput(
1196
+ last_hidden_state=hidden_states,
1197
+ extract_features=extract_features,
1198
+ hidden_states=encoder_outputs.hidden_states,
1199
+ attentions=encoder_outputs.attentions,
1200
+ )
1201
+
1202
+
1203
+ @auto_docstring(
1204
+ custom_intro="""
1205
+ Wav2Vec2Conformer Model with a quantizer and `VQ` head on top.
1206
+ """
1207
+ )
1208
+ class Wav2Vec2ConformerForPreTraining(Wav2Vec2ConformerPreTrainedModel):
1209
+ def __init__(self, config: Wav2Vec2ConformerConfig):
1210
+ super().__init__(config)
1211
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
1212
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
1213
+
1214
+ self.quantizer = Wav2Vec2ConformerGumbelVectorQuantizer(config)
1215
+
1216
+ self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)
1217
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
1218
+
1219
+ # Initialize weights and apply final processing
1220
+ self.post_init()
1221
+
1222
+ def set_gumbel_temperature(self, temperature: int):
1223
+ """
1224
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
1225
+ """
1226
+ self.quantizer.temperature = temperature
1227
+
1228
+ def freeze_feature_encoder(self):
1229
+ """
1230
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1231
+ not be updated during training.
1232
+ """
1233
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
1234
+
1235
+ @staticmethod
1236
+ def compute_contrastive_logits(
1237
+ target_features: torch.FloatTensor,
1238
+ negative_features: torch.FloatTensor,
1239
+ predicted_features: torch.FloatTensor,
1240
+ temperature: float = 0.1,
1241
+ ):
1242
+ """
1243
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
1244
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
1245
+ """
1246
+ target_features = torch.cat([target_features, negative_features], dim=0)
1247
+
1248
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1).type_as(
1249
+ target_features
1250
+ )
1251
+
1252
+ # apply temperature
1253
+ logits = logits / temperature
1254
+ return logits
1255
+
1256
+ @auto_docstring
1257
+ def forward(
1258
+ self,
1259
+ input_values: torch.Tensor | None,
1260
+ attention_mask: torch.Tensor | None = None,
1261
+ mask_time_indices: torch.BoolTensor | None = None,
1262
+ sampled_negative_indices: torch.BoolTensor | None = None,
1263
+ output_attentions: bool | None = None,
1264
+ output_hidden_states: bool | None = None,
1265
+ return_dict: bool | None = None,
1266
+ **kwargs,
1267
+ ) -> tuple | Wav2Vec2ConformerForPreTrainingOutput:
1268
+ r"""
1269
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1270
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1271
+ masked extracted features in *config.proj_codevector_dim* space.
1272
+ sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
1273
+ Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
1274
+ Required input for pre-training.
1275
+
1276
+ Example:
1277
+
1278
+ ```python
1279
+ >>> import torch
1280
+ >>> from transformers import AutoFeatureExtractor, Wav2Vec2ConformerForPreTraining
1281
+ >>> from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer import _compute_mask_indices, _sample_negative_indices
1282
+ >>> from datasets import load_dataset
1283
+
1284
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2_conformer-base")
1285
+ >>> model = Wav2Vec2ConformerForPreTraining.from_pretrained("facebook/wav2vec2_conformer-base")
1286
+
1287
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
1288
+ >>> input_values = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt").input_values # Batch size 1
1289
+
1290
+ >>> # compute masked indices
1291
+ >>> batch_size, raw_sequence_length = input_values.shape
1292
+ >>> sequence_length = model._get_feat_extract_output_lengths(raw_sequence_length).item()
1293
+ >>> mask_time_indices = _compute_mask_indices(
1294
+ ... shape=(batch_size, sequence_length), mask_prob=0.2, mask_length=2
1295
+ ... )
1296
+ >>> sampled_negative_indices = _sample_negative_indices(
1297
+ ... features_shape=(batch_size, sequence_length),
1298
+ ... num_negatives=model.config.num_negatives,
1299
+ ... mask_time_indices=mask_time_indices,
1300
+ ... )
1301
+ >>> mask_time_indices = torch.tensor(data=mask_time_indices, device=input_values.device, dtype=torch.long)
1302
+ >>> sampled_negative_indices = torch.tensor(
1303
+ ... data=sampled_negative_indices, device=input_values.device, dtype=torch.long
1304
+ ... )
1305
+
1306
+ >>> with torch.no_grad():
1307
+ ... outputs = model(input_values, mask_time_indices=mask_time_indices)
1308
+
1309
+ >>> # compute cosine similarity between predicted (=projected_states) and target (=projected_quantized_states)
1310
+ >>> cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)
1311
+
1312
+ >>> # show that cosine similarity is much higher than random
1313
+ >>> cosine_sim[mask_time_indices.to(torch.bool)].mean() > 0.5
1314
+ tensor(True)
1315
+
1316
+ >>> # for contrastive loss training model should be put into train mode
1317
+ >>> model = model.train()
1318
+ >>> loss = model(
1319
+ ... input_values, mask_time_indices=mask_time_indices, sampled_negative_indices=sampled_negative_indices
1320
+ ... ).loss
1321
+ ```"""
1322
+
1323
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1324
+
1325
+ if mask_time_indices is not None:
1326
+ mask_time_indices = mask_time_indices.to(torch.bool)
1327
+
1328
+ outputs = self.wav2vec2_conformer(
1329
+ input_values,
1330
+ attention_mask=attention_mask,
1331
+ output_attentions=output_attentions,
1332
+ output_hidden_states=output_hidden_states,
1333
+ mask_time_indices=mask_time_indices,
1334
+ return_dict=return_dict,
1335
+ )
1336
+
1337
+ # 1. project all transformed features (including masked) to final vq dim
1338
+ transformer_features = self.project_hid(outputs[0])
1339
+
1340
+ # 2. quantize all (unmasked) extracted features and project to final vq dim
1341
+ extract_features = self.dropout_features(outputs[1])
1342
+
1343
+ if attention_mask is not None:
1344
+ # compute reduced attention_mask corresponding to feature vectors
1345
+ attention_mask = self._get_feature_vector_attention_mask(
1346
+ extract_features.shape[1], attention_mask, add_adapter=False
1347
+ )
1348
+
1349
+ quantized_features, codevector_perplexity = self.quantizer(
1350
+ extract_features, mask_time_indices=mask_time_indices
1351
+ )
1352
+
1353
+ quantized_features = quantized_features.to(self.project_q.weight.dtype)
1354
+ quantized_features = self.project_q(quantized_features)
1355
+
1356
+ loss = contrastive_loss = diversity_loss = None
1357
+ if sampled_negative_indices is not None:
1358
+ batch_size, sequence_length, hidden_size = quantized_features.shape
1359
+
1360
+ # for training, we sample negatives
1361
+ # 3. sample K negatives (distractors) quantized states for contrastive loss
1362
+ # if attention_mask is passed, make sure that padded feature vectors cannot be sampled
1363
+ # sample negative quantized vectors BTC => (BxT)C
1364
+ negative_quantized_features = quantized_features.view(-1, hidden_size)[
1365
+ sampled_negative_indices.long().view(-1)
1366
+ ]
1367
+ negative_quantized_features = negative_quantized_features.view(
1368
+ batch_size, sequence_length, -1, hidden_size
1369
+ ).permute(2, 0, 1, 3)
1370
+
1371
+ # 4. compute logits, corresponding to `logs = sim(c_t, [q_t, \sim{q}_t]) / \kappa`
1372
+ # of equation (3) in https://huggingface.co/papers/2006.11477
1373
+ logits = self.compute_contrastive_logits(
1374
+ quantized_features[None, :],
1375
+ negative_quantized_features,
1376
+ transformer_features,
1377
+ self.config.contrastive_logits_temperature,
1378
+ )
1379
+
1380
+ # 5. if a negative vector is identical to the positive (i.e. when codebook utilization is low),
1381
+ # its cosine similarity will be masked
1382
+ neg_is_pos = (quantized_features == negative_quantized_features).all(-1)
1383
+
1384
+ if neg_is_pos.any():
1385
+ logits[1:][neg_is_pos] = float("-inf")
1386
+
1387
+ # 6. compute contrastive loss \mathbf{L}_m = cross_entropy(logs) =
1388
+ # -log(exp(sim(c_t, q_t)/\kappa) / \sum_{\sim{q}} exp(sim(c_t, \sim{q})/\kappa))
1389
+ logits = logits.transpose(0, 2).reshape(-1, logits.size(0))
1390
+ target = ((1 - mask_time_indices.long()) * -100).transpose(0, 1).flatten()
1391
+
1392
+ contrastive_loss = nn.functional.cross_entropy(logits.float(), target, reduction="sum")
1393
+ # 7. compute diversity loss: \mathbf{L}_d
1394
+ num_codevectors = self.config.num_codevectors_per_group * self.config.num_codevector_groups
1395
+ diversity_loss = ((num_codevectors - codevector_perplexity) / num_codevectors) * mask_time_indices.sum()
1396
+
1397
+ # 8. \mathbf{L} = \mathbf{L}_m + \alpha * \mathbf{L}_d
1398
+ loss = contrastive_loss + self.config.diversity_loss_weight * diversity_loss
1399
+
1400
+ if not return_dict:
1401
+ if loss is not None:
1402
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1403
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1404
+
1405
+ return Wav2Vec2ConformerForPreTrainingOutput(
1406
+ loss=loss,
1407
+ projected_states=transformer_features,
1408
+ projected_quantized_states=quantized_features,
1409
+ codevector_perplexity=codevector_perplexity,
1410
+ hidden_states=outputs.hidden_states,
1411
+ attentions=outputs.attentions,
1412
+ contrastive_loss=contrastive_loss,
1413
+ diversity_loss=diversity_loss,
1414
+ )
1415
+
1416
+
1417
+ _HIDDEN_STATES_START_POSITION = 2
1418
+
1419
+
1420
+ @auto_docstring(
1421
+ custom_intro="""
1422
+ Wav2Vec2Conformer Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1423
+ """
1424
+ )
1425
+ class Wav2Vec2ConformerForCTC(Wav2Vec2ConformerPreTrainedModel):
1426
+ def __init__(self, config, target_lang: str | None = None):
1427
+ r"""
1428
+ target_lang (`str`, *optional*):
1429
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1430
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
1431
+ default.
1432
+ """
1433
+ super().__init__(config)
1434
+
1435
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
1436
+ self.dropout = nn.Dropout(config.final_dropout)
1437
+
1438
+ self.target_lang = target_lang
1439
+
1440
+ if config.vocab_size is None:
1441
+ raise ValueError(
1442
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1443
+ "does not define the vocabulary size of the language model head. Please "
1444
+ "instantiate the model as follows: `Wav2Vec2ConformerForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1445
+ "or define `vocab_size` of your model's configuration."
1446
+ )
1447
+ output_hidden_size = (
1448
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1449
+ )
1450
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1451
+
1452
+ # Initialize weights and apply final processing
1453
+ self.post_init()
1454
+
1455
+ def freeze_feature_encoder(self):
1456
+ """
1457
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1458
+ not be updated during training.
1459
+ """
1460
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
1461
+
1462
+ @auto_docstring
1463
+ def forward(
1464
+ self,
1465
+ input_values: torch.Tensor | None,
1466
+ attention_mask: torch.Tensor | None = None,
1467
+ output_attentions: bool | None = None,
1468
+ output_hidden_states: bool | None = None,
1469
+ return_dict: bool | None = None,
1470
+ labels: torch.Tensor | None = None,
1471
+ **kwargs,
1472
+ ) -> tuple | CausalLMOutput:
1473
+ r"""
1474
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1475
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1476
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1477
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1478
+ config.vocab_size - 1]`.
1479
+ """
1480
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1481
+
1482
+ if labels is not None and labels.max() >= self.config.vocab_size:
1483
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1484
+
1485
+ outputs = self.wav2vec2_conformer(
1486
+ input_values,
1487
+ attention_mask=attention_mask,
1488
+ output_attentions=output_attentions,
1489
+ output_hidden_states=output_hidden_states,
1490
+ return_dict=return_dict,
1491
+ )
1492
+
1493
+ hidden_states = outputs[0]
1494
+ hidden_states = self.dropout(hidden_states)
1495
+
1496
+ logits = self.lm_head(hidden_states)
1497
+
1498
+ loss = None
1499
+ if labels is not None:
1500
+ # retrieve loss input_lengths from attention_mask
1501
+ attention_mask = (
1502
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1503
+ )
1504
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1505
+
1506
+ # assuming that padded tokens are filled with -100
1507
+ # when not being attended to
1508
+ labels_mask = labels >= 0
1509
+ target_lengths = labels_mask.sum(-1)
1510
+ flattened_targets = labels.masked_select(labels_mask)
1511
+
1512
+ # ctc_loss doesn't support fp16
1513
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1514
+
1515
+ with torch.backends.cudnn.flags(enabled=False):
1516
+ loss = nn.functional.ctc_loss(
1517
+ log_probs,
1518
+ flattened_targets,
1519
+ input_lengths,
1520
+ target_lengths,
1521
+ blank=self.config.pad_token_id,
1522
+ reduction=self.config.ctc_loss_reduction,
1523
+ zero_infinity=self.config.ctc_zero_infinity,
1524
+ )
1525
+
1526
+ if not return_dict:
1527
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1528
+ return ((loss,) + output) if loss is not None else output
1529
+
1530
+ return CausalLMOutput(
1531
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1532
+ )
1533
+
1534
+
1535
+ @auto_docstring(
1536
+ custom_intro="""
1537
+ Wav2Vec2Conformer Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1538
+ SUPERB Keyword Spotting.
1539
+ """
1540
+ )
1541
+ class Wav2Vec2ConformerForSequenceClassification(Wav2Vec2ConformerPreTrainedModel):
1542
+ def __init__(self, config):
1543
+ super().__init__(config)
1544
+
1545
+ if hasattr(config, "add_adapter") and config.add_adapter:
1546
+ raise ValueError(
1547
+ "Sequence classification does not support the use of Wav2Vec2Conformer adapters (config.add_adapter=True)"
1548
+ )
1549
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
1550
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1551
+ if config.use_weighted_layer_sum:
1552
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1553
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1554
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1555
+
1556
+ # Initialize weights and apply final processing
1557
+ self.post_init()
1558
+
1559
+ def freeze_feature_encoder(self):
1560
+ """
1561
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1562
+ not be updated during training.
1563
+ """
1564
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
1565
+
1566
+ def freeze_base_model(self):
1567
+ """
1568
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1569
+ be updated during training. Only the classification head will be updated.
1570
+ """
1571
+ for param in self.wav2vec2_conformer.parameters():
1572
+ param.requires_grad = False
1573
+
1574
+ @auto_docstring
1575
+ def forward(
1576
+ self,
1577
+ input_values: torch.Tensor | None,
1578
+ attention_mask: torch.Tensor | None = None,
1579
+ output_attentions: bool | None = None,
1580
+ output_hidden_states: bool | None = None,
1581
+ return_dict: bool | None = None,
1582
+ labels: torch.Tensor | None = None,
1583
+ **kwargs,
1584
+ ) -> tuple | SequenceClassifierOutput:
1585
+ r"""
1586
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1587
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1588
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1589
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1590
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1591
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2ConformerProcessor.__call__`] for details.
1592
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1593
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1594
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1595
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1596
+ """
1597
+
1598
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1599
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1600
+
1601
+ outputs = self.wav2vec2_conformer(
1602
+ input_values,
1603
+ attention_mask=attention_mask,
1604
+ output_attentions=output_attentions,
1605
+ output_hidden_states=output_hidden_states,
1606
+ return_dict=return_dict,
1607
+ )
1608
+
1609
+ if self.config.use_weighted_layer_sum:
1610
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1611
+ hidden_states = torch.stack(hidden_states, dim=1)
1612
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1613
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1614
+ else:
1615
+ hidden_states = outputs[0]
1616
+
1617
+ hidden_states = self.projector(hidden_states)
1618
+ if attention_mask is None:
1619
+ pooled_output = hidden_states.mean(dim=1)
1620
+ else:
1621
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1622
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1623
+ hidden_states[~expand_padding_mask] = 0.0
1624
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1625
+
1626
+ logits = self.classifier(pooled_output)
1627
+
1628
+ loss = None
1629
+ if labels is not None:
1630
+ loss_fct = CrossEntropyLoss()
1631
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1632
+
1633
+ if not return_dict:
1634
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1635
+ return ((loss,) + output) if loss is not None else output
1636
+
1637
+ return SequenceClassifierOutput(
1638
+ loss=loss,
1639
+ logits=logits,
1640
+ hidden_states=outputs.hidden_states,
1641
+ attentions=outputs.attentions,
1642
+ )
1643
+
1644
+
1645
+ @auto_docstring
1646
+ class Wav2Vec2ConformerForAudioFrameClassification(Wav2Vec2ConformerPreTrainedModel):
1647
+ def __init__(self, config):
1648
+ super().__init__(config)
1649
+
1650
+ if hasattr(config, "add_adapter") and config.add_adapter:
1651
+ raise ValueError(
1652
+ "Audio frame classification does not support the use of Wav2Vec2Conformer adapters (config.add_adapter=True)"
1653
+ )
1654
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
1655
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1656
+ if config.use_weighted_layer_sum:
1657
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1658
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1659
+ self.num_labels = config.num_labels
1660
+
1661
+ self.post_init()
1662
+
1663
+ def freeze_feature_encoder(self):
1664
+ """
1665
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1666
+ not be updated during training.
1667
+ """
1668
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
1669
+
1670
+ def freeze_base_model(self):
1671
+ """
1672
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1673
+ be updated during training. Only the classification head will be updated.
1674
+ """
1675
+ for param in self.wav2vec2_conformer.parameters():
1676
+ param.requires_grad = False
1677
+
1678
+ @auto_docstring
1679
+ def forward(
1680
+ self,
1681
+ input_values: torch.Tensor | None,
1682
+ attention_mask: torch.Tensor | None = None,
1683
+ labels: torch.Tensor | None = None,
1684
+ output_attentions: bool | None = None,
1685
+ output_hidden_states: bool | None = None,
1686
+ return_dict: bool | None = None,
1687
+ **kwargs,
1688
+ ) -> tuple | TokenClassifierOutput:
1689
+ r"""
1690
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1691
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1692
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1693
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1694
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1695
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2ConformerProcessor.__call__`] for details.
1696
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1697
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1698
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1699
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1700
+ """
1701
+
1702
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1703
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1704
+
1705
+ outputs = self.wav2vec2_conformer(
1706
+ input_values,
1707
+ attention_mask=attention_mask,
1708
+ output_attentions=output_attentions,
1709
+ output_hidden_states=output_hidden_states,
1710
+ return_dict=return_dict,
1711
+ )
1712
+
1713
+ if self.config.use_weighted_layer_sum:
1714
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1715
+ hidden_states = torch.stack(hidden_states, dim=1)
1716
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1717
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1718
+ else:
1719
+ hidden_states = outputs[0]
1720
+
1721
+ logits = self.classifier(hidden_states)
1722
+
1723
+ loss = None
1724
+ if labels is not None:
1725
+ loss_fct = CrossEntropyLoss()
1726
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
1727
+
1728
+ if not return_dict:
1729
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1730
+ return output
1731
+
1732
+ return TokenClassifierOutput(
1733
+ loss=loss,
1734
+ logits=logits,
1735
+ hidden_states=outputs.hidden_states,
1736
+ attentions=outputs.attentions,
1737
+ )
1738
+
1739
+
1740
+ class AMSoftmaxLoss(nn.Module):
1741
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
1742
+ super().__init__()
1743
+ self.scale = scale
1744
+ self.margin = margin
1745
+ self.num_labels = num_labels
1746
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
1747
+ self.loss = nn.CrossEntropyLoss()
1748
+
1749
+ def forward(self, hidden_states, labels):
1750
+ labels = labels.flatten()
1751
+ weight = nn.functional.normalize(self.weight, dim=0)
1752
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
1753
+ cos_theta = torch.mm(hidden_states, weight)
1754
+ psi = cos_theta - self.margin
1755
+
1756
+ onehot = nn.functional.one_hot(labels, self.num_labels)
1757
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
1758
+ loss = self.loss(logits, labels)
1759
+
1760
+ return loss
1761
+
1762
+
1763
+ class TDNNLayer(nn.Module):
1764
+ def __init__(self, config, layer_id=0):
1765
+ super().__init__()
1766
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
1767
+ self.out_conv_dim = config.tdnn_dim[layer_id]
1768
+ self.kernel_size = config.tdnn_kernel[layer_id]
1769
+ self.dilation = config.tdnn_dilation[layer_id]
1770
+
1771
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
1772
+ self.activation = nn.ReLU()
1773
+
1774
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1775
+ if is_peft_available():
1776
+ from peft.tuners.lora import LoraLayer
1777
+
1778
+ if is_peft_available():
1779
+ if isinstance(self.kernel, LoraLayer):
1780
+ warnings.warn(
1781
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
1782
+ "You should exclude TDNNLayer from LoRA's target modules.",
1783
+ )
1784
+
1785
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
1786
+ hidden_states = hidden_states.transpose(1, 2)
1787
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
1788
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
1789
+ hidden_states = hidden_states.transpose(1, 2)
1790
+
1791
+ hidden_states = self.activation(hidden_states)
1792
+ return hidden_states
1793
+
1794
+
1795
+ @auto_docstring(
1796
+ custom_intro="""
1797
+ Wav2Vec2Conformer Model with an XVector feature extraction head on top for tasks like Speaker Verification.
1798
+ """
1799
+ )
1800
+ class Wav2Vec2ConformerForXVector(Wav2Vec2ConformerPreTrainedModel):
1801
+ def __init__(self, config):
1802
+ super().__init__(config)
1803
+
1804
+ self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
1805
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1806
+ if config.use_weighted_layer_sum:
1807
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1808
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
1809
+
1810
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
1811
+ self.tdnn = nn.ModuleList(tdnn_layers)
1812
+
1813
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
1814
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
1815
+
1816
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
1817
+
1818
+ self.post_init()
1819
+
1820
+ def freeze_feature_encoder(self):
1821
+ """
1822
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1823
+ not be updated during training.
1824
+ """
1825
+ self.wav2vec2_conformer.feature_extractor._freeze_parameters()
1826
+
1827
+ def freeze_base_model(self):
1828
+ """
1829
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1830
+ be updated during training. Only the classification head will be updated.
1831
+ """
1832
+ for param in self.wav2vec2_conformer.parameters():
1833
+ param.requires_grad = False
1834
+
1835
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
1836
+ """
1837
+ Computes the output length of the TDNN layers
1838
+ """
1839
+
1840
+ def _conv_out_length(input_length, kernel_size, stride):
1841
+ # 1D convolutional layer output length formula taken
1842
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1843
+ return (input_length - kernel_size) // stride + 1
1844
+
1845
+ for kernel_size in self.config.tdnn_kernel:
1846
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
1847
+
1848
+ return input_lengths
1849
+
1850
+ @auto_docstring
1851
+ def forward(
1852
+ self,
1853
+ input_values: torch.Tensor | None,
1854
+ attention_mask: torch.Tensor | None = None,
1855
+ output_attentions: bool | None = None,
1856
+ output_hidden_states: bool | None = None,
1857
+ return_dict: bool | None = None,
1858
+ labels: torch.Tensor | None = None,
1859
+ **kwargs,
1860
+ ) -> tuple | XVectorOutput:
1861
+ r"""
1862
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1863
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1864
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1865
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1866
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1867
+ into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2ConformerProcessor.__call__`] for details.
1868
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1869
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1870
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1871
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1872
+ """
1873
+
1874
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1875
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1876
+
1877
+ outputs = self.wav2vec2_conformer(
1878
+ input_values,
1879
+ attention_mask=attention_mask,
1880
+ output_attentions=output_attentions,
1881
+ output_hidden_states=output_hidden_states,
1882
+ return_dict=return_dict,
1883
+ )
1884
+
1885
+ if self.config.use_weighted_layer_sum:
1886
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1887
+ hidden_states = torch.stack(hidden_states, dim=1)
1888
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1889
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1890
+ else:
1891
+ hidden_states = outputs[0]
1892
+
1893
+ hidden_states = self.projector(hidden_states)
1894
+
1895
+ for tdnn_layer in self.tdnn:
1896
+ hidden_states = tdnn_layer(hidden_states)
1897
+
1898
+ # Statistic Pooling
1899
+ if attention_mask is None:
1900
+ mean_features = hidden_states.mean(dim=1)
1901
+ std_features = hidden_states.std(dim=1)
1902
+ else:
1903
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
1904
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
1905
+ mean_features = []
1906
+ std_features = []
1907
+ for i, length in enumerate(tdnn_output_lengths):
1908
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
1909
+ std_features.append(hidden_states[i, :length].std(dim=0))
1910
+ mean_features = torch.stack(mean_features)
1911
+ std_features = torch.stack(std_features)
1912
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
1913
+
1914
+ output_embeddings = self.feature_extractor(statistic_pooling)
1915
+ logits = self.classifier(output_embeddings)
1916
+
1917
+ loss = None
1918
+ if labels is not None:
1919
+ loss = self.objective(logits, labels)
1920
+
1921
+ if not return_dict:
1922
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
1923
+ return ((loss,) + output) if loss is not None else output
1924
+
1925
+ return XVectorOutput(
1926
+ loss=loss,
1927
+ logits=logits,
1928
+ embeddings=output_embeddings,
1929
+ hidden_states=outputs.hidden_states,
1930
+ attentions=outputs.attentions,
1931
+ )
1932
+
1933
+
1934
+ __all__ = [
1935
+ "Wav2Vec2ConformerForAudioFrameClassification",
1936
+ "Wav2Vec2ConformerForCTC",
1937
+ "Wav2Vec2ConformerForPreTraining",
1938
+ "Wav2Vec2ConformerForSequenceClassification",
1939
+ "Wav2Vec2ConformerForXVector",
1940
+ "Wav2Vec2ConformerModel",
1941
+ "Wav2Vec2ConformerPreTrainedModel",
1942
+ ]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from ... import initialization as init
8
+ from ...activations import ACT2FN
9
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
10
+ from ...integrations.fsdp import is_fsdp_managed_module
11
+ from ...modeling_layers import GradientCheckpointingLayer
12
+ from ...modeling_outputs import BaseModelOutput, Wav2Vec2BaseModelOutput
13
+ from ...modeling_utils import PreTrainedModel
14
+ from ...utils import ModelOutput, auto_docstring, logging
15
+ from ..wav2vec2.modeling_wav2vec2 import (
16
+ Wav2Vec2Adapter,
17
+ Wav2Vec2AdapterLayer,
18
+ Wav2Vec2FeatureEncoder,
19
+ Wav2Vec2FeatureProjection,
20
+ Wav2Vec2FeedForward,
21
+ Wav2Vec2ForAudioFrameClassification,
22
+ Wav2Vec2ForCTC,
23
+ Wav2Vec2ForPreTraining,
24
+ Wav2Vec2ForSequenceClassification,
25
+ Wav2Vec2ForXVector,
26
+ Wav2Vec2GumbelVectorQuantizer,
27
+ Wav2Vec2Model,
28
+ Wav2Vec2PositionalConvEmbedding,
29
+ )
30
+ from .configuration_wav2vec2_conformer import Wav2Vec2ConformerConfig
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+ _HIDDEN_STATES_START_POSITION = 2
36
+
37
+
38
+ @auto_docstring(
39
+ custom_intro="""
40
+ Output type of [`Wav2Vec2ConformerForPreTraining`], with potential hidden states and attentions.
41
+ """
42
+ )
43
+ @dataclass
44
+ class Wav2Vec2ConformerForPreTrainingOutput(ModelOutput):
45
+ r"""
46
+ loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
47
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
48
+ paper](https://huggingface.co/papers/2006.11477).
49
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
50
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
51
+ projected quantized states.
52
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
53
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
54
+ target vectors for contrastive loss.
55
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
56
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
57
+ contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
58
+ The contrastive loss (L_m) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
59
+ diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
60
+ The diversity loss (L_d) as stated in the [official paper](https://huggingface.co/papers/2006.11477).
61
+ """
62
+
63
+ loss: torch.FloatTensor | None = None
64
+ projected_states: torch.FloatTensor | None = None
65
+ projected_quantized_states: torch.FloatTensor | None = None
66
+ codevector_perplexity: torch.FloatTensor | None = None
67
+ hidden_states: tuple[torch.FloatTensor] | None = None
68
+ attentions: tuple[torch.FloatTensor] | None = None
69
+ contrastive_loss: torch.FloatTensor | None = None
70
+ diversity_loss: torch.FloatTensor | None = None
71
+
72
+
73
+ class Wav2Vec2ConformerPositionalConvEmbedding(Wav2Vec2PositionalConvEmbedding):
74
+ pass
75
+
76
+
77
+ class Wav2Vec2ConformerRotaryPositionalEmbedding(nn.Module):
78
+ """Rotary positional embedding
79
+ Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://huggingface.co/papers/2104.09864
80
+ """
81
+
82
+ def __init__(self, config):
83
+ super().__init__()
84
+ dim = config.hidden_size // config.num_attention_heads
85
+ base = config.rotary_embedding_base
86
+
87
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
88
+ self.register_buffer("inv_freq", inv_freq)
89
+ self.cached_sequence_length = None
90
+ self.cached_rotary_positional_embedding = None
91
+
92
+ def forward(self, hidden_states):
93
+ sequence_length = hidden_states.shape[1]
94
+
95
+ if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
96
+ return self.cached_rotary_positional_embedding
97
+
98
+ self.cached_sequence_length = sequence_length
99
+ # Embeddings are computed in the dtype of the inv_freq constant
100
+ time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)
101
+ freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
102
+ embeddings = torch.cat((freqs, freqs), dim=-1)
103
+
104
+ cos_embeddings = embeddings.cos()[:, None, None, :]
105
+ sin_embeddings = embeddings.sin()[:, None, None, :]
106
+ # Computed embeddings are cast to the dtype of the hidden state inputs
107
+ self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings]).type_as(hidden_states)
108
+ return self.cached_rotary_positional_embedding
109
+
110
+
111
+ class Wav2Vec2ConformerRelPositionalEmbedding(nn.Module):
112
+ """Relative positional encoding module."""
113
+
114
+ def __init__(self, config):
115
+ super().__init__()
116
+ self.max_len = config.max_source_positions
117
+ self.d_model = config.hidden_size
118
+ self.register_buffer("pe", self.extend_pe(torch.tensor(0.0).expand(1, self.max_len)), persistent=False)
119
+
120
+ def extend_pe(self, x, pe=None):
121
+ # Reset the positional encodings
122
+ if pe is not None:
123
+ # self.pe contains both positive and negative parts
124
+ # the length of self.pe is 2 * input_len - 1
125
+ if pe.size(1) >= x.size(1) * 2 - 1:
126
+ if pe.dtype != x.dtype or pe.device != x.device:
127
+ pe = pe.to(dtype=x.dtype, device=x.device)
128
+ return pe
129
+ # Suppose `i` is the position of query vector and `j` is the
130
+ # position of key vector. We use positive relative positions when keys
131
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
132
+ pe_positive = torch.zeros(x.size(1), self.d_model)
133
+ pe_negative = torch.zeros(x.size(1), self.d_model)
134
+ position = torch.arange(0, x.size(1), dtype=torch.int64).float().unsqueeze(1)
135
+ div_term = torch.exp(
136
+ torch.arange(0, self.d_model, 2, dtype=torch.int64).float() * -(math.log(10000.0) / self.d_model)
137
+ )
138
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
139
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
140
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
141
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
142
+
143
+ # Reverse the order of positive indices and concat both positive and
144
+ # negative indices. This is used to support the shifting trick
145
+ # as in https://huggingface.co/papers/1901.02860
146
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
147
+ pe_negative = pe_negative[1:].unsqueeze(0)
148
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
149
+ return pe.to(device=x.device, dtype=x.dtype)
150
+
151
+ def forward(self, hidden_states: torch.Tensor):
152
+ self.pe = self.extend_pe(hidden_states, self.pe)
153
+ start_idx = self.pe.size(1) // 2 - hidden_states.size(1) + 1
154
+ end_idx = self.pe.size(1) // 2 + hidden_states.size(1)
155
+ relative_position_embeddings = self.pe[:, start_idx:end_idx]
156
+
157
+ return relative_position_embeddings
158
+
159
+
160
+ class Wav2Vec2ConformerFeatureEncoder(Wav2Vec2FeatureEncoder):
161
+ pass
162
+
163
+
164
+ class Wav2Vec2ConformerFeatureProjection(Wav2Vec2FeatureProjection):
165
+ pass
166
+
167
+
168
+ class Wav2Vec2ConformerFeedForward(Wav2Vec2FeedForward):
169
+ pass
170
+
171
+
172
+ class Wav2Vec2ConformerConvolutionModule(nn.Module):
173
+ """Convolution block used in the conformer block"""
174
+
175
+ def __init__(self, config):
176
+ super().__init__()
177
+ if (config.conv_depthwise_kernel_size - 1) % 2 == 1:
178
+ raise ValueError("`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding")
179
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
180
+ self.pointwise_conv1 = nn.Conv1d(
181
+ config.hidden_size,
182
+ 2 * config.hidden_size,
183
+ kernel_size=1,
184
+ stride=1,
185
+ padding=0,
186
+ bias=False,
187
+ )
188
+ self.glu = nn.GLU(dim=1)
189
+ self.depthwise_conv = nn.Conv1d(
190
+ config.hidden_size,
191
+ config.hidden_size,
192
+ config.conv_depthwise_kernel_size,
193
+ stride=1,
194
+ padding=(config.conv_depthwise_kernel_size - 1) // 2,
195
+ groups=config.hidden_size,
196
+ bias=False,
197
+ )
198
+ self.batch_norm = nn.BatchNorm1d(config.hidden_size)
199
+ self.activation = ACT2FN[config.hidden_act]
200
+ self.pointwise_conv2 = nn.Conv1d(
201
+ config.hidden_size,
202
+ config.hidden_size,
203
+ kernel_size=1,
204
+ stride=1,
205
+ padding=0,
206
+ bias=False,
207
+ )
208
+ self.dropout = nn.Dropout(config.conformer_conv_dropout)
209
+
210
+ def forward(self, hidden_states):
211
+ hidden_states = self.layer_norm(hidden_states)
212
+ # exchange the temporal dimension and the feature dimension
213
+ hidden_states = hidden_states.transpose(1, 2)
214
+
215
+ # GLU mechanism
216
+ # => (batch, 2*channel, dim)
217
+ hidden_states = self.pointwise_conv1(hidden_states)
218
+ # => (batch, channel, dim)
219
+ hidden_states = self.glu(hidden_states)
220
+
221
+ # 1D Depthwise Conv
222
+ hidden_states = self.depthwise_conv(hidden_states)
223
+ hidden_states = self.batch_norm(hidden_states)
224
+ hidden_states = self.activation(hidden_states)
225
+
226
+ hidden_states = self.pointwise_conv2(hidden_states)
227
+ hidden_states = self.dropout(hidden_states)
228
+ hidden_states = hidden_states.transpose(1, 2)
229
+ return hidden_states
230
+
231
+
232
+ class Wav2Vec2ConformerSelfAttention(nn.Module):
233
+ """Construct an Wav2Vec2ConformerSelfAttention object.
234
+ Can be enhanced with rotary or relative position embeddings.
235
+ """
236
+
237
+ def __init__(self, config):
238
+ super().__init__()
239
+
240
+ self.head_size = config.hidden_size // config.num_attention_heads
241
+ self.num_heads = config.num_attention_heads
242
+ self.position_embeddings_type = config.position_embeddings_type
243
+
244
+ self.linear_q = nn.Linear(config.hidden_size, config.hidden_size)
245
+ self.linear_k = nn.Linear(config.hidden_size, config.hidden_size)
246
+ self.linear_v = nn.Linear(config.hidden_size, config.hidden_size)
247
+ self.linear_out = nn.Linear(config.hidden_size, config.hidden_size)
248
+
249
+ self.dropout = nn.Dropout(p=config.attention_dropout)
250
+
251
+ if self.position_embeddings_type == "relative":
252
+ # linear transformation for positional encoding
253
+ self.linear_pos = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
254
+ # these two learnable bias are used in matrix c and matrix d
255
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
256
+ self.pos_bias_u = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
257
+ self.pos_bias_v = nn.Parameter(torch.zeros(self.num_heads, self.head_size))
258
+
259
+ def forward(
260
+ self,
261
+ hidden_states: torch.Tensor,
262
+ attention_mask: torch.Tensor | None = None,
263
+ relative_position_embeddings: torch.Tensor | None = None,
264
+ output_attentions: bool = False,
265
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
266
+ # self-attention mechanism
267
+ batch_size, sequence_length, hidden_size = hidden_states.size()
268
+
269
+ # make sure query/key states can be != value states
270
+ query_key_states = hidden_states
271
+ value_states = hidden_states
272
+
273
+ if self.position_embeddings_type == "rotary":
274
+ if relative_position_embeddings is None:
275
+ raise ValueError(
276
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'"
277
+ )
278
+ query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)
279
+
280
+ # project query_key_states and value_states
281
+ query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
282
+ key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)
283
+ value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)
284
+
285
+ # => (batch, head, time1, d_k)
286
+ query = query.transpose(1, 2)
287
+ key = key.transpose(1, 2)
288
+ value = value.transpose(1, 2)
289
+
290
+ if self.position_embeddings_type == "relative":
291
+ if relative_position_embeddings is None:
292
+ raise ValueError(
293
+ "`relative_position_embeddings` has to be defined when `self.position_embeddings_type =="
294
+ " 'relative'"
295
+ )
296
+ # apply relative_position_embeddings to qk scores
297
+ # as proposed in Transformer_XL: https://huggingface.co/papers/1901.02860
298
+ scores = self._apply_relative_embeddings(
299
+ query=query, key=key, relative_position_embeddings=relative_position_embeddings
300
+ )
301
+ else:
302
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)
303
+
304
+ # apply attention_mask if necessary
305
+ if attention_mask is not None:
306
+ scores = scores + attention_mask
307
+
308
+ # => (batch, head, time1, time2)
309
+ probs = torch.softmax(scores, dim=-1)
310
+ probs = self.dropout(probs)
311
+
312
+ # => (batch, head, time1, d_k)
313
+ hidden_states = torch.matmul(probs, value)
314
+
315
+ # => (batch, time1, hidden_size)
316
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)
317
+ hidden_states = self.linear_out(hidden_states)
318
+
319
+ return hidden_states, probs
320
+
321
+ def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):
322
+ batch_size, sequence_length, hidden_size = hidden_states.size()
323
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)
324
+
325
+ cos = relative_position_embeddings[0, :sequence_length, ...]
326
+ sin = relative_position_embeddings[1, :sequence_length, ...]
327
+
328
+ # rotate hidden_states with rotary embeddings
329
+ hidden_states = hidden_states.transpose(0, 1)
330
+ rotated_states_begin = hidden_states[..., : self.head_size // 2]
331
+ rotated_states_end = hidden_states[..., self.head_size // 2 :]
332
+ rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)
333
+ hidden_states = (hidden_states * cos) + (rotated_states * sin)
334
+ hidden_states = hidden_states.transpose(0, 1)
335
+
336
+ hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)
337
+
338
+ return hidden_states
339
+
340
+ def _apply_relative_embeddings(self, query, key, relative_position_embeddings):
341
+ # 1. project positional embeddings
342
+ # => (batch, head, 2*time1-1, d_k)
343
+ proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)
344
+ proj_relative_position_embeddings = proj_relative_position_embeddings.view(
345
+ relative_position_embeddings.size(0), -1, self.num_heads, self.head_size
346
+ )
347
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)
348
+ proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)
349
+
350
+ # 2. Add bias to query
351
+ # => (batch, head, time1, d_k)
352
+ query = query.transpose(1, 2)
353
+ q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)
354
+ q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)
355
+
356
+ # 3. attention score: first compute matrix a and matrix c
357
+ # as described in https://huggingface.co/papers/1901.02860 Section 3.3
358
+ # => (batch, head, time1, time2)
359
+ scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))
360
+
361
+ # 4. then compute matrix b and matrix d
362
+ # => (batch, head, time1, 2*time1-1)
363
+ scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)
364
+
365
+ # 5. shift matrix b and matrix d
366
+ zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)
367
+ scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)
368
+ scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])
369
+ scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)
370
+ scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)
371
+ scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]
372
+
373
+ # 6. sum matrices
374
+ # => (batch, head, time1, time2)
375
+ scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)
376
+
377
+ return scores
378
+
379
+
380
+ class Wav2Vec2ConformerEncoderLayer(GradientCheckpointingLayer):
381
+ """Conformer block based on https://huggingface.co/papers/2005.08100."""
382
+
383
+ def __init__(self, config):
384
+ super().__init__()
385
+ embed_dim = config.hidden_size
386
+ dropout = config.attention_dropout
387
+
388
+ # Feed-forward 1
389
+ self.ffn1_layer_norm = nn.LayerNorm(embed_dim)
390
+ self.ffn1 = Wav2Vec2ConformerFeedForward(config)
391
+
392
+ # Self-Attention
393
+ self.self_attn_layer_norm = nn.LayerNorm(embed_dim)
394
+ self.self_attn_dropout = nn.Dropout(dropout)
395
+ self.self_attn = Wav2Vec2ConformerSelfAttention(config)
396
+
397
+ # Conformer Convolution
398
+ self.conv_module = Wav2Vec2ConformerConvolutionModule(config)
399
+
400
+ # Feed-forward 2
401
+ self.ffn2_layer_norm = nn.LayerNorm(embed_dim)
402
+ self.ffn2 = Wav2Vec2ConformerFeedForward(config)
403
+ self.final_layer_norm = nn.LayerNorm(embed_dim)
404
+
405
+ def forward(
406
+ self,
407
+ hidden_states,
408
+ attention_mask: torch.Tensor | None = None,
409
+ relative_position_embeddings: torch.Tensor | None = None,
410
+ output_attentions: bool = False,
411
+ ):
412
+ # 1. Feed-Forward 1 layer
413
+ residual = hidden_states
414
+ hidden_states = self.ffn1_layer_norm(hidden_states)
415
+ hidden_states = self.ffn1(hidden_states)
416
+ hidden_states = hidden_states * 0.5 + residual
417
+ residual = hidden_states
418
+
419
+ # 2. Self-Attention layer
420
+ hidden_states = self.self_attn_layer_norm(hidden_states)
421
+ hidden_states, attn_weigts = self.self_attn(
422
+ hidden_states=hidden_states,
423
+ attention_mask=attention_mask,
424
+ relative_position_embeddings=relative_position_embeddings,
425
+ output_attentions=output_attentions,
426
+ )
427
+ hidden_states = self.self_attn_dropout(hidden_states)
428
+ hidden_states = hidden_states + residual
429
+
430
+ # 3. Convolutional Layer
431
+ residual = hidden_states
432
+ hidden_states = self.conv_module(hidden_states)
433
+ hidden_states = residual + hidden_states
434
+
435
+ # 4. Feed-Forward 2 Layer
436
+ residual = hidden_states
437
+ hidden_states = self.ffn2_layer_norm(hidden_states)
438
+ hidden_states = self.ffn2(hidden_states)
439
+ hidden_states = hidden_states * 0.5 + residual
440
+ hidden_states = self.final_layer_norm(hidden_states)
441
+
442
+ return hidden_states, attn_weigts
443
+
444
+
445
+ class Wav2Vec2ConformerEncoder(nn.Module):
446
+ def __init__(self, config):
447
+ super().__init__()
448
+ self.config = config
449
+
450
+ if config.position_embeddings_type == "relative":
451
+ self.embed_positions = Wav2Vec2ConformerRelPositionalEmbedding(config)
452
+ elif config.position_embeddings_type == "rotary":
453
+ self.embed_positions = Wav2Vec2ConformerRotaryPositionalEmbedding(config)
454
+ else:
455
+ self.embed_positions = None
456
+
457
+ self.pos_conv_embed = Wav2Vec2ConformerPositionalConvEmbedding(config)
458
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
459
+ self.dropout = nn.Dropout(config.hidden_dropout)
460
+ self.layers = nn.ModuleList([Wav2Vec2ConformerEncoderLayer(config) for _ in range(config.num_hidden_layers)])
461
+ self.gradient_checkpointing = False
462
+
463
+ def forward(
464
+ self,
465
+ hidden_states,
466
+ attention_mask=None,
467
+ output_attentions=False,
468
+ output_hidden_states=False,
469
+ return_dict=True,
470
+ ):
471
+ all_hidden_states = () if output_hidden_states else None
472
+ all_self_attentions = () if output_attentions else None
473
+
474
+ if attention_mask is not None:
475
+ # make sure padded tokens output 0
476
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
477
+ hidden_states[~expand_attention_mask] = 0.0
478
+
479
+ # extend attention_mask
480
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
481
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
482
+ attention_mask = attention_mask.expand(
483
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
484
+ )
485
+
486
+ hidden_states = self.dropout(hidden_states)
487
+
488
+ if self.embed_positions is not None:
489
+ relative_position_embeddings = self.embed_positions(hidden_states)
490
+ else:
491
+ relative_position_embeddings = None
492
+
493
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
494
+
495
+ for i, layer in enumerate(self.layers):
496
+ if output_hidden_states:
497
+ all_hidden_states = all_hidden_states + (hidden_states,)
498
+
499
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
500
+ dropout_probability = torch.rand([])
501
+
502
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
503
+ if not skip_the_layer or synced_gpus:
504
+ # under fsdp or deepspeed zero3 all gpus must run in sync
505
+ layer_outputs = layer(
506
+ hidden_states,
507
+ attention_mask=attention_mask,
508
+ relative_position_embeddings=relative_position_embeddings,
509
+ output_attentions=output_attentions,
510
+ )
511
+ hidden_states = layer_outputs[0]
512
+
513
+ if skip_the_layer:
514
+ layer_outputs = (None, None)
515
+
516
+ if output_attentions:
517
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
518
+
519
+ hidden_states = self.layer_norm(hidden_states)
520
+ if output_hidden_states:
521
+ all_hidden_states = all_hidden_states + (hidden_states,)
522
+
523
+ if not return_dict:
524
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
525
+ return BaseModelOutput(
526
+ last_hidden_state=hidden_states,
527
+ hidden_states=all_hidden_states,
528
+ attentions=all_self_attentions,
529
+ )
530
+
531
+
532
+ class Wav2Vec2ConformerGumbelVectorQuantizer(Wav2Vec2GumbelVectorQuantizer):
533
+ pass
534
+
535
+
536
+ class Wav2Vec2ConformerAdapter(Wav2Vec2Adapter):
537
+ pass
538
+
539
+
540
+ class Wav2Vec2ConformerAdapterLayer(Wav2Vec2AdapterLayer):
541
+ pass
542
+
543
+
544
+ @auto_docstring
545
+ class Wav2Vec2ConformerPreTrainedModel(PreTrainedModel):
546
+ config: Wav2Vec2ConformerConfig
547
+ base_model_prefix = "wav2vec2_conformer"
548
+ main_input_name = "input_values"
549
+ input_modalities = "audio"
550
+ supports_gradient_checkpointing = True
551
+
552
+ @torch.no_grad()
553
+ def _init_weights(self, module):
554
+ """Initialize the weights"""
555
+ # Wav2Vec2ForPreTraining last 2 linear layers need standard Linear init.
556
+ if isinstance(module, Wav2Vec2ConformerForPreTraining):
557
+ module.project_hid.reset_parameters()
558
+ module.project_q.reset_parameters()
559
+ # gumbel softmax requires special init
560
+ elif isinstance(module, Wav2Vec2ConformerGumbelVectorQuantizer):
561
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
562
+ init.zeros_(module.weight_proj.bias)
563
+ init.uniform_(module.codevectors)
564
+ elif isinstance(module, Wav2Vec2ConformerSelfAttention):
565
+ if hasattr(module, "pos_bias_u"):
566
+ init.xavier_uniform_(module.pos_bias_u)
567
+ if hasattr(module, "pos_bias_v"):
568
+ init.xavier_uniform_(module.pos_bias_v)
569
+ elif isinstance(module, Wav2Vec2ConformerPositionalConvEmbedding):
570
+ init.normal_(
571
+ module.conv.weight,
572
+ mean=0,
573
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
574
+ )
575
+ init.constant_(module.conv.bias, 0)
576
+ elif isinstance(module, Wav2Vec2ConformerFeatureProjection):
577
+ k = math.sqrt(1 / module.projection.in_features)
578
+ init.uniform_(module.projection.weight, a=-k, b=k)
579
+ init.uniform_(module.projection.bias, a=-k, b=k)
580
+ elif isinstance(module, nn.Linear):
581
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
582
+
583
+ if module.bias is not None:
584
+ init.zeros_(module.bias)
585
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm1d)):
586
+ init.zeros_(module.bias)
587
+ init.ones_(module.weight)
588
+ if getattr(module, "running_mean", None) is not None:
589
+ init.zeros_(module.running_mean)
590
+ init.ones_(module.running_var)
591
+ init.zeros_(module.num_batches_tracked)
592
+ elif isinstance(module, nn.Conv1d):
593
+ init.kaiming_normal_(module.weight)
594
+
595
+ if module.bias is not None:
596
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
597
+ init.uniform_(module.bias, a=-k, b=k)
598
+ elif isinstance(module, Wav2Vec2ConformerRotaryPositionalEmbedding):
599
+ dim = self.config.hidden_size // self.config.num_attention_heads
600
+ base = self.config.rotary_embedding_base
601
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
602
+ init.copy_(module.inv_freq, inv_freq)
603
+ elif isinstance(module, Wav2Vec2ConformerRelPositionalEmbedding):
604
+ init.copy_(module.pe, module.extend_pe(torch.tensor(0.0).expand(1, module.max_len)))
605
+
606
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
607
+ """
608
+ Computes the output length of the convolutional layers
609
+ """
610
+
611
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
612
+
613
+ def _conv_out_length(input_length, kernel_size, stride):
614
+ # 1D convolutional layer output length formula taken
615
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
616
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
617
+
618
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
619
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
620
+
621
+ if add_adapter:
622
+ for _ in range(self.config.num_adapter_layers):
623
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
624
+
625
+ return input_lengths
626
+
627
+ def _get_feature_vector_attention_mask(
628
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
629
+ ):
630
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
631
+ # on inference mode.
632
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
633
+
634
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
635
+ output_lengths = output_lengths.to(torch.long)
636
+
637
+ batch_size = attention_mask.shape[0]
638
+
639
+ attention_mask = torch.zeros(
640
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
641
+ )
642
+ # these two operations makes sure that all values before the output lengths idxs are attended to
643
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
644
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
645
+ return attention_mask
646
+
647
+
648
+ WAV2VEC2_CONFORMER_START_DOCSTRING = None # will be automatically redefined
649
+
650
+
651
+ Wav2Vec2ConformerBaseModelOutput = Wav2Vec2BaseModelOutput
652
+
653
+
654
+ class Wav2Vec2ConformerModel(Wav2Vec2ConformerPreTrainedModel, Wav2Vec2Model):
655
+ def __init__(self, config: Wav2Vec2ConformerConfig):
656
+ Wav2Vec2ConformerPreTrainedModel.__init__(self, config)
657
+ self.config = config
658
+ self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config)
659
+ self.feature_projection = Wav2Vec2ConformerFeatureProjection(config)
660
+
661
+ # model only needs masking vector if mask prob is > 0.0
662
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
663
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
664
+
665
+ self.encoder = Wav2Vec2ConformerEncoder(config)
666
+
667
+ self.adapter = Wav2Vec2ConformerAdapter(config) if config.add_adapter else None
668
+
669
+ # Initialize weights and apply final processing
670
+ self.post_init()
671
+
672
+
673
+ class Wav2Vec2ConformerForPreTraining(Wav2Vec2ForPreTraining):
674
+ def __init__(self, config: Wav2Vec2ConformerConfig):
675
+ super().__init__(config)
676
+
677
+
678
+ class Wav2Vec2ConformerForCTC(Wav2Vec2ForCTC):
679
+ def __init__(self, config, target_lang: str | None = None):
680
+ r"""
681
+ target_lang (`str`, *optional*):
682
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
683
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
684
+ default.
685
+ """
686
+ super().__init__(config)
687
+
688
+ def tie_weights(self):
689
+ raise AttributeError("Not needed for Wav2Vec2Conformer")
690
+
691
+ def freeze_base_model(self):
692
+ raise AttributeError("Not needed for Wav2Vec2Conformer")
693
+
694
+
695
+ class Wav2Vec2ConformerForSequenceClassification(Wav2Vec2ForSequenceClassification):
696
+ def __init__(self, config):
697
+ super().__init__(config)
698
+
699
+
700
+ class Wav2Vec2ConformerForAudioFrameClassification(Wav2Vec2ForAudioFrameClassification):
701
+ def __init__(self, config):
702
+ super().__init__(config)
703
+
704
+
705
+ class Wav2Vec2ConformerForXVector(Wav2Vec2ForXVector):
706
+ def __init__(self, config):
707
+ super().__init__(config)
708
+
709
+
710
+ __all__ = [
711
+ "Wav2Vec2ConformerForAudioFrameClassification",
712
+ "Wav2Vec2ConformerForCTC",
713
+ "Wav2Vec2ConformerForPreTraining",
714
+ "Wav2Vec2ConformerForSequenceClassification",
715
+ "Wav2Vec2ConformerForXVector",
716
+ "Wav2Vec2ConformerModel",
717
+ "Wav2Vec2ConformerPreTrainedModel",
718
+ ]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .tokenization_wav2vec2_phoneme import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (655 Bytes). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__pycache__/tokenization_wav2vec2_phoneme.cpython-312.pyc ADDED
Binary file (26.1 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization class for Wav2Vec2Phoneme."""
15
+
16
+ import json
17
+ import os
18
+ from dataclasses import dataclass
19
+ from itertools import groupby
20
+ from typing import TYPE_CHECKING, Any, Union
21
+
22
+ import numpy as np
23
+
24
+ from ...tokenization_python import PreTrainedTokenizer
25
+ from ...tokenization_utils_base import AddedToken
26
+ from ...utils import (
27
+ ModelOutput,
28
+ logging,
29
+ requires_backends,
30
+ to_py_obj,
31
+ )
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ import torch
39
+
40
+
41
+ VOCAB_FILES_NAMES = {
42
+ "vocab_file": "vocab.json",
43
+ "tokenizer_config_file": "tokenizer_config.json",
44
+ }
45
+
46
+
47
+ # Wav2Vec2Phoneme has no max input length
48
+
49
+
50
+ ListOfDict = list[dict[str, int | str]]
51
+
52
+
53
+ @dataclass
54
+ class Wav2Vec2PhonemeCTCTokenizerOutput(ModelOutput):
55
+ """
56
+ Output type of [` Wav2Vec2PhonemeCTCTokenizer`], with transcription.
57
+
58
+ Args:
59
+ text (list of `str` or `str`):
60
+ Decoded logits in text from. Usually the speech transcription.
61
+ char_offsets (list of `list[dict[str, Union[int, str]]]` or `list[dict[str, Union[int, str]]]`):
62
+ Offsets of the decoded characters. In combination with sampling rate and model downsampling rate char
63
+ offsets can be used to compute time stamps for each character. Total logit score of the beam associated with
64
+ produced text.
65
+ """
66
+
67
+ text: list[str] | str
68
+ char_offsets: list[ListOfDict] | ListOfDict = None
69
+
70
+
71
+ class Wav2Vec2PhonemeCTCTokenizer(PreTrainedTokenizer):
72
+ """
73
+ Constructs a Wav2Vec2PhonemeCTC tokenizer.
74
+
75
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
76
+ the superclass for more information regarding such methods.
77
+
78
+ Args:
79
+ vocab_file (`str`):
80
+ File containing the vocabulary.
81
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
82
+ The beginning of sentence token.
83
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
84
+ The end of sentence token.
85
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
86
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
87
+ token instead.
88
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
89
+ The token used for padding, for example when batching sequences of different lengths.
90
+ do_phonemize (`bool`, *optional*, defaults to `True`):
91
+ Whether the tokenizer should phonetize the input or not. Only if a sequence of phonemes is passed to the
92
+ tokenizer, `do_phonemize` should be set to `False`.
93
+ phonemizer_lang (`str`, *optional*, defaults to `"en-us"`):
94
+ The language of the phoneme set to which the tokenizer should phonetize the input text to.
95
+ phonemizer_backend (`str`, *optional*. defaults to `"espeak"`):
96
+ The backend phonetization library that shall be used by the phonemizer library. Defaults to `espeak-ng`.
97
+ See the [phonemizer package](https://github.com/bootphon/phonemizer#readme). for more information.
98
+
99
+ **kwargs
100
+ Additional keyword arguments passed along to [`PreTrainedTokenizer`]
101
+ """
102
+
103
+ vocab_files_names = VOCAB_FILES_NAMES
104
+ model_input_names = ["input_ids", "attention_mask"]
105
+
106
+ def __init__(
107
+ self,
108
+ vocab_file,
109
+ bos_token="<s>",
110
+ eos_token="</s>",
111
+ unk_token="<unk>",
112
+ pad_token="<pad>",
113
+ phone_delimiter_token=" ",
114
+ word_delimiter_token=None,
115
+ do_phonemize=True,
116
+ phonemizer_lang="en-us",
117
+ phonemizer_backend="espeak",
118
+ **kwargs,
119
+ ):
120
+ # Recover delimiters from V5 `*_token` auto-promotion; they aren't vocab tokens.
121
+ model_specific = kwargs.get("model_specific_special_tokens") or {}
122
+ if "word_delimiter_token" in model_specific:
123
+ word_delimiter_token = model_specific.pop("word_delimiter_token")
124
+ if "phone_delimiter_token" in model_specific:
125
+ phone_delimiter_token = model_specific.pop("phone_delimiter_token")
126
+ if not model_specific:
127
+ kwargs.pop("model_specific_special_tokens", None)
128
+
129
+ self._word_delimiter_token = word_delimiter_token
130
+ self._phone_delimiter_token = phone_delimiter_token
131
+ self.do_phonemize = do_phonemize
132
+ self.phonemizer_lang = phonemizer_lang
133
+ self.phonemizer_backend = phonemizer_backend
134
+
135
+ if do_phonemize:
136
+ self.init_backend(self.phonemizer_lang)
137
+
138
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
139
+ self.encoder = json.load(vocab_handle)
140
+ self.decoder = {v: k for k, v in self.encoder.items()}
141
+
142
+ super().__init__(
143
+ unk_token=unk_token,
144
+ bos_token=bos_token,
145
+ eos_token=eos_token,
146
+ pad_token=pad_token,
147
+ do_phonemize=do_phonemize,
148
+ phonemizer_lang=phonemizer_lang,
149
+ phonemizer_backend=phonemizer_backend,
150
+ **kwargs,
151
+ )
152
+ self.init_kwargs["word_delimiter_token"] = word_delimiter_token
153
+ self.init_kwargs["phone_delimiter_token"] = phone_delimiter_token
154
+
155
+ @property
156
+ def vocab_size(self) -> int:
157
+ return len(self.decoder)
158
+
159
+ def get_vocab(self) -> dict:
160
+ vocab = dict(self.encoder.copy())
161
+ vocab.update(self.added_tokens_encoder)
162
+ return vocab
163
+
164
+ def _add_tokens(self, new_tokens: list[str] | list[AddedToken], special_tokens: bool = False) -> int:
165
+ # Overwritten to never strip!
166
+ to_add = []
167
+ for token in new_tokens:
168
+ if isinstance(token, str):
169
+ to_add.append(AddedToken(token, rstrip=False, lstrip=False, normalized=True, special=special_tokens))
170
+ else:
171
+ to_add.append(token)
172
+
173
+ return super()._add_tokens(to_add, special_tokens)
174
+
175
+ def init_backend(self, phonemizer_lang: str):
176
+ """
177
+ Initializes the backend.
178
+
179
+ Args:
180
+ phonemizer_lang (`str`): The language to be used.
181
+ """
182
+ requires_backends(self, "phonemizer")
183
+ from phonemizer.backend import BACKENDS
184
+
185
+ self._phonemizer_backend = BACKENDS[self.phonemizer_backend](phonemizer_lang, language_switch="remove-flags")
186
+
187
+ def prepare_for_tokenization(
188
+ self,
189
+ text: str,
190
+ is_split_into_words: bool = False,
191
+ phonemizer_lang: str | None = None,
192
+ do_phonemize: bool | None = None,
193
+ **kwargs,
194
+ ) -> tuple[str, dict[str, Any]]:
195
+ """
196
+ Performs any necessary transformations before tokenization.
197
+
198
+ This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
199
+ `kwargs` at the end of the encoding process to be sure all the arguments have been used.
200
+
201
+ Args:
202
+ text (`str`):
203
+ The text to prepare.
204
+ is_split_into_words (`bool`, *optional*, defaults to `False`):
205
+ Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
206
+ tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
207
+ which it will tokenize. This is useful for NER or token classification.
208
+ phonemizer_lang (`str`, *optional*):
209
+ The language of the phoneme set to which the tokenizer should phonetize the input text to.
210
+ do_phonemize (`bool`, *optional*):
211
+ Whether the tokenizer should phonetize the input text or not. Only if a sequence of phonemes is passed
212
+ to the tokenizer, `do_phonemize` should be set to `False`.
213
+
214
+
215
+ Returns:
216
+ `tuple[str, dict[str, Any]]`: The prepared text and the unused kwargs.
217
+ """
218
+ if is_split_into_words:
219
+ text = " " + text
220
+
221
+ # set whether tokenizer should phonemize or not
222
+ if do_phonemize is not None:
223
+ self.do_phonemize = do_phonemize
224
+
225
+ # set the correct phonemizer language
226
+ if phonemizer_lang is not None:
227
+ self.phonemizer_lang = phonemizer_lang
228
+ self.init_backend(phonemizer_lang)
229
+
230
+ return (text, {})
231
+
232
+ def _tokenize(self, text, **kwargs):
233
+ """
234
+ Converts a string into a sequence of tokens (string), using the tokenizer.
235
+ """
236
+
237
+ # make sure whitespace is stripped to prevent <unk>
238
+ text = text.strip()
239
+
240
+ # phonemize
241
+ if self.do_phonemize:
242
+ text = text.lower()
243
+
244
+ # create list of phonemes
245
+ text = self.phonemize(text, self.phonemizer_lang)
246
+
247
+ # make sure ' ' is between phonemes
248
+ tokens = text.split(" ")
249
+
250
+ tokens = list(filter(lambda p: p.strip() != "", tokens))
251
+ return tokens
252
+
253
+ def phonemize(self, text: str, phonemizer_lang: str | None = None) -> str:
254
+ from phonemizer.separator import Separator
255
+
256
+ word_delimiter = self.word_delimiter_token + " " if self.word_delimiter_token is not None else ""
257
+ if phonemizer_lang is not None and phonemizer_lang != self.phonemizer_lang:
258
+ self.init_backend(phonemizer_lang)
259
+ else:
260
+ phonemizer_lang = self.phonemizer_lang
261
+
262
+ separator = Separator(phone=self.phone_delimiter_token, word=word_delimiter, syllable="")
263
+ phonemes = self._phonemizer_backend.phonemize(
264
+ [text],
265
+ separator=separator,
266
+ )
267
+ phonemes = phonemes[0].strip()
268
+
269
+ return phonemes
270
+
271
+ @property
272
+ def word_delimiter_token(self) -> str:
273
+ """
274
+ `str`: Word delimiter token. Log an error if used while not having been set.
275
+ """
276
+ if self._word_delimiter_token is None:
277
+ if self.verbose:
278
+ logger.error("Using word_delimiter_token, but it is not set yet.")
279
+ return None
280
+ return str(self._word_delimiter_token)
281
+
282
+ @property
283
+ def word_delimiter_token_id(self) -> int | None:
284
+ """
285
+ `Optional[int]`: Id of the word_delimiter_token in the vocabulary. Returns `None` if the token has not been
286
+ set.
287
+ """
288
+ if self._word_delimiter_token is None:
289
+ return None
290
+ return self.convert_tokens_to_ids(self.word_delimiter_token)
291
+
292
+ @word_delimiter_token.setter
293
+ def word_delimiter_token(self, value):
294
+ self._word_delimiter_token = value
295
+
296
+ @word_delimiter_token_id.setter
297
+ def word_delimiter_token_id(self, value):
298
+ self._word_delimiter_token = self.convert_tokens_to_ids(value)
299
+
300
+ @property
301
+ def phone_delimiter_token(self) -> str:
302
+ """
303
+ `str`: Word delimiter token. Log an error if used while not having been set.
304
+ """
305
+ if self._phone_delimiter_token is None:
306
+ if self.verbose:
307
+ logger.error("Using phone_delimiter_token, but it is not set yet.")
308
+ return None
309
+ return str(self._phone_delimiter_token)
310
+
311
+ @property
312
+ def phone_delimiter_token_id(self) -> int | None:
313
+ """
314
+ `Optional[int]`: Id of the phone_delimiter_token in the vocabulary. Returns `None` if the token has not been
315
+ set.
316
+ """
317
+ if self._phone_delimiter_token is None:
318
+ return None
319
+ return self.convert_tokens_to_ids(self.phone_delimiter_token)
320
+
321
+ @phone_delimiter_token.setter
322
+ def phone_delimiter_token(self, value):
323
+ self._phone_delimiter_token = value
324
+
325
+ @phone_delimiter_token_id.setter
326
+ def phone_delimiter_token_id(self, value):
327
+ self._phone_delimiter_token = self.convert_tokens_to_ids(value)
328
+
329
+ def _convert_token_to_id(self, token: str) -> int:
330
+ """Converts a token (str) in an index (integer) using the vocab."""
331
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
332
+
333
+ def _convert_id_to_token(self, index: int) -> str:
334
+ """Converts an index (integer) in a token (str) using the vocab."""
335
+ result = self.decoder.get(index, self.unk_token)
336
+ return result
337
+
338
+ def convert_tokens_to_string(
339
+ self,
340
+ tokens: list[str],
341
+ group_tokens: bool = True,
342
+ spaces_between_special_tokens: bool = False,
343
+ filter_word_delimiter_token: bool = True,
344
+ output_char_offsets: bool = False,
345
+ ) -> str:
346
+ """
347
+ Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
348
+ """
349
+ # group same tokens into non-repeating tokens in CTC style decoding
350
+ if group_tokens:
351
+ chars, char_repetitions = zip(*((token, len(list(group_iter))) for token, group_iter in groupby(tokens)))
352
+ else:
353
+ chars = tokens
354
+ char_repetitions = len(tokens) * [1]
355
+
356
+ # filter self.pad_token which is used as CTC-blank token
357
+ processed_chars = list(filter(lambda char: char != self.pad_token, chars))
358
+
359
+ # also filter self.word_delimiter_token if not not
360
+ if filter_word_delimiter_token and self.word_delimiter_token is not None:
361
+ processed_chars = list(filter(lambda token: token != self.word_delimiter_token, processed_chars))
362
+
363
+ # retrieve offsets
364
+ char_offsets = None
365
+ if output_char_offsets:
366
+ word_delimiter_token_for_offsets = (
367
+ self.word_delimiter_token if filter_word_delimiter_token is True else None
368
+ )
369
+ char_offsets = self._compute_offsets(
370
+ char_repetitions, chars, self.pad_token, word_delimiter_token=word_delimiter_token_for_offsets
371
+ )
372
+
373
+ if len(char_offsets) != len(processed_chars):
374
+ raise ValueError(
375
+ f"`char_offsets`: {char_offsets} and `processed_tokens`: {processed_chars}"
376
+ " have to be of the same length, but are: `len(offsets)`: "
377
+ f"{len(char_offsets)} and `len(processed_tokens)`: {len(processed_chars)}"
378
+ )
379
+
380
+ # set tokens to correct processed token
381
+ for i, char in enumerate(processed_chars):
382
+ char_offsets[i]["char"] = char
383
+
384
+ string = " ".join(processed_chars).strip()
385
+
386
+ return {"text": string, "char_offsets": char_offsets}
387
+
388
+ @staticmethod
389
+ def _compute_offsets(
390
+ char_repetitions: list[int], chars: list[str], ctc_token: int, word_delimiter_token: int | None = None
391
+ ) -> list[dict[str, str | int]]:
392
+ end_indices = np.asarray(char_repetitions).cumsum()
393
+ start_indices = np.concatenate(([0], end_indices[:-1]))
394
+
395
+ offsets = [
396
+ {"char": t, "start_offset": s, "end_offset": e} for t, s, e in zip(chars, start_indices, end_indices)
397
+ ]
398
+
399
+ # filter out CTC token
400
+ offsets = list(filter(lambda offsets: offsets["char"] != ctc_token, offsets))
401
+
402
+ # filter out word delimiter token if necessary
403
+ if word_delimiter_token is not None:
404
+ offsets = list(filter(lambda offsets: offsets["char"] != word_delimiter_token, offsets))
405
+
406
+ return offsets
407
+
408
+ def _decode(
409
+ self,
410
+ token_ids: list[int],
411
+ skip_special_tokens: bool = False,
412
+ clean_up_tokenization_spaces: bool | None = None,
413
+ group_tokens: bool = True,
414
+ filter_word_delimiter_token: bool = True,
415
+ spaces_between_special_tokens: bool = False,
416
+ output_char_offsets: bool = False,
417
+ ) -> str:
418
+ """
419
+ special _decode function is needed for Wav2Vec2PhonemeTokenizer because added tokens should be treated exactly
420
+ the same as tokens of the base vocabulary and therefore the function `convert_tokens_to_string` has to be
421
+ called on the whole token list and not individually on added tokens
422
+ """
423
+ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
424
+
425
+ result = []
426
+ for token in filtered_tokens:
427
+ if skip_special_tokens and token in self.all_special_ids:
428
+ continue
429
+ result.append(token)
430
+
431
+ string_output = self.convert_tokens_to_string(
432
+ result,
433
+ group_tokens=group_tokens,
434
+ spaces_between_special_tokens=spaces_between_special_tokens,
435
+ filter_word_delimiter_token=filter_word_delimiter_token,
436
+ output_char_offsets=output_char_offsets,
437
+ )
438
+
439
+ text = string_output["text"]
440
+
441
+ clean_up_tokenization_spaces = (
442
+ clean_up_tokenization_spaces
443
+ if clean_up_tokenization_spaces is not None
444
+ else self.clean_up_tokenization_spaces
445
+ )
446
+ if clean_up_tokenization_spaces:
447
+ text = self.clean_up_tokenization(text)
448
+
449
+ if output_char_offsets:
450
+ return Wav2Vec2PhonemeCTCTokenizerOutput(text=text, char_offsets=string_output["char_offsets"])
451
+ else:
452
+ return text
453
+
454
+ # overwritten from `tokenization_utils_base.py` because we need docs for `output_char_offsets` here
455
+ def decode(
456
+ self,
457
+ token_ids: Union[int, list[int], np.ndarray, "torch.Tensor"],
458
+ skip_special_tokens: bool = False,
459
+ clean_up_tokenization_spaces: bool | None = None,
460
+ output_char_offsets: bool = False,
461
+ **kwargs,
462
+ ) -> str:
463
+ """
464
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
465
+ tokens and clean up tokenization spaces.
466
+
467
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
468
+
469
+ Args:
470
+ token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
471
+ List of tokenized input ids. Can be obtained using the `__call__` method.
472
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
473
+ Whether or not to remove special tokens in the decoding.
474
+ clean_up_tokenization_spaces (`bool`, *optional*):
475
+ Whether or not to clean up the tokenization spaces.
476
+ output_char_offsets (`bool`, *optional*, defaults to `False`):
477
+ Whether or not to output character offsets. Character offsets can be used in combination with the
478
+ sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.
479
+
480
+ <Tip>
481
+
482
+ Please take a look at the Example of [`~models.wav2vec2.tokenization_wav2vec2.decode`] to better
483
+ understand how to make use of `output_word_offsets`.
484
+ [`~model.wav2vec2_phoneme.tokenization_wav2vec2_phoneme.batch_decode`] works the same way with
485
+ phonemes.
486
+
487
+ </Tip>
488
+
489
+ kwargs (additional keyword arguments, *optional*):
490
+ Will be passed to the underlying model specific decode method.
491
+
492
+ Returns:
493
+ `str` or [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]: The decoded
494
+ sentence. Will be a [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]
495
+ when `output_char_offsets == True`.
496
+ """
497
+ # Convert inputs to python lists
498
+ token_ids = to_py_obj(token_ids)
499
+
500
+ return self._decode(
501
+ token_ids=token_ids,
502
+ skip_special_tokens=skip_special_tokens,
503
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
504
+ output_char_offsets=output_char_offsets,
505
+ **kwargs,
506
+ )
507
+
508
+ # overwritten from `tokenization_utils_base.py` because tokenizer can output
509
+ # `ModelOutput` which should not be a list for batched output and because
510
+ # we need docs for `output_char_offsets` here
511
+ def batch_decode(
512
+ self,
513
+ sequences: Union[list[int], list[list[int]], np.ndarray, "torch.Tensor"],
514
+ skip_special_tokens: bool = False,
515
+ clean_up_tokenization_spaces: bool | None = None,
516
+ output_char_offsets: bool = False,
517
+ **kwargs,
518
+ ) -> list[str]:
519
+ """
520
+ Convert a list of lists of token ids into a list of strings by calling decode.
521
+
522
+ Args:
523
+ sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`):
524
+ List of tokenized input ids. Can be obtained using the `__call__` method.
525
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
526
+ Whether or not to remove special tokens in the decoding.
527
+ clean_up_tokenization_spaces (`bool`, *optional*):
528
+ Whether or not to clean up the tokenization spaces.
529
+ output_char_offsets (`bool`, *optional*, defaults to `False`):
530
+ Whether or not to output character offsets. Character offsets can be used in combination with the
531
+ sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.
532
+
533
+ <Tip>
534
+
535
+ Please take a look at the Example of [`~models.wav2vec2.tokenization_wav2vec2.decode`] to better
536
+ understand how to make use of `output_word_offsets`.
537
+ [`~model.wav2vec2_phoneme.tokenization_wav2vec2_phoneme.batch_decode`] works analogous with phonemes
538
+ and batched output.
539
+
540
+ </Tip>
541
+
542
+ kwargs (additional keyword arguments, *optional*):
543
+ Will be passed to the underlying model specific decode method.
544
+
545
+ Returns:
546
+ `list[str]` or [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]: The
547
+ decoded sentence. Will be a
548
+ [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`] when
549
+ `output_char_offsets == True`.
550
+ """
551
+ batch_decoded = [
552
+ self.decode(
553
+ seq,
554
+ skip_special_tokens=skip_special_tokens,
555
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
556
+ output_char_offsets=output_char_offsets,
557
+ **kwargs,
558
+ )
559
+ for seq in sequences
560
+ ]
561
+ if output_char_offsets:
562
+ # transform list of dicts to dict of lists
563
+ return Wav2Vec2PhonemeCTCTokenizerOutput({k: [d[k] for d in batch_decoded] for k in batch_decoded[0]})
564
+
565
+ return batch_decoded
566
+
567
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
568
+ if not os.path.isdir(save_directory):
569
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
570
+ return
571
+ vocab_file = os.path.join(
572
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
573
+ )
574
+
575
+ with open(vocab_file, "w", encoding="utf-8") as f:
576
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
577
+
578
+ return (vocab_file,)
579
+
580
+
581
+ __all__ = ["Wav2Vec2PhonemeCTCTokenizer"]
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .processing_wav2vec2_with_lm import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (653 Bytes). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/__pycache__/processing_wav2vec2_with_lm.cpython-312.pyc ADDED
Binary file (26.6 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Speech processor class for Wav2Vec2
16
+ """
17
+
18
+ import os
19
+ from collections.abc import Iterable
20
+ from contextlib import nullcontext
21
+ from dataclasses import dataclass
22
+ from multiprocessing import get_context, get_start_method
23
+ from multiprocessing.pool import Pool
24
+ from typing import TYPE_CHECKING
25
+
26
+ import numpy as np
27
+
28
+ from ...processing_utils import ProcessorMixin
29
+ from ...utils import ModelOutput, auto_docstring, logging, requires_backends
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ if TYPE_CHECKING:
36
+ from pyctcdecode import BeamSearchDecoderCTC
37
+
38
+ from ...feature_extraction_utils import FeatureExtractionMixin
39
+ from ...tokenization_python import PreTrainedTokenizerBase
40
+
41
+
42
+ ListOfDict = list[dict[str, int | str]]
43
+
44
+
45
+ @dataclass
46
+ class Wav2Vec2DecoderWithLMOutput(ModelOutput):
47
+ """
48
+ Output type of [`Wav2Vec2DecoderWithLM`], with transcription.
49
+
50
+ Args:
51
+ text (list of `str` or `str`):
52
+ Decoded logits in text from. Usually the speech transcription.
53
+ logit_score (list of `float` or `float`):
54
+ Total logit score of the beams associated with produced text.
55
+ lm_score (list of `float`):
56
+ Fused lm_score of the beams associated with produced text.
57
+ word_offsets (list of `list[dict[str, Union[int, str]]]` or `list[dict[str, Union[int, str]]]`):
58
+ Offsets of the decoded words. In combination with sampling rate and model downsampling rate word offsets
59
+ can be used to compute time stamps for each word.
60
+ """
61
+
62
+ text: list[list[str]] | list[str] | str
63
+ logit_score: list[list[float]] | list[float] | float = None
64
+ lm_score: list[list[float]] | list[float] | float = None
65
+ word_offsets: list[list[ListOfDict]] | list[ListOfDict] | ListOfDict = None
66
+
67
+
68
+ @auto_docstring
69
+ class Wav2Vec2ProcessorWithLM(ProcessorMixin):
70
+ def __init__(
71
+ self,
72
+ feature_extractor: "FeatureExtractionMixin",
73
+ tokenizer: "PreTrainedTokenizerBase",
74
+ decoder: "BeamSearchDecoderCTC",
75
+ ):
76
+ r"""
77
+ decoder (`pyctcdecode.BeamSearchDecoderCTC`):
78
+ An instance of [`pyctcdecode.BeamSearchDecoderCTC`]. The decoder is a required input.
79
+ """
80
+ from pyctcdecode import BeamSearchDecoderCTC
81
+
82
+ super().__init__(feature_extractor, tokenizer)
83
+ if not isinstance(decoder, BeamSearchDecoderCTC):
84
+ raise TypeError(f"`decoder` has to be of type {BeamSearchDecoderCTC.__class__}, but is {type(decoder)}")
85
+
86
+ if feature_extractor.__class__.__name__ not in ["Wav2Vec2FeatureExtractor", "SeamlessM4TFeatureExtractor"]:
87
+ raise ValueError(
88
+ f"`feature_extractor` has to be of type `Wav2Vec2FeatureExtractor` or `SeamlessM4TFeatureExtractor`, but is {type(feature_extractor)}"
89
+ )
90
+
91
+ # make sure that decoder's alphabet and tokenizer's vocab match in content
92
+ missing_decoder_tokens = self.get_missing_alphabet_tokens(decoder, tokenizer)
93
+ if len(missing_decoder_tokens) > 0:
94
+ raise ValueError(
95
+ f"The tokens {missing_decoder_tokens} are defined in the tokenizer's "
96
+ "vocabulary, but not in the decoder's alphabet. "
97
+ f"Make sure to include {missing_decoder_tokens} in the decoder's alphabet."
98
+ )
99
+
100
+ self.decoder = decoder
101
+
102
+ def save_pretrained(self, save_directory):
103
+ super().save_pretrained(save_directory)
104
+ self.decoder.save_to_dir(save_directory)
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
108
+ r"""
109
+ Instantiate a [`Wav2Vec2ProcessorWithLM`] from a pretrained Wav2Vec2 processor.
110
+
111
+ <Tip>
112
+
113
+ This class method is simply calling the feature extractor's
114
+ [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], Wav2Vec2CTCTokenizer's
115
+ [`~tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained`], and
116
+ [`pyctcdecode.BeamSearchDecoderCTC.load_from_hf_hub`].
117
+
118
+ Please refer to the docstrings of the methods above for more information.
119
+
120
+ </Tip>
121
+
122
+ Args:
123
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
124
+ This can be either:
125
+
126
+ - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
127
+ huggingface.co.
128
+ - a path to a *directory* containing a feature extractor file saved using the
129
+ [`~SequenceFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`.
130
+ - a path to a saved feature extractor JSON *file*, e.g.,
131
+ `./my_model_directory/preprocessor_config.json`.
132
+ **kwargs
133
+ Additional keyword arguments passed along to both [`SequenceFeatureExtractor`] and
134
+ [`PreTrainedTokenizer`]
135
+ """
136
+ requires_backends(cls, "pyctcdecode")
137
+ from pyctcdecode import BeamSearchDecoderCTC
138
+
139
+ feature_extractor, tokenizer = super()._get_arguments_from_pretrained(pretrained_model_name_or_path, **kwargs)
140
+
141
+ if os.path.isdir(pretrained_model_name_or_path) or os.path.isfile(pretrained_model_name_or_path):
142
+ unigram_encoding = kwargs.get("unigram_encoding", "utf-8")
143
+ decoder = BeamSearchDecoderCTC.load_from_dir(pretrained_model_name_or_path, unigram_encoding)
144
+ else:
145
+ # BeamSearchDecoderCTC has no auto class
146
+ kwargs.pop("_from_auto", None)
147
+ # snapshot_download has no `trust_remote_code` flag
148
+ kwargs.pop("trust_remote_code", None)
149
+
150
+ # make sure that only relevant filenames are downloaded
151
+ language_model_filenames = os.path.join(BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*")
152
+ alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
153
+ allow_patterns = [language_model_filenames, alphabet_filename]
154
+
155
+ decoder = BeamSearchDecoderCTC.load_from_hf_hub(
156
+ pretrained_model_name_or_path, allow_patterns=allow_patterns, **kwargs
157
+ )
158
+
159
+ # set language model attributes
160
+ for attribute in ["alpha", "beta", "unk_score_offset", "score_boundary"]:
161
+ value = kwargs.pop(attribute, None)
162
+
163
+ if value is not None:
164
+ cls._set_language_model_attribute(decoder, attribute, value)
165
+
166
+ # make sure that decoder's alphabet and tokenizer's vocab match in content
167
+ missing_decoder_tokens = cls.get_missing_alphabet_tokens(decoder, tokenizer)
168
+ if len(missing_decoder_tokens) > 0:
169
+ raise ValueError(
170
+ f"The tokens {missing_decoder_tokens} are defined in the tokenizer's "
171
+ "vocabulary, but not in the decoder's alphabet. "
172
+ f"Make sure to include {missing_decoder_tokens} in the decoder's alphabet."
173
+ )
174
+
175
+ return cls(feature_extractor=feature_extractor, tokenizer=tokenizer, decoder=decoder)
176
+
177
+ @staticmethod
178
+ def _set_language_model_attribute(decoder: "BeamSearchDecoderCTC", attribute: str, value: float):
179
+ setattr(decoder.model_container[decoder._model_key], attribute, value)
180
+
181
+ @property
182
+ def language_model(self):
183
+ return self.decoder.model_container[self.decoder._model_key]
184
+
185
+ @staticmethod
186
+ def get_missing_alphabet_tokens(decoder, tokenizer):
187
+ from pyctcdecode.alphabet import BLANK_TOKEN_PTN, UNK_TOKEN, UNK_TOKEN_PTN
188
+
189
+ # we need to make sure that all of the tokenizer's except the special tokens
190
+ # are present in the decoder's alphabet. Retrieve missing alphabet token
191
+ # from decoder
192
+ tokenizer_vocab_list = list(tokenizer.get_vocab().keys())
193
+
194
+ # replace special tokens
195
+ for i, token in enumerate(tokenizer_vocab_list):
196
+ if BLANK_TOKEN_PTN.match(token):
197
+ tokenizer_vocab_list[i] = ""
198
+ if token == tokenizer.word_delimiter_token:
199
+ tokenizer_vocab_list[i] = " "
200
+ if UNK_TOKEN_PTN.match(token):
201
+ tokenizer_vocab_list[i] = UNK_TOKEN
202
+
203
+ # are any of the extra tokens no special tokenizer tokens?
204
+ missing_tokens = set(tokenizer_vocab_list) - set(decoder._alphabet.labels)
205
+
206
+ return missing_tokens
207
+
208
+ @auto_docstring
209
+ def __call__(self, *args, **kwargs):
210
+ audio = kwargs.pop("audio", None)
211
+ sampling_rate = kwargs.pop("sampling_rate", None)
212
+ text = kwargs.pop("text", None)
213
+ if len(args) > 0:
214
+ audio = args[0]
215
+ args = args[1:]
216
+
217
+ if audio is None and text is None:
218
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
219
+
220
+ if audio is not None:
221
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
222
+ if text is not None:
223
+ encodings = self.tokenizer(text, **kwargs)
224
+
225
+ if text is None:
226
+ return inputs
227
+ elif audio is None:
228
+ return encodings
229
+ else:
230
+ inputs["labels"] = encodings["input_ids"]
231
+ return inputs
232
+
233
+ def pad(self, *args, **kwargs):
234
+ """
235
+ When used in normal mode, this method forwards all its arguments to the feature extractor's
236
+ [`~FeatureExtractionMixin.pad`] and returns its output. If used in the context
237
+ [`~Wav2Vec2ProcessorWithLM.as_target_processor`] this method forwards all its arguments to
238
+ Wav2Vec2CTCTokenizer's [`~Wav2Vec2CTCTokenizer.pad`]. Please refer to the docstring of the above two methods
239
+ for more information.
240
+ """
241
+ input_features = kwargs.pop("input_features", None)
242
+ labels = kwargs.pop("labels", None)
243
+ if len(args) > 0:
244
+ input_features = args[0]
245
+ args = args[1:]
246
+
247
+ if input_features is not None:
248
+ input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
249
+ if labels is not None:
250
+ labels = self.tokenizer.pad(labels, **kwargs)
251
+
252
+ if labels is None:
253
+ return input_features
254
+ elif input_features is None:
255
+ return labels
256
+ else:
257
+ input_features["labels"] = labels["input_ids"]
258
+ return input_features
259
+
260
+ def batch_decode(
261
+ self,
262
+ logits: np.ndarray,
263
+ pool: Pool | None = None,
264
+ num_processes: int | None = None,
265
+ beam_width: int | None = None,
266
+ beam_prune_logp: float | None = None,
267
+ token_min_logp: float | None = None,
268
+ hotwords: Iterable[str] | None = None,
269
+ hotword_weight: float | None = None,
270
+ alpha: float | None = None,
271
+ beta: float | None = None,
272
+ unk_score_offset: float | None = None,
273
+ lm_score_boundary: bool | None = None,
274
+ output_word_offsets: bool = False,
275
+ n_best: int = 1,
276
+ ):
277
+ """
278
+ Batch decode output logits to audio transcription with language model support.
279
+
280
+ <Tip>
281
+
282
+ This function makes use of Python's multiprocessing. Currently, multiprocessing is available only on Unix
283
+ systems (see this [issue](https://github.com/kensho-technologies/pyctcdecode/issues/65)).
284
+
285
+ If you are decoding multiple batches, consider creating a `Pool` and passing it to `batch_decode`. Otherwise,
286
+ `batch_decode` will be very slow since it will create a fresh `Pool` for each call. See usage example below.
287
+
288
+ </Tip>
289
+
290
+ Args:
291
+ logits (`np.ndarray`):
292
+ The logits output vector of the model representing the log probabilities for each token.
293
+ pool (`multiprocessing.Pool`, *optional*):
294
+ An optional user-managed pool. If not set, one will be automatically created and closed. The pool
295
+ should be instantiated *after* `Wav2Vec2ProcessorWithLM`. Otherwise, the LM won't be available to the
296
+ pool's sub-processes.
297
+
298
+ <Tip>
299
+
300
+ Currently, only pools created with a 'fork' context can be used. If a 'spawn' pool is passed, it will
301
+ be ignored and sequential decoding will be used instead.
302
+
303
+ </Tip>
304
+
305
+ num_processes (`int`, *optional*):
306
+ If `pool` is not set, number of processes on which the function should be parallelized over. Defaults
307
+ to the number of available CPUs.
308
+ beam_width (`int`, *optional*):
309
+ Maximum number of beams at each step in decoding. Defaults to pyctcdecode's DEFAULT_BEAM_WIDTH.
310
+ beam_prune_logp (`int`, *optional*):
311
+ Beams that are much worse than best beam will be pruned Defaults to pyctcdecode's DEFAULT_PRUNE_LOGP.
312
+ token_min_logp (`int`, *optional*):
313
+ Tokens below this logp are skipped unless they are argmax of frame Defaults to pyctcdecode's
314
+ DEFAULT_MIN_TOKEN_LOGP.
315
+ hotwords (`list[str]`, *optional*):
316
+ List of words with extra importance, can be OOV for LM
317
+ hotword_weight (`int`, *optional*):
318
+ Weight factor for hotword importance Defaults to pyctcdecode's DEFAULT_HOTWORD_WEIGHT.
319
+ alpha (`float`, *optional*):
320
+ Weight for language model during shallow fusion
321
+ beta (`float`, *optional*):
322
+ Weight for length score adjustment of during scoring
323
+ unk_score_offset (`float`, *optional*):
324
+ Amount of log score offset for unknown tokens
325
+ lm_score_boundary (`bool`, *optional*):
326
+ Whether to have kenlm respect boundaries when scoring
327
+ output_word_offsets (`bool`, *optional*, defaults to `False`):
328
+ Whether or not to output word offsets. Word offsets can be used in combination with the sampling rate
329
+ and model downsampling rate to compute the time-stamps of transcribed words.
330
+ n_best (`int`, *optional*, defaults to `1`):
331
+ Number of best hypotheses to return. If `n_best` is greater than 1, the returned `text` will be a list
332
+ of lists of strings, `logit_score` will be a list of lists of floats, and `lm_score` will be a list of
333
+ lists of floats, where the length of the outer list will correspond to the batch size and the length of
334
+ the inner list will correspond to the number of returned hypotheses . The value should be >= 1.
335
+
336
+ <Tip>
337
+
338
+ Please take a look at the Example of [`~Wav2Vec2ProcessorWithLM.decode`] to better understand how to
339
+ make use of `output_word_offsets`. [`~Wav2Vec2ProcessorWithLM.batch_decode`] works the same way with
340
+ batched output.
341
+
342
+ </Tip>
343
+
344
+ Returns:
345
+ [`~models.wav2vec2.Wav2Vec2DecoderWithLMOutput`].
346
+
347
+ Example:
348
+ See [Decoding multiple audios](#decoding-multiple-audios).
349
+ """
350
+
351
+ from pyctcdecode.constants import (
352
+ DEFAULT_BEAM_WIDTH,
353
+ DEFAULT_HOTWORD_WEIGHT,
354
+ DEFAULT_MIN_TOKEN_LOGP,
355
+ DEFAULT_PRUNE_LOGP,
356
+ )
357
+
358
+ # set defaults
359
+ beam_width = beam_width if beam_width is not None else DEFAULT_BEAM_WIDTH
360
+ beam_prune_logp = beam_prune_logp if beam_prune_logp is not None else DEFAULT_PRUNE_LOGP
361
+ token_min_logp = token_min_logp if token_min_logp is not None else DEFAULT_MIN_TOKEN_LOGP
362
+ hotword_weight = hotword_weight if hotword_weight is not None else DEFAULT_HOTWORD_WEIGHT
363
+
364
+ # reset params at every forward call. It's just a `set` method in pyctcdecode
365
+ self.decoder.reset_params(
366
+ alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary
367
+ )
368
+
369
+ # create multiprocessing pool and list numpy arrays
370
+ # filter out logits padding
371
+ logits_list = [array[(array != -100.0).all(axis=-1)] for array in logits]
372
+
373
+ # create a pool if necessary while also using it as a context manager to close itself
374
+ if pool is None:
375
+ # fork is safe to use only on Unix, see "Contexts and start methods" section on
376
+ # multiprocessing's docs (https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods)
377
+ default_context = get_start_method()
378
+
379
+ if default_context == "fork":
380
+ cm = pool = get_context().Pool(num_processes)
381
+ else:
382
+ logger.warning(
383
+ "Parallel batch decoding is not currently supported in this platform. "
384
+ "Falling back to sequential decoding."
385
+ )
386
+ cm = nullcontext()
387
+ else:
388
+ # pool is managed by the user, so we don't need to close it
389
+ cm = nullcontext()
390
+
391
+ if num_processes is not None:
392
+ logger.warning(
393
+ "Parameter `num_process` was passed, but it will be ignored since `pool` was also specified."
394
+ )
395
+
396
+ # pyctcdecode
397
+ with cm:
398
+ decoded_beams = self.decoder.decode_beams_batch(
399
+ pool=pool,
400
+ logits_list=logits_list,
401
+ beam_width=beam_width,
402
+ beam_prune_logp=beam_prune_logp,
403
+ token_min_logp=token_min_logp,
404
+ hotwords=hotwords,
405
+ hotword_weight=hotword_weight,
406
+ )
407
+
408
+ # extract text and scores
409
+ batch_texts, logit_scores, lm_scores, word_offsets = [], [], [], []
410
+
411
+ for d in decoded_beams:
412
+ batch_texts.append([beam[0] for beam in d])
413
+ logit_scores.append([beam[-2] for beam in d])
414
+ lm_scores.append([beam[-1] for beam in d])
415
+
416
+ # word_offsets.append([{"word": t[0], "start_offset": t[1][0], "end_offset": t[1][1]} for t in d[0][1]])
417
+
418
+ word_offsets.append(
419
+ [
420
+ [
421
+ {"word": word, "start_offset": start_offset, "end_offset": end_offset}
422
+ for word, (start_offset, end_offset) in beam[1]
423
+ ]
424
+ for beam in d
425
+ ]
426
+ )
427
+
428
+ word_offsets = word_offsets if output_word_offsets else None
429
+
430
+ if n_best == 1:
431
+ return Wav2Vec2DecoderWithLMOutput(
432
+ text=[hyps[0] for hyps in batch_texts],
433
+ logit_score=[hyps[0] for hyps in logit_scores],
434
+ lm_score=[hyps[0] for hyps in lm_scores],
435
+ word_offsets=[hyps[0] for hyps in word_offsets] if word_offsets is not None else None,
436
+ )
437
+ else:
438
+ return Wav2Vec2DecoderWithLMOutput(
439
+ text=[hyps[:n_best] for hyps in batch_texts],
440
+ logit_score=[hyps[:n_best] for hyps in logit_scores],
441
+ lm_score=[hyps[:n_best] for hyps in lm_scores],
442
+ word_offsets=[hyps[:n_best] for hyps in word_offsets] if word_offsets is not None else None,
443
+ )
444
+
445
+ def decode(
446
+ self,
447
+ logits: np.ndarray,
448
+ beam_width: int | None = None,
449
+ beam_prune_logp: float | None = None,
450
+ token_min_logp: float | None = None,
451
+ hotwords: Iterable[str] | None = None,
452
+ hotword_weight: float | None = None,
453
+ alpha: float | None = None,
454
+ beta: float | None = None,
455
+ unk_score_offset: float | None = None,
456
+ lm_score_boundary: bool | None = None,
457
+ output_word_offsets: bool = False,
458
+ n_best: int = 1,
459
+ ):
460
+ """
461
+ Decode output logits to audio transcription with language model support.
462
+
463
+ Args:
464
+ logits (`np.ndarray`):
465
+ The logits output vector of the model representing the log probabilities for each token.
466
+ beam_width (`int`, *optional*):
467
+ Maximum number of beams at each step in decoding. Defaults to pyctcdecode's DEFAULT_BEAM_WIDTH.
468
+ beam_prune_logp (`int`, *optional*):
469
+ A threshold to prune beams with log-probs less than best_beam_logp + beam_prune_logp. The value should
470
+ be <= 0. Defaults to pyctcdecode's DEFAULT_PRUNE_LOGP.
471
+ token_min_logp (`int`, *optional*):
472
+ Tokens with log-probs below token_min_logp are skipped unless they are have the maximum log-prob for an
473
+ utterance. Defaults to pyctcdecode's DEFAULT_MIN_TOKEN_LOGP.
474
+ hotwords (`list[str]`, *optional*):
475
+ List of words with extra importance which can be missing from the LM's vocabulary, e.g. ["huggingface"]
476
+ hotword_weight (`int`, *optional*):
477
+ Weight multiplier that boosts hotword scores. Defaults to pyctcdecode's DEFAULT_HOTWORD_WEIGHT.
478
+ alpha (`float`, *optional*):
479
+ Weight for language model during shallow fusion
480
+ beta (`float`, *optional*):
481
+ Weight for length score adjustment of during scoring
482
+ unk_score_offset (`float`, *optional*):
483
+ Amount of log score offset for unknown tokens
484
+ lm_score_boundary (`bool`, *optional*):
485
+ Whether to have kenlm respect boundaries when scoring
486
+ output_word_offsets (`bool`, *optional*, defaults to `False`):
487
+ Whether or not to output word offsets. Word offsets can be used in combination with the sampling rate
488
+ and model downsampling rate to compute the time-stamps of transcribed words.
489
+ n_best (`int`, *optional*, defaults to `1`):
490
+ Number of best hypotheses to return. If `n_best` is greater than 1, the returned `text` will be a list
491
+ of strings, `logit_score` will be a list of floats, and `lm_score` will be a list of floats, where the
492
+ length of these lists will correspond to the number of returned hypotheses. The value should be >= 1.
493
+
494
+ <Tip>
495
+
496
+ Please take a look at the example below to better understand how to make use of `output_word_offsets`.
497
+
498
+ </Tip>
499
+
500
+ Returns:
501
+ [`~models.wav2vec2.Wav2Vec2DecoderWithLMOutput`].
502
+
503
+ Example:
504
+
505
+ ```python
506
+ >>> # Let's see how to retrieve time steps for a model
507
+ >>> from transformers import AutoTokenizer, AutoProcessor, AutoModelForCTC
508
+ >>> from datasets import load_dataset
509
+ >>> import datasets
510
+ >>> import torch
511
+
512
+ >>> # import model, feature extractor, tokenizer
513
+ >>> model = AutoModelForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm")
514
+ >>> processor = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm")
515
+
516
+ >>> # load first sample of English common_voice
517
+ >>> dataset = load_dataset("mozilla-foundation/common_voice_11_0", "en", split="train", streaming=True)
518
+ >>> dataset = dataset.cast_column("audio", datasets.Audio(sampling_rate=16_000))
519
+ >>> dataset_iter = iter(dataset)
520
+ >>> sample = next(dataset_iter)
521
+
522
+ >>> # forward sample through model to get greedily predicted transcription ids
523
+ >>> input_values = processor(sample["audio"]["array"], return_tensors="pt").input_values
524
+ >>> with torch.no_grad():
525
+ ... logits = model(input_values).logits[0].cpu().numpy()
526
+
527
+ >>> # retrieve word stamps (analogous commands for `output_char_offsets`)
528
+ >>> outputs = processor.decode(logits, output_word_offsets=True)
529
+ >>> # compute `time_offset` in seconds as product of downsampling ratio and sampling_rate
530
+ >>> time_offset = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
531
+
532
+ >>> word_offsets = [
533
+ ... {
534
+ ... "word": d["word"],
535
+ ... "start_time": round(d["start_offset"] * time_offset, 2),
536
+ ... "end_time": round(d["end_offset"] * time_offset, 2),
537
+ ... }
538
+ ... for d in outputs.word_offsets
539
+ ... ]
540
+ >>> # compare word offsets with audio `en_train_0/common_voice_en_19121553.mp3` online on the dataset viewer:
541
+ >>> # https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0/viewer/en
542
+ >>> word_offsets[:4]
543
+ [{'word': 'THE', 'start_time': 0.68, 'end_time': 0.78}, {'word': 'TRACK', 'start_time': 0.88, 'end_time': 1.1}, {'word': 'APPEARS', 'start_time': 1.18, 'end_time': 1.66}, {'word': 'ON', 'start_time': 1.86, 'end_time': 1.92}]
544
+ ```"""
545
+
546
+ from pyctcdecode.constants import (
547
+ DEFAULT_BEAM_WIDTH,
548
+ DEFAULT_HOTWORD_WEIGHT,
549
+ DEFAULT_MIN_TOKEN_LOGP,
550
+ DEFAULT_PRUNE_LOGP,
551
+ )
552
+
553
+ # set defaults
554
+ beam_width = beam_width if beam_width is not None else DEFAULT_BEAM_WIDTH
555
+ beam_prune_logp = beam_prune_logp if beam_prune_logp is not None else DEFAULT_PRUNE_LOGP
556
+ token_min_logp = token_min_logp if token_min_logp is not None else DEFAULT_MIN_TOKEN_LOGP
557
+ hotword_weight = hotword_weight if hotword_weight is not None else DEFAULT_HOTWORD_WEIGHT
558
+
559
+ # reset params at every forward call. It's just a `set` method in pyctcdecode
560
+ self.decoder.reset_params(
561
+ alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary
562
+ )
563
+
564
+ # pyctcdecode
565
+ decoded_beams = self.decoder.decode_beams(
566
+ logits,
567
+ beam_width=beam_width,
568
+ beam_prune_logp=beam_prune_logp,
569
+ token_min_logp=token_min_logp,
570
+ hotwords=hotwords,
571
+ hotword_weight=hotword_weight,
572
+ )
573
+
574
+ word_offsets = None
575
+ if output_word_offsets:
576
+ word_offsets = [
577
+ [
578
+ {"word": word, "start_offset": start_offset, "end_offset": end_offset}
579
+ for word, (start_offset, end_offset) in beam[2]
580
+ ]
581
+ for beam in decoded_beams
582
+ ]
583
+ logit_scores = [beam[-2] for beam in decoded_beams]
584
+
585
+ lm_scores = [beam[-1] for beam in decoded_beams]
586
+
587
+ hypotheses = [beam[0] for beam in decoded_beams]
588
+
589
+ if n_best > len(decoded_beams):
590
+ logger.info(
591
+ "N-best size is larger than the number of generated hypotheses, all hypotheses will be returned."
592
+ )
593
+
594
+ if n_best == 1:
595
+ return Wav2Vec2DecoderWithLMOutput(
596
+ text=hypotheses[0],
597
+ logit_score=logit_scores[0],
598
+ lm_score=lm_scores[0],
599
+ word_offsets=word_offsets[0] if word_offsets is not None else None,
600
+ )
601
+ else:
602
+ return Wav2Vec2DecoderWithLMOutput(
603
+ text=hypotheses[:n_best],
604
+ logit_score=logit_scores[:n_best],
605
+ lm_score=lm_scores[:n_best],
606
+ word_offsets=word_offsets[:n_best] if word_offsets is not None else None,
607
+ )
608
+
609
+
610
+ __all__ = ["Wav2Vec2ProcessorWithLM"]
.venv/lib/python3.12/site-packages/transformers/models/wavlm/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_wavlm import *
22
+ from .modeling_wavlm import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (663 Bytes). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/configuration_wavlm.cpython-312.pyc ADDED
Binary file (14.8 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modeling_wavlm.cpython-312.pyc ADDED
Binary file (79.2 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wavlm/__pycache__/modular_wavlm.cpython-312.pyc ADDED
Binary file (27.8 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/wavlm/configuration_wavlm.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Fairseq Authors, Microsoft Research, and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """WavLM model configuration"""
15
+
16
+ import functools
17
+ import operator
18
+
19
+ from huggingface_hub.dataclasses import strict
20
+
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ...utils import auto_docstring
23
+
24
+
25
+ @auto_docstring(checkpoint="microsoft/wavlm-base")
26
+ @strict
27
+ class WavLMConfig(PreTrainedConfig):
28
+ r"""
29
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
30
+ The dropout probability for output of the feature encoder.
31
+ final_dropout (`float`, *optional*, defaults to 0.1):
32
+ The dropout probability for the final projection layer of [`WavLMForCTC`].
33
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
34
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
35
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
36
+ convolutional layers.
37
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
38
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
39
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
40
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
41
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
42
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
43
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
44
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
45
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
46
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
47
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
48
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
49
+ *conv_dim*.
50
+ conv_bias (`bool`, *optional*, defaults to `False`):
51
+ Whether the 1D convolutional layers have a bias.
52
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
53
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
54
+ embeddings layer.
55
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
56
+ Number of groups of 1D convolutional positional embeddings layer.
57
+ num_buckets (`int`, *optional*, defaults to 320):
58
+ The number of buckets to use for each attention layer
59
+ max_bucket_distance (`int`, *optional*, defaults to 800):
60
+ Maximum bucket distance
61
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
62
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
63
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
64
+ False` corresponds to applying layer norm after the attention layer.
65
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
66
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
67
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
68
+ Recognition](https://huggingface.co/papers/1904.08779).
69
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
70
+ Probability of each feature vector along the time axis to be chosen as the start of the vector span to be
71
+ masked. Approximately `mask_time_prob * sequence_length // mask_time_length` feature vectors will be masked
72
+ along the time axis. This is only relevant if `apply_spec_augment is True`.
73
+ mask_time_length (`int`, *optional*, defaults to 10):
74
+ Length of vector span along the time axis.
75
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
76
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
77
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
78
+ mask_time_min_masks''
79
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
80
+ Probability of each feature vector along the feature axis to be chosen as the start of the vector span to
81
+ be masked. Approximately `mask_time_prob * hidden_size // mask_time_length` feature vectors will be masked
82
+ along the time axis. This is only relevant if `apply_spec_augment is True`.
83
+ mask_feature_length (`int`, *optional*, defaults to 10):
84
+ Length of vector span along the feature axis.
85
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
86
+ Number of entries in each quantization codebook (group).
87
+ num_codevector_groups (`int`, *optional*, defaults to 2):
88
+ Number of codevector groups for product codevector quantization.
89
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
90
+ The temperature *kappa* in the contrastive loss.
91
+ num_negatives (`int`, *optional*, defaults to 100):
92
+ Number of negative samples for the contrastive loss.
93
+ codevector_dim (`int`, *optional*, defaults to 256):
94
+ Dimensionality of the quantized feature vectors.
95
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
96
+ Dimensionality of the final projection of both the quantized and the transformer features.
97
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
98
+ The weight of the codebook diversity loss component.
99
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
100
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
101
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
102
+ of [`WavLMForCTC`].
103
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
104
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
105
+ instance of [`WavLMForSequenceClassification`].
106
+ classifier_proj_size (`int`, *optional*, defaults to 256):
107
+ Dimensionality of the projection before token mean-pooling for classification.
108
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
109
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
110
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
111
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
112
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
113
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
114
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
115
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
116
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
117
+ xvector_output_dim (`int`, *optional*, defaults to 512):
118
+ Dimensionality of the *XVector* embedding vectors.
119
+ num_ctc_classes (`int`, *optional*, defaults to 80):
120
+ Specifies the number of classes (phoneme tokens and blank token) for phoneme-level CTC loss. Only relevant
121
+ when using an instance of [`UniSpeechForPreTraining`].
122
+ add_adapter (`bool`, *optional*, defaults to `False`):
123
+ Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for
124
+ warm-starting Wav2Vec2 for SpeechEncoderDecoder models.
125
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
126
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
127
+ adapter_stride (`int`, *optional*, defaults to 2):
128
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
129
+ num_adapter_layers (`int`, *optional*, defaults to 3):
130
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
131
+ True`.
132
+ output_hidden_size (`int`, *optional*):
133
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
134
+ if `add_adapter is True`.
135
+
136
+ Example:
137
+
138
+ ```python
139
+
140
+ ```
141
+
142
+ Example:
143
+
144
+ ```python
145
+ >>> from transformers import WavLMConfig, WavLMModel
146
+
147
+ >>> # Initializing a WavLM facebook/wavlm-base-960h style configuration
148
+ >>> configuration = WavLMConfig()
149
+
150
+ >>> # Initializing a model (with random weights) from the facebook/wavlm-base-960h style configuration
151
+ >>> model = WavLMModel(configuration)
152
+
153
+ >>> # Accessing the model configuration
154
+ >>> configuration = model.config
155
+ ```"""
156
+
157
+ model_type = "wavlm"
158
+
159
+ vocab_size: int = 32
160
+ hidden_size: int = 768
161
+ num_hidden_layers: int = 12
162
+ num_attention_heads: int = 12
163
+ intermediate_size: int = 3072
164
+ hidden_act: str = "gelu"
165
+ hidden_dropout: float | int = 0.1
166
+ activation_dropout: float | int = 0.1
167
+ attention_dropout: float | int = 0.1
168
+ feat_proj_dropout: float | int = 0.0
169
+ final_dropout: float | int = 0.1
170
+ layerdrop: float | int = 0.1
171
+ initializer_range: float = 0.02
172
+ layer_norm_eps: float = 1e-5
173
+ feat_extract_norm: str = "group"
174
+ feat_extract_activation: str = "gelu"
175
+ conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
176
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
177
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
178
+ conv_bias: bool = False
179
+ num_conv_pos_embeddings: int = 128
180
+ num_conv_pos_embedding_groups: int = 16
181
+ num_buckets: int = 320
182
+ max_bucket_distance: int = 800
183
+ do_stable_layer_norm: bool = False
184
+ apply_spec_augment: bool = True
185
+ mask_time_prob: float | int = 0.05
186
+ mask_time_length: int = 10
187
+ mask_time_min_masks: int = 2
188
+ mask_feature_prob: float | int = 0.0
189
+ mask_feature_length: int = 10
190
+ num_codevectors_per_group: int = 320
191
+ num_codevector_groups: int = 2
192
+ contrastive_logits_temperature: float = 0.1
193
+ num_negatives: int = 100
194
+ codevector_dim: int = 256
195
+ proj_codevector_dim: int = 256
196
+ diversity_loss_weight: float = 0.1
197
+ ctc_loss_reduction: str = "mean"
198
+ ctc_zero_infinity: bool = False
199
+ use_weighted_layer_sum: bool = False
200
+ classifier_proj_size: int = 256
201
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
202
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
203
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
204
+ xvector_output_dim: int = 512
205
+ num_ctc_classes: int = 80
206
+ pad_token_id: int | None = 0
207
+ bos_token_id: int | None = 1
208
+ eos_token_id: int | list[int] | None = 2
209
+ add_adapter: bool = False
210
+ adapter_kernel_size: int = 3
211
+ adapter_stride: int = 2
212
+ num_adapter_layers: int = 3
213
+ output_hidden_size: int | None = None
214
+
215
+ def __post_init__(self, **kwargs):
216
+ self.num_feat_extract_layers = len(self.conv_dim)
217
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
218
+ super().__post_init__(**kwargs)
219
+
220
+ def validate_architecture(self):
221
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
222
+ if (
223
+ (len(self.conv_stride) != self.num_feat_extract_layers)
224
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
225
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
226
+ ):
227
+ raise ValueError(
228
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
229
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
230
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
231
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
232
+ )
233
+
234
+ @property
235
+ def inputs_to_logits_ratio(self):
236
+ return functools.reduce(operator.mul, self.conv_stride, 1)
237
+
238
+
239
+ __all__ = ["WavLMConfig"]
.venv/lib/python3.12/site-packages/transformers/models/wavlm/modeling_wavlm.py ADDED
@@ -0,0 +1,1654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/wavlm/modular_wavlm.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_wavlm.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ import math
8
+ import warnings
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from torch.nn import CrossEntropyLoss
15
+
16
+ from ... import initialization as init
17
+ from ...activations import ACT2FN
18
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
19
+ from ...integrations.fsdp import is_fsdp_managed_module
20
+ from ...modeling_layers import GradientCheckpointingLayer
21
+ from ...modeling_outputs import (
22
+ BaseModelOutput,
23
+ CausalLMOutput,
24
+ SequenceClassifierOutput,
25
+ TokenClassifierOutput,
26
+ Wav2Vec2BaseModelOutput,
27
+ XVectorOutput,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel, get_torch_context_manager_or_global_device
30
+ from ...utils import auto_docstring, is_peft_available, logging
31
+ from .configuration_wavlm import WavLMConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class WavLMSamePadLayer(nn.Module):
38
+ def __init__(self, num_conv_pos_embeddings):
39
+ super().__init__()
40
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
41
+
42
+ def forward(self, hidden_states):
43
+ if self.num_pad_remove > 0:
44
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
45
+ return hidden_states
46
+
47
+
48
+ class WavLMPositionalConvEmbedding(nn.Module):
49
+ def __init__(self, config):
50
+ super().__init__()
51
+ self.conv = nn.Conv1d(
52
+ config.hidden_size,
53
+ config.hidden_size,
54
+ kernel_size=config.num_conv_pos_embeddings,
55
+ padding=config.num_conv_pos_embeddings // 2,
56
+ groups=config.num_conv_pos_embedding_groups,
57
+ )
58
+
59
+ weight_norm = nn.utils.weight_norm
60
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
61
+ weight_norm = nn.utils.parametrizations.weight_norm
62
+
63
+ if is_deepspeed_zero3_enabled():
64
+ import deepspeed
65
+
66
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
67
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
68
+ if hasattr(self.conv, "parametrizations"):
69
+ weight_g = self.conv.parametrizations.weight.original0
70
+ weight_v = self.conv.parametrizations.weight.original1
71
+ else:
72
+ weight_g = self.conv.weight_g
73
+ weight_v = self.conv.weight_v
74
+ deepspeed.zero.register_external_parameter(self, weight_v)
75
+ deepspeed.zero.register_external_parameter(self, weight_g)
76
+ else:
77
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
78
+
79
+ self.padding = WavLMSamePadLayer(config.num_conv_pos_embeddings)
80
+ self.activation = ACT2FN[config.feat_extract_activation]
81
+
82
+ def forward(self, hidden_states):
83
+ hidden_states = hidden_states.transpose(1, 2)
84
+
85
+ hidden_states = self.conv(hidden_states)
86
+ hidden_states = self.padding(hidden_states)
87
+ hidden_states = self.activation(hidden_states)
88
+
89
+ hidden_states = hidden_states.transpose(1, 2)
90
+ return hidden_states
91
+
92
+
93
+ class WavLMFeatureProjection(nn.Module):
94
+ def __init__(self, config):
95
+ super().__init__()
96
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
97
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
98
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
99
+
100
+ def forward(self, hidden_states):
101
+ # non-projected hidden states are needed for quantization
102
+ norm_hidden_states = self.layer_norm(hidden_states)
103
+ hidden_states = self.projection(norm_hidden_states)
104
+ hidden_states = self.dropout(hidden_states)
105
+ return hidden_states, norm_hidden_states
106
+
107
+
108
+ class WavLMAttention(nn.Module):
109
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
110
+
111
+ def __init__(
112
+ self,
113
+ embed_dim: int,
114
+ num_heads: int,
115
+ dropout: float | int = 0.0,
116
+ num_buckets: int = 320,
117
+ max_distance: int = 800,
118
+ has_relative_position_bias: bool = True,
119
+ ):
120
+ super().__init__()
121
+ self.embed_dim = embed_dim
122
+ self.num_heads = num_heads
123
+ self.dropout = dropout
124
+ self.head_dim = embed_dim // num_heads
125
+
126
+ if (self.head_dim * num_heads) != self.embed_dim:
127
+ raise ValueError(
128
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
129
+ f" and `num_heads`: {num_heads})."
130
+ )
131
+ self.scaling = self.head_dim**-0.5
132
+
133
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
134
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
135
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
136
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
137
+
138
+ self.num_buckets = num_buckets
139
+ self.max_distance = max_distance
140
+
141
+ self.gru_rel_pos_const = nn.Parameter(torch.ones(1, self.num_heads, 1, 1))
142
+ self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)
143
+
144
+ if has_relative_position_bias:
145
+ self.rel_attn_embed = nn.Embedding(self.num_buckets, self.num_heads)
146
+
147
+ def forward(
148
+ self,
149
+ hidden_states: torch.Tensor,
150
+ attention_mask: torch.Tensor | None = None,
151
+ position_bias: torch.Tensor | None = None,
152
+ output_attentions: bool = False,
153
+ index=0,
154
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
155
+ """Attention layer with relative attention"""
156
+ bsz, tgt_len, _ = hidden_states.size()
157
+
158
+ # first pass of attention layer creates position bias
159
+ if position_bias is None:
160
+ position_bias = self.compute_bias(tgt_len, tgt_len)
161
+ position_bias = (
162
+ position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, tgt_len)
163
+ )
164
+
165
+ # Compute relative position bias:
166
+ # 1) get reshape hidden_states
167
+ gated_hidden_states = hidden_states.view(hidden_states.shape[:-1] + (self.num_heads, -1))
168
+ gated_hidden_states = gated_hidden_states.permute(0, 2, 1, 3)
169
+
170
+ # 2) project hidden states
171
+ relative_position_proj = self.gru_rel_pos_linear(gated_hidden_states)
172
+ relative_position_proj = relative_position_proj.view(gated_hidden_states.shape[:-1] + (2, 4)).sum(-1)
173
+
174
+ # 3) compute gate for position bias from projected hidden states
175
+ gate_a, gate_b = torch.sigmoid(relative_position_proj).chunk(2, dim=-1)
176
+ gate_output = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0
177
+
178
+ # 4) apply gate to position bias to compute gated position_bias
179
+ gated_position_bias = gate_output.view(bsz * self.num_heads, -1, 1) * position_bias
180
+ gated_position_bias = gated_position_bias.view((-1, tgt_len, tgt_len))
181
+
182
+ attn_output, attn_weights = self.torch_multi_head_self_attention(
183
+ hidden_states, attention_mask, gated_position_bias, output_attentions
184
+ )
185
+
186
+ return attn_output, attn_weights, position_bias
187
+
188
+ def torch_multi_head_self_attention(
189
+ self,
190
+ hidden_states: torch.FloatTensor,
191
+ attention_mask: torch.LongTensor | torch.BoolTensor,
192
+ gated_position_bias: torch.FloatTensor,
193
+ output_attentions: bool,
194
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor]:
195
+ """simple wrapper around torch's multi_head_attention_forward function"""
196
+ # self-attention assumes q = k = v
197
+ query = key = value = hidden_states.transpose(0, 1)
198
+ key_padding_mask = attention_mask.ne(1) if attention_mask is not None else None
199
+
200
+ # disable bias and add_zero_attn
201
+ bias_k = bias_v = None
202
+ add_zero_attn = False
203
+
204
+ # PyTorch 1.3.0 has F.multi_head_attention_forward defined
205
+ # so no problem with backwards compatibility
206
+ attn_output, attn_weights = F.multi_head_attention_forward(
207
+ query,
208
+ key,
209
+ value,
210
+ self.embed_dim,
211
+ self.num_heads,
212
+ torch.empty([0]),
213
+ torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
214
+ bias_k,
215
+ bias_v,
216
+ add_zero_attn,
217
+ self.dropout,
218
+ self.out_proj.weight,
219
+ self.out_proj.bias,
220
+ self.training,
221
+ key_padding_mask,
222
+ output_attentions,
223
+ gated_position_bias,
224
+ use_separate_proj_weight=True,
225
+ q_proj_weight=self.q_proj.weight,
226
+ k_proj_weight=self.k_proj.weight,
227
+ v_proj_weight=self.v_proj.weight,
228
+ )
229
+
230
+ # [Seq_Len, Batch Size, ...] -> [Batch Size, Seq_Len, ...]
231
+ attn_output = attn_output.transpose(0, 1)
232
+
233
+ if attn_weights is not None:
234
+ # IMPORTANT: Attention weights are averaged weights
235
+ # here which should not be the case. This is an open issue
236
+ # on PyTorch: https://github.com/pytorch/pytorch/issues/32590
237
+ attn_weights = attn_weights[:, None].broadcast_to(
238
+ attn_weights.shape[:1] + (self.num_heads,) + attn_weights.shape[1:]
239
+ )
240
+
241
+ return attn_output, attn_weights
242
+
243
+ def compute_bias(self, query_length: int, key_length: int) -> torch.FloatTensor:
244
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
245
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
246
+ relative_position = memory_position - context_position
247
+ relative_position_bucket = self._relative_positions_bucket(relative_position)
248
+ relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)
249
+ values = self.rel_attn_embed(relative_position_bucket)
250
+ values = values.permute([2, 0, 1])
251
+ return values
252
+
253
+ def _relative_positions_bucket(self, relative_positions: torch.FloatTensor) -> torch.FloatTensor:
254
+ num_buckets = self.num_buckets // 2
255
+
256
+ relative_buckets = (relative_positions > 0).to(torch.long) * num_buckets
257
+ relative_positions = torch.abs(relative_positions)
258
+
259
+ max_exact = num_buckets // 2
260
+ is_small = relative_positions < max_exact
261
+
262
+ relative_positions_if_large = torch.log(relative_positions.float() / max_exact)
263
+ relative_positions_if_large = relative_positions_if_large / math.log(self.max_distance / max_exact)
264
+ relative_positions_if_large = relative_positions_if_large * (num_buckets - max_exact)
265
+ relative_position_if_large = (max_exact + relative_positions_if_large).to(torch.long)
266
+ relative_position_if_large = torch.min(
267
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
268
+ )
269
+
270
+ relative_buckets += torch.where(is_small, relative_positions, relative_position_if_large)
271
+ return relative_buckets
272
+
273
+
274
+ class WavLMFeedForward(nn.Module):
275
+ def __init__(self, config):
276
+ super().__init__()
277
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
278
+
279
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
280
+ if isinstance(config.hidden_act, str):
281
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
282
+ else:
283
+ self.intermediate_act_fn = config.hidden_act
284
+
285
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
286
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
287
+
288
+ def forward(self, hidden_states):
289
+ hidden_states = self.intermediate_dense(hidden_states)
290
+ hidden_states = self.intermediate_act_fn(hidden_states)
291
+ hidden_states = self.intermediate_dropout(hidden_states)
292
+
293
+ hidden_states = self.output_dense(hidden_states)
294
+ hidden_states = self.output_dropout(hidden_states)
295
+ return hidden_states
296
+
297
+
298
+ class WavLMEncoderLayer(GradientCheckpointingLayer):
299
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
300
+ super().__init__()
301
+ self.attention = WavLMAttention(
302
+ embed_dim=config.hidden_size,
303
+ num_heads=config.num_attention_heads,
304
+ dropout=config.attention_dropout,
305
+ num_buckets=config.num_buckets,
306
+ max_distance=config.max_bucket_distance,
307
+ has_relative_position_bias=has_relative_position_bias,
308
+ )
309
+ self.dropout = nn.Dropout(config.hidden_dropout)
310
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
311
+ self.feed_forward = WavLMFeedForward(config)
312
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
313
+
314
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False, index=0):
315
+ attn_residual = hidden_states
316
+ hidden_states, attn_weights, position_bias = self.attention(
317
+ hidden_states,
318
+ attention_mask=attention_mask,
319
+ position_bias=position_bias,
320
+ output_attentions=output_attentions,
321
+ index=index,
322
+ )
323
+ hidden_states = self.dropout(hidden_states)
324
+ hidden_states = attn_residual + hidden_states
325
+
326
+ hidden_states = self.layer_norm(hidden_states)
327
+
328
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
329
+ hidden_states = self.final_layer_norm(hidden_states)
330
+
331
+ outputs = (hidden_states, position_bias)
332
+
333
+ if output_attentions:
334
+ outputs += (attn_weights,)
335
+
336
+ return outputs
337
+
338
+
339
+ class WavLMEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
340
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
341
+ super().__init__()
342
+ self.attention = WavLMAttention(
343
+ embed_dim=config.hidden_size,
344
+ num_heads=config.num_attention_heads,
345
+ dropout=config.attention_dropout,
346
+ num_buckets=config.num_buckets,
347
+ max_distance=config.max_bucket_distance,
348
+ has_relative_position_bias=has_relative_position_bias,
349
+ )
350
+ self.dropout = nn.Dropout(config.hidden_dropout)
351
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
352
+ self.feed_forward = WavLMFeedForward(config)
353
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
354
+
355
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False):
356
+ attn_residual = hidden_states
357
+ hidden_states = self.layer_norm(hidden_states)
358
+ hidden_states, attn_weights, position_bias = self.attention(
359
+ hidden_states,
360
+ attention_mask=attention_mask,
361
+ position_bias=position_bias,
362
+ output_attentions=output_attentions,
363
+ )
364
+ hidden_states = self.dropout(hidden_states)
365
+ hidden_states = attn_residual + hidden_states
366
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
367
+
368
+ outputs = (hidden_states, position_bias)
369
+
370
+ if output_attentions:
371
+ outputs += (attn_weights,)
372
+
373
+ return outputs
374
+
375
+
376
+ class WavLMEncoder(nn.Module):
377
+ def __init__(self, config):
378
+ super().__init__()
379
+ self.config = config
380
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
381
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
382
+ self.dropout = nn.Dropout(config.hidden_dropout)
383
+ self.layers = nn.ModuleList(
384
+ [WavLMEncoderLayer(config, has_relative_position_bias=(i == 0)) for i in range(config.num_hidden_layers)]
385
+ )
386
+ self.gradient_checkpointing = False
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states,
391
+ attention_mask=None,
392
+ output_attentions=False,
393
+ output_hidden_states=False,
394
+ return_dict=True,
395
+ ):
396
+ all_hidden_states = () if output_hidden_states else None
397
+ all_self_attentions = () if output_attentions else None
398
+
399
+ if attention_mask is not None:
400
+ # make sure padded tokens output 0
401
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
402
+ hidden_states[~expand_attention_mask] = 0
403
+
404
+ position_embeddings = self.pos_conv_embed(hidden_states)
405
+ hidden_states = hidden_states + position_embeddings
406
+ hidden_states = self.layer_norm(hidden_states)
407
+ hidden_states = self.dropout(hidden_states)
408
+
409
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
410
+ position_bias = None
411
+
412
+ for i, layer in enumerate(self.layers):
413
+ if output_hidden_states:
414
+ all_hidden_states = all_hidden_states + (hidden_states,)
415
+
416
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
417
+ dropout_probability = torch.rand([])
418
+
419
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
420
+ if not skip_the_layer or synced_gpus:
421
+ # under fsdp or deepspeed zero3 all gpus must run in sync
422
+ layer_outputs = layer(
423
+ hidden_states,
424
+ attention_mask=attention_mask,
425
+ position_bias=position_bias,
426
+ output_attentions=output_attentions,
427
+ index=i,
428
+ )
429
+
430
+ hidden_states, position_bias = layer_outputs[:2]
431
+
432
+ if skip_the_layer:
433
+ layer_outputs = (None, None, None)
434
+
435
+ if output_attentions:
436
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
437
+
438
+ if output_hidden_states:
439
+ all_hidden_states = all_hidden_states + (hidden_states,)
440
+
441
+ if not return_dict:
442
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
443
+ return BaseModelOutput(
444
+ last_hidden_state=hidden_states,
445
+ hidden_states=all_hidden_states,
446
+ attentions=all_self_attentions,
447
+ )
448
+
449
+
450
+ class WavLMEncoderStableLayerNorm(nn.Module):
451
+ def __init__(self, config):
452
+ super().__init__()
453
+ self.config = config
454
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
455
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
456
+ self.dropout = nn.Dropout(config.hidden_dropout)
457
+ self.layers = nn.ModuleList(
458
+ [
459
+ WavLMEncoderLayerStableLayerNorm(config, has_relative_position_bias=(i == 0))
460
+ for i in range(config.num_hidden_layers)
461
+ ]
462
+ )
463
+ self.gradient_checkpointing = False
464
+
465
+ def forward(
466
+ self,
467
+ hidden_states,
468
+ attention_mask=None,
469
+ output_attentions=False,
470
+ output_hidden_states=False,
471
+ return_dict=True,
472
+ ):
473
+ all_hidden_states = () if output_hidden_states else None
474
+ all_self_attentions = () if output_attentions else None
475
+
476
+ if attention_mask is not None:
477
+ # make sure padded tokens are not attended to
478
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
479
+ hidden_states[~expand_attention_mask] = 0
480
+
481
+ position_embeddings = self.pos_conv_embed(hidden_states)
482
+ hidden_states = hidden_states + position_embeddings
483
+ hidden_states = self.dropout(hidden_states)
484
+
485
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
486
+ position_bias = None
487
+
488
+ for i, layer in enumerate(self.layers):
489
+ if output_hidden_states:
490
+ all_hidden_states = all_hidden_states + (hidden_states,)
491
+
492
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
493
+ dropout_probability = torch.rand([])
494
+
495
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
496
+ if not skip_the_layer or synced_gpus:
497
+ # under fsdp or deepspeed zero3 all gpus must run in sync
498
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
499
+ layer_outputs = layer(
500
+ hidden_states,
501
+ attention_mask=attention_mask,
502
+ output_attentions=output_attentions,
503
+ position_bias=position_bias,
504
+ )
505
+ hidden_states, position_bias = layer_outputs[:2]
506
+
507
+ if skip_the_layer:
508
+ layer_outputs = (None, None, None)
509
+
510
+ if output_attentions:
511
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
512
+
513
+ hidden_states = self.layer_norm(hidden_states)
514
+
515
+ if output_hidden_states:
516
+ all_hidden_states = all_hidden_states + (hidden_states,)
517
+
518
+ if not return_dict:
519
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
520
+ return BaseModelOutput(
521
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
522
+ )
523
+
524
+
525
+ class WavLMGumbelVectorQuantizer(nn.Module):
526
+ """
527
+ Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
528
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
529
+ """
530
+
531
+ def __init__(self, config):
532
+ super().__init__()
533
+ self.num_groups = config.num_codevector_groups
534
+ self.num_vars = config.num_codevectors_per_group
535
+
536
+ if config.codevector_dim % self.num_groups != 0:
537
+ raise ValueError(
538
+ f"`config.codevector_dim {config.codevector_dim} must be divisible"
539
+ f" by `config.num_codevector_groups` {self.num_groups} "
540
+ "for concatenation."
541
+ )
542
+
543
+ # storage for codebook variables (codewords)
544
+ self.codevectors = nn.Parameter(
545
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
546
+ )
547
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
548
+
549
+ # can be decayed for training
550
+ self.temperature = 2
551
+
552
+ @staticmethod
553
+ def _compute_perplexity(probs):
554
+ marginal_probs = probs.mean(dim=0)
555
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
556
+ return perplexity
557
+
558
+ def forward(self, hidden_states):
559
+ batch_size, sequence_length, hidden_size = hidden_states.shape
560
+
561
+ # project to codevector dim
562
+ hidden_states = self.weight_proj(hidden_states)
563
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
564
+
565
+ if self.training:
566
+ # sample code vector probs via gumbel in differentiateable way
567
+ codevector_probs = nn.functional.gumbel_softmax(hidden_states.float(), tau=self.temperature, hard=True)
568
+ codevector_probs = codevector_probs.type_as(hidden_states)
569
+
570
+ # compute perplexity
571
+ codevector_soft_dist = torch.softmax(
572
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
573
+ )
574
+ perplexity = self._compute_perplexity(codevector_soft_dist)
575
+ else:
576
+ # take argmax in non-differentiable way
577
+ # comptute hard codevector distribution (one hot)
578
+ codevector_idx = hidden_states.argmax(dim=-1)
579
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
580
+ -1, codevector_idx.view(-1, 1), 1.0
581
+ )
582
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
583
+
584
+ perplexity = self._compute_perplexity(codevector_probs)
585
+
586
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
587
+ # use probs to retrieve codevectors
588
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
589
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
590
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
591
+
592
+ return codevectors, perplexity
593
+
594
+
595
+ @auto_docstring
596
+ class WavLMPreTrainedModel(PreTrainedModel):
597
+ config: WavLMConfig
598
+ base_model_prefix = "wavlm"
599
+ main_input_name = "input_values"
600
+ input_modalities = "audio"
601
+ supports_gradient_checkpointing = True
602
+ _supports_flash_attn = False
603
+ _supports_sdpa = False
604
+ _supports_flex_attn = False
605
+
606
+ @torch.no_grad()
607
+ def _init_weights(self, module):
608
+ """Initialize the weights"""
609
+ # gumbel softmax requires special init
610
+ if isinstance(module, WavLMGumbelVectorQuantizer):
611
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
612
+ init.zeros_(module.weight_proj.bias)
613
+ init.uniform_(module.codevectors)
614
+ elif isinstance(module, WavLMPositionalConvEmbedding):
615
+ init.normal_(
616
+ module.conv.weight,
617
+ mean=0,
618
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
619
+ )
620
+ init.constant_(module.conv.bias, 0)
621
+ elif isinstance(module, WavLMFeatureProjection):
622
+ k = math.sqrt(1 / module.projection.in_features)
623
+ init.uniform_(module.projection.weight, a=-k, b=k)
624
+ init.uniform_(module.projection.bias, a=-k, b=k)
625
+ elif isinstance(module, nn.Linear):
626
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
627
+
628
+ if module.bias is not None:
629
+ init.zeros_(module.bias)
630
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
631
+ init.zeros_(module.bias)
632
+ init.ones_(module.weight)
633
+ elif isinstance(module, nn.Conv1d):
634
+ init.kaiming_normal_(module.weight)
635
+
636
+ if module.bias is not None:
637
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
638
+ init.uniform_(module.bias, a=-k, b=k)
639
+
640
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
641
+ """
642
+ Computes the output length of the convolutional layers
643
+ """
644
+
645
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
646
+
647
+ def _conv_out_length(input_length, kernel_size, stride):
648
+ # 1D convolutional layer output length formula taken
649
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
650
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
651
+
652
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
653
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
654
+
655
+ if add_adapter:
656
+ for _ in range(self.config.num_adapter_layers):
657
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
658
+
659
+ return input_lengths
660
+
661
+ def _get_feature_vector_attention_mask(
662
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
663
+ ):
664
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
665
+ # on inference mode.
666
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
667
+
668
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
669
+ output_lengths = output_lengths.to(torch.long)
670
+
671
+ batch_size = attention_mask.shape[0]
672
+
673
+ attention_mask = torch.zeros(
674
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
675
+ )
676
+ # these two operations makes sure that all values before the output lengths idxs are attended to
677
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
678
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
679
+ return attention_mask
680
+
681
+
682
+ class WavLMNoLayerNormConvLayer(GradientCheckpointingLayer):
683
+ def __init__(self, config, layer_id=0):
684
+ super().__init__()
685
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
686
+ self.out_conv_dim = config.conv_dim[layer_id]
687
+
688
+ self.conv = nn.Conv1d(
689
+ self.in_conv_dim,
690
+ self.out_conv_dim,
691
+ kernel_size=config.conv_kernel[layer_id],
692
+ stride=config.conv_stride[layer_id],
693
+ bias=config.conv_bias,
694
+ )
695
+ self.activation = ACT2FN[config.feat_extract_activation]
696
+
697
+ def forward(self, hidden_states):
698
+ hidden_states = self.conv(hidden_states)
699
+ hidden_states = self.activation(hidden_states)
700
+ return hidden_states
701
+
702
+
703
+ class WavLMLayerNormConvLayer(GradientCheckpointingLayer):
704
+ def __init__(self, config, layer_id=0):
705
+ super().__init__()
706
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
707
+ self.out_conv_dim = config.conv_dim[layer_id]
708
+
709
+ self.conv = nn.Conv1d(
710
+ self.in_conv_dim,
711
+ self.out_conv_dim,
712
+ kernel_size=config.conv_kernel[layer_id],
713
+ stride=config.conv_stride[layer_id],
714
+ bias=config.conv_bias,
715
+ )
716
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
717
+ self.activation = ACT2FN[config.feat_extract_activation]
718
+
719
+ def forward(self, hidden_states):
720
+ hidden_states = self.conv(hidden_states)
721
+
722
+ hidden_states = hidden_states.transpose(-2, -1)
723
+ hidden_states = self.layer_norm(hidden_states)
724
+ hidden_states = hidden_states.transpose(-2, -1)
725
+
726
+ hidden_states = self.activation(hidden_states)
727
+ return hidden_states
728
+
729
+
730
+ class WavLMGroupNormConvLayer(GradientCheckpointingLayer):
731
+ def __init__(self, config, layer_id=0):
732
+ super().__init__()
733
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
734
+ self.out_conv_dim = config.conv_dim[layer_id]
735
+
736
+ self.conv = nn.Conv1d(
737
+ self.in_conv_dim,
738
+ self.out_conv_dim,
739
+ kernel_size=config.conv_kernel[layer_id],
740
+ stride=config.conv_stride[layer_id],
741
+ bias=config.conv_bias,
742
+ )
743
+ self.activation = ACT2FN[config.feat_extract_activation]
744
+
745
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
746
+
747
+ def forward(self, hidden_states):
748
+ hidden_states = self.conv(hidden_states)
749
+ hidden_states = self.layer_norm(hidden_states)
750
+ hidden_states = self.activation(hidden_states)
751
+ return hidden_states
752
+
753
+
754
+ class WavLMFeatureEncoder(nn.Module):
755
+ """Construct the features from raw audio waveform"""
756
+
757
+ def __init__(self, config):
758
+ super().__init__()
759
+
760
+ if config.feat_extract_norm == "group":
761
+ conv_layers = [WavLMGroupNormConvLayer(config, layer_id=0)] + [
762
+ WavLMNoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)
763
+ ]
764
+ elif config.feat_extract_norm == "layer":
765
+ conv_layers = [WavLMLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
766
+ else:
767
+ raise ValueError(
768
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
769
+ )
770
+ self.conv_layers = nn.ModuleList(conv_layers)
771
+ self.gradient_checkpointing = False
772
+ self._requires_grad = True
773
+
774
+ def _freeze_parameters(self):
775
+ for param in self.parameters():
776
+ param.requires_grad = False
777
+ self._requires_grad = False
778
+
779
+ def forward(self, input_values):
780
+ hidden_states = input_values[:, None]
781
+
782
+ # make sure hidden_states require grad for gradient_checkpointing
783
+ if self._requires_grad and self.training:
784
+ hidden_states.requires_grad = True
785
+
786
+ for conv_layer in self.conv_layers:
787
+ hidden_states = conv_layer(hidden_states)
788
+
789
+ return hidden_states
790
+
791
+
792
+ class WavLMAdapterLayer(nn.Module):
793
+ def __init__(self, config):
794
+ super().__init__()
795
+ self.conv = nn.Conv1d(
796
+ config.output_hidden_size,
797
+ 2 * config.output_hidden_size,
798
+ config.adapter_kernel_size,
799
+ stride=config.adapter_stride,
800
+ padding=1,
801
+ )
802
+
803
+ def forward(self, hidden_states):
804
+ hidden_states = self.conv(hidden_states)
805
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
806
+
807
+ return hidden_states
808
+
809
+
810
+ class WavLMAdapter(nn.Module):
811
+ def __init__(self, config):
812
+ super().__init__()
813
+
814
+ # feature dim might need to be down-projected
815
+ if config.output_hidden_size != config.hidden_size:
816
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
817
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)
818
+ else:
819
+ self.proj = self.proj_layer_norm = None
820
+
821
+ self.layers = nn.ModuleList(WavLMAdapterLayer(config) for _ in range(config.num_adapter_layers))
822
+ self.layerdrop = config.layerdrop
823
+
824
+ def forward(self, hidden_states):
825
+ # down project hidden_states if necessary
826
+ if self.proj is not None and self.proj_layer_norm is not None:
827
+ hidden_states = self.proj(hidden_states)
828
+ hidden_states = self.proj_layer_norm(hidden_states)
829
+
830
+ hidden_states = hidden_states.transpose(1, 2)
831
+
832
+ for layer in self.layers:
833
+ layerdrop_prob = np.random.random()
834
+ if not self.training or (layerdrop_prob > self.layerdrop):
835
+ hidden_states = layer(hidden_states)
836
+
837
+ hidden_states = hidden_states.transpose(1, 2)
838
+ return hidden_states
839
+
840
+
841
+ def _compute_mask_indices(
842
+ shape: tuple[int, int],
843
+ mask_prob: float,
844
+ mask_length: int,
845
+ attention_mask: torch.LongTensor | None = None,
846
+ min_masks: int = 0,
847
+ ) -> np.ndarray:
848
+ """
849
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
850
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
851
+ CPU as part of the preprocessing during training.
852
+
853
+ Args:
854
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
855
+ the first element is the batch size and the second element is the length of the axis to span.
856
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
857
+ independently generated mask spans of length `mask_length` is computed by
858
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
859
+ actual percentage will be smaller.
860
+ mask_length: size of the mask
861
+ min_masks: minimum number of masked spans
862
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
863
+ each batch dimension.
864
+ """
865
+ batch_size, sequence_length = shape
866
+
867
+ if mask_length < 1:
868
+ raise ValueError("`mask_length` has to be bigger than 0.")
869
+
870
+ if mask_length > sequence_length:
871
+ raise ValueError(
872
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
873
+ f" and `sequence_length`: {sequence_length}`"
874
+ )
875
+
876
+ # epsilon is used for probabilistic rounding
877
+ epsilon = np.random.rand(1).item()
878
+
879
+ def compute_num_masked_span(input_length):
880
+ """Given input length, compute how many spans should be masked"""
881
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
882
+ num_masked_span = max(num_masked_span, min_masks)
883
+
884
+ # make sure num masked span <= sequence_length
885
+ if num_masked_span * mask_length > sequence_length:
886
+ num_masked_span = sequence_length // mask_length
887
+
888
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
889
+ if input_length - (mask_length - 1) < num_masked_span:
890
+ num_masked_span = max(input_length - (mask_length - 1), 0)
891
+
892
+ return num_masked_span
893
+
894
+ # compute number of masked spans in batch
895
+ input_lengths = (
896
+ attention_mask.detach().sum(-1).tolist()
897
+ if attention_mask is not None
898
+ else [sequence_length for _ in range(batch_size)]
899
+ )
900
+
901
+ # SpecAugment mask to fill
902
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
903
+ spec_aug_mask_idxs = []
904
+
905
+ max_num_masked_span = compute_num_masked_span(sequence_length)
906
+
907
+ if max_num_masked_span == 0:
908
+ return spec_aug_mask
909
+
910
+ for input_length in input_lengths:
911
+ # compute num of masked spans for this input
912
+ num_masked_span = compute_num_masked_span(input_length)
913
+
914
+ # get random indices to mask
915
+ spec_aug_mask_idx = np.random.choice(
916
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
917
+ )
918
+
919
+ # pick first sampled index that will serve as a dummy index to pad vector
920
+ # to ensure same dimension for all batches due to probabilistic rounding
921
+ # Picking first sample just pads those vectors twice.
922
+ if len(spec_aug_mask_idx) == 0:
923
+ # this case can only happen if `input_length` is strictly smaller then
924
+ # `sequence_length` in which case the last token has to be a padding
925
+ # token which we can use as a dummy mask id
926
+ dummy_mask_idx = sequence_length - 1
927
+ else:
928
+ dummy_mask_idx = spec_aug_mask_idx[0]
929
+
930
+ spec_aug_mask_idx = np.concatenate(
931
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
932
+ )
933
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
934
+
935
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
936
+
937
+ # expand masked indices to masked spans
938
+ spec_aug_mask_idxs = np.broadcast_to(
939
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
940
+ )
941
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
942
+
943
+ # add offset to the starting indexes so that indexes now create a span
944
+ offsets = np.arange(mask_length)[None, None, :]
945
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
946
+ batch_size, max_num_masked_span * mask_length
947
+ )
948
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
949
+
950
+ # ensure that we cannot have indices larger than sequence_length
951
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
952
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
953
+
954
+ # scatter indices to mask
955
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
956
+
957
+ return spec_aug_mask
958
+
959
+
960
+ WavLMBaseModelOutput = Wav2Vec2BaseModelOutput
961
+
962
+
963
+ @auto_docstring
964
+ class WavLMModel(WavLMPreTrainedModel):
965
+ def __init__(self, config: WavLMConfig):
966
+ super().__init__(config)
967
+ self.config = config
968
+ self.feature_extractor = WavLMFeatureEncoder(config)
969
+ self.feature_projection = WavLMFeatureProjection(config)
970
+
971
+ # model only needs masking vector if mask prob is > 0.0
972
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
973
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
974
+
975
+ if config.do_stable_layer_norm:
976
+ self.encoder = WavLMEncoderStableLayerNorm(config)
977
+ else:
978
+ self.encoder = WavLMEncoder(config)
979
+
980
+ self.adapter = WavLMAdapter(config) if config.add_adapter else None
981
+
982
+ # Initialize weights and apply final processing
983
+ self.post_init()
984
+
985
+ def freeze_feature_encoder(self):
986
+ """
987
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
988
+ not be updated during training.
989
+ """
990
+ self.feature_extractor._freeze_parameters()
991
+
992
+ def _mask_hidden_states(
993
+ self,
994
+ hidden_states: torch.FloatTensor,
995
+ mask_time_indices: torch.FloatTensor | None = None,
996
+ attention_mask: torch.LongTensor | None = None,
997
+ ):
998
+ """
999
+ Masks extracted features along time axis and/or along feature axis according to
1000
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
1001
+ """
1002
+
1003
+ # `config.apply_spec_augment` can set masking to False
1004
+ if not getattr(self.config, "apply_spec_augment", True):
1005
+ return hidden_states
1006
+
1007
+ # generate indices & apply SpecAugment along time axis
1008
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1009
+
1010
+ if mask_time_indices is not None:
1011
+ # apply SpecAugment along time axis with given mask_time_indices
1012
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1013
+ elif self.config.mask_time_prob > 0 and self.training:
1014
+ mask_time_indices = _compute_mask_indices(
1015
+ (batch_size, sequence_length),
1016
+ mask_prob=self.config.mask_time_prob,
1017
+ mask_length=self.config.mask_time_length,
1018
+ attention_mask=attention_mask,
1019
+ min_masks=self.config.mask_time_min_masks,
1020
+ )
1021
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1022
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1023
+
1024
+ if self.config.mask_feature_prob > 0 and self.training:
1025
+ # generate indices & apply SpecAugment along feature axis
1026
+ mask_feature_indices = _compute_mask_indices(
1027
+ (batch_size, hidden_size),
1028
+ mask_prob=self.config.mask_feature_prob,
1029
+ mask_length=self.config.mask_feature_length,
1030
+ min_masks=self.config.mask_feature_min_masks,
1031
+ )
1032
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1033
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1034
+ hidden_states[mask_feature_indices] = 0
1035
+
1036
+ return hidden_states
1037
+
1038
+ @auto_docstring
1039
+ def forward(
1040
+ self,
1041
+ input_values: torch.Tensor | None,
1042
+ attention_mask: torch.Tensor | None = None,
1043
+ mask_time_indices: torch.FloatTensor | None = None,
1044
+ output_attentions: bool | None = None,
1045
+ output_hidden_states: bool | None = None,
1046
+ return_dict: bool | None = None,
1047
+ **kwargs,
1048
+ ) -> tuple | WavLMBaseModelOutput:
1049
+ r"""
1050
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1051
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1052
+ masked extracted features in *config.proj_codevector_dim* space.
1053
+ """
1054
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1055
+ output_hidden_states = (
1056
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1057
+ )
1058
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1059
+
1060
+ extract_features = self.feature_extractor(input_values)
1061
+ extract_features = extract_features.transpose(1, 2)
1062
+
1063
+ if attention_mask is not None:
1064
+ # compute reduced attention_mask corresponding to feature vectors
1065
+ attention_mask = self._get_feature_vector_attention_mask(
1066
+ extract_features.shape[1], attention_mask, add_adapter=False
1067
+ )
1068
+
1069
+ hidden_states, extract_features = self.feature_projection(extract_features)
1070
+ hidden_states = self._mask_hidden_states(
1071
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1072
+ )
1073
+
1074
+ encoder_outputs = self.encoder(
1075
+ hidden_states,
1076
+ attention_mask=attention_mask,
1077
+ output_attentions=output_attentions,
1078
+ output_hidden_states=output_hidden_states,
1079
+ return_dict=return_dict,
1080
+ )
1081
+
1082
+ hidden_states = encoder_outputs[0]
1083
+
1084
+ if self.adapter is not None:
1085
+ hidden_states = self.adapter(hidden_states)
1086
+
1087
+ if not return_dict:
1088
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1089
+
1090
+ return WavLMBaseModelOutput(
1091
+ last_hidden_state=hidden_states,
1092
+ extract_features=extract_features,
1093
+ hidden_states=encoder_outputs.hidden_states,
1094
+ attentions=encoder_outputs.attentions,
1095
+ )
1096
+
1097
+
1098
+ _HIDDEN_STATES_START_POSITION = 2
1099
+
1100
+
1101
+ @auto_docstring(
1102
+ custom_intro="""
1103
+ WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1104
+ """
1105
+ )
1106
+ class WavLMForCTC(WavLMPreTrainedModel):
1107
+ def __init__(self, config, target_lang: str | None = None):
1108
+ r"""
1109
+ target_lang (`str`, *optional*):
1110
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1111
+ adapter.<lang>.bin. Only relevant when using an instance of [`WavLMForCTC`] with adapters. Uses 'eng' by
1112
+ default.
1113
+ """
1114
+ super().__init__(config)
1115
+
1116
+ self.wavlm = WavLMModel(config)
1117
+ self.dropout = nn.Dropout(config.final_dropout)
1118
+
1119
+ self.target_lang = target_lang
1120
+
1121
+ if config.vocab_size is None:
1122
+ raise ValueError(
1123
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1124
+ "does not define the vocabulary size of the language model head. Please "
1125
+ "instantiate the model as follows: `WavLMForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1126
+ "or define `vocab_size` of your model's configuration."
1127
+ )
1128
+ output_hidden_size = (
1129
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1130
+ )
1131
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1132
+
1133
+ # Initialize weights and apply final processing
1134
+ self.post_init()
1135
+
1136
+ def tie_weights(self, **kwargs):
1137
+ """
1138
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
1139
+ passing `target_lang=...` to `from_pretrained(...)`.
1140
+
1141
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
1142
+ """
1143
+
1144
+ if get_torch_context_manager_or_global_device() == torch.device("meta"):
1145
+ return
1146
+
1147
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
1148
+ # correctly load adapter layers for WavLM so that we do not have to introduce a new API to
1149
+ # [`PreTrainedModel`]. While slightly hacky, WavLM never has to tie input and output embeddings, so that it is
1150
+ # ok to repurpose this function here.
1151
+ target_lang = self.target_lang
1152
+
1153
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
1154
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
1155
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
1156
+ logger.info("By default `target_lang` is set to 'eng'.")
1157
+ elif target_lang is not None:
1158
+ self.load_adapter(target_lang, force_load=True)
1159
+
1160
+ def freeze_feature_encoder(self):
1161
+ """
1162
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1163
+ not be updated during training.
1164
+ """
1165
+ self.wavlm.feature_extractor._freeze_parameters()
1166
+
1167
+ def freeze_base_model(self):
1168
+ """
1169
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1170
+ be updated during training. Only the classification head will be updated.
1171
+ """
1172
+ for param in self.wavlm.parameters():
1173
+ param.requires_grad = False
1174
+
1175
+ @auto_docstring
1176
+ def forward(
1177
+ self,
1178
+ input_values: torch.Tensor | None,
1179
+ attention_mask: torch.Tensor | None = None,
1180
+ output_attentions: bool | None = None,
1181
+ output_hidden_states: bool | None = None,
1182
+ return_dict: bool | None = None,
1183
+ labels: torch.Tensor | None = None,
1184
+ **kwargs,
1185
+ ) -> tuple | CausalLMOutput:
1186
+ r"""
1187
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1188
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1189
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1190
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1191
+ config.vocab_size - 1]`.
1192
+ """
1193
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1194
+
1195
+ if labels is not None and labels.max() >= self.config.vocab_size:
1196
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1197
+
1198
+ outputs = self.wavlm(
1199
+ input_values,
1200
+ attention_mask=attention_mask,
1201
+ output_attentions=output_attentions,
1202
+ output_hidden_states=output_hidden_states,
1203
+ return_dict=return_dict,
1204
+ )
1205
+
1206
+ hidden_states = outputs[0]
1207
+ hidden_states = self.dropout(hidden_states)
1208
+
1209
+ logits = self.lm_head(hidden_states)
1210
+
1211
+ loss = None
1212
+ if labels is not None:
1213
+ # retrieve loss input_lengths from attention_mask
1214
+ attention_mask = (
1215
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1216
+ )
1217
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1218
+
1219
+ # assuming that padded tokens are filled with -100
1220
+ # when not being attended to
1221
+ labels_mask = labels >= 0
1222
+ target_lengths = labels_mask.sum(-1)
1223
+ flattened_targets = labels.masked_select(labels_mask)
1224
+
1225
+ # ctc_loss doesn't support fp16
1226
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1227
+
1228
+ with torch.backends.cudnn.flags(enabled=False):
1229
+ loss = nn.functional.ctc_loss(
1230
+ log_probs,
1231
+ flattened_targets,
1232
+ input_lengths,
1233
+ target_lengths,
1234
+ blank=self.config.pad_token_id,
1235
+ reduction=self.config.ctc_loss_reduction,
1236
+ zero_infinity=self.config.ctc_zero_infinity,
1237
+ )
1238
+
1239
+ if not return_dict:
1240
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1241
+ return ((loss,) + output) if loss is not None else output
1242
+
1243
+ return CausalLMOutput(
1244
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1245
+ )
1246
+
1247
+
1248
+ @auto_docstring(
1249
+ custom_intro="""
1250
+ WavLM Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1251
+ SUPERB Keyword Spotting.
1252
+ """
1253
+ )
1254
+ class WavLMForSequenceClassification(WavLMPreTrainedModel):
1255
+ def __init__(self, config):
1256
+ super().__init__(config)
1257
+
1258
+ if hasattr(config, "add_adapter") and config.add_adapter:
1259
+ raise ValueError(
1260
+ "Sequence classification does not support the use of WavLM adapters (config.add_adapter=True)"
1261
+ )
1262
+ self.wavlm = WavLMModel(config)
1263
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1264
+ if config.use_weighted_layer_sum:
1265
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1266
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1267
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1268
+
1269
+ # Initialize weights and apply final processing
1270
+ self.post_init()
1271
+
1272
+ def freeze_feature_encoder(self):
1273
+ """
1274
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1275
+ not be updated during training.
1276
+ """
1277
+ self.wavlm.feature_extractor._freeze_parameters()
1278
+
1279
+ def freeze_base_model(self):
1280
+ """
1281
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1282
+ be updated during training. Only the classification head will be updated.
1283
+ """
1284
+ for param in self.wavlm.parameters():
1285
+ param.requires_grad = False
1286
+
1287
+ @auto_docstring
1288
+ def forward(
1289
+ self,
1290
+ input_values: torch.Tensor | None,
1291
+ attention_mask: torch.Tensor | None = None,
1292
+ output_attentions: bool | None = None,
1293
+ output_hidden_states: bool | None = None,
1294
+ return_dict: bool | None = None,
1295
+ labels: torch.Tensor | None = None,
1296
+ **kwargs,
1297
+ ) -> tuple | SequenceClassifierOutput:
1298
+ r"""
1299
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1300
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1301
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1302
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1303
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1304
+ into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details.
1305
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1306
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1307
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1308
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1309
+ """
1310
+
1311
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1312
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1313
+
1314
+ outputs = self.wavlm(
1315
+ input_values,
1316
+ attention_mask=attention_mask,
1317
+ output_attentions=output_attentions,
1318
+ output_hidden_states=output_hidden_states,
1319
+ return_dict=return_dict,
1320
+ )
1321
+
1322
+ if self.config.use_weighted_layer_sum:
1323
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1324
+ hidden_states = torch.stack(hidden_states, dim=1)
1325
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1326
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1327
+ else:
1328
+ hidden_states = outputs[0]
1329
+
1330
+ hidden_states = self.projector(hidden_states)
1331
+ if attention_mask is None:
1332
+ pooled_output = hidden_states.mean(dim=1)
1333
+ else:
1334
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1335
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1336
+ hidden_states[~expand_padding_mask] = 0.0
1337
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1338
+
1339
+ logits = self.classifier(pooled_output)
1340
+
1341
+ loss = None
1342
+ if labels is not None:
1343
+ loss_fct = CrossEntropyLoss()
1344
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1345
+
1346
+ if not return_dict:
1347
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1348
+ return ((loss,) + output) if loss is not None else output
1349
+
1350
+ return SequenceClassifierOutput(
1351
+ loss=loss,
1352
+ logits=logits,
1353
+ hidden_states=outputs.hidden_states,
1354
+ attentions=outputs.attentions,
1355
+ )
1356
+
1357
+
1358
+ @auto_docstring
1359
+ class WavLMForAudioFrameClassification(WavLMPreTrainedModel):
1360
+ def __init__(self, config):
1361
+ super().__init__(config)
1362
+
1363
+ if hasattr(config, "add_adapter") and config.add_adapter:
1364
+ raise ValueError(
1365
+ "Audio frame classification does not support the use of WavLM adapters (config.add_adapter=True)"
1366
+ )
1367
+ self.wavlm = WavLMModel(config)
1368
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1369
+ if config.use_weighted_layer_sum:
1370
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1371
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1372
+ self.num_labels = config.num_labels
1373
+
1374
+ self.post_init()
1375
+
1376
+ def freeze_feature_encoder(self):
1377
+ """
1378
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1379
+ not be updated during training.
1380
+ """
1381
+ self.wavlm.feature_extractor._freeze_parameters()
1382
+
1383
+ def freeze_base_model(self):
1384
+ """
1385
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1386
+ be updated during training. Only the classification head will be updated.
1387
+ """
1388
+ for param in self.wavlm.parameters():
1389
+ param.requires_grad = False
1390
+
1391
+ @auto_docstring
1392
+ def forward(
1393
+ self,
1394
+ input_values: torch.Tensor | None,
1395
+ attention_mask: torch.Tensor | None = None,
1396
+ labels: torch.Tensor | None = None,
1397
+ output_attentions: bool | None = None,
1398
+ output_hidden_states: bool | None = None,
1399
+ return_dict: bool | None = None,
1400
+ **kwargs,
1401
+ ) -> tuple | TokenClassifierOutput:
1402
+ r"""
1403
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1404
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1405
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1406
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1407
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1408
+ into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details.
1409
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1410
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1411
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1412
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1413
+ """
1414
+
1415
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1416
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1417
+
1418
+ outputs = self.wavlm(
1419
+ input_values,
1420
+ attention_mask=attention_mask,
1421
+ output_attentions=output_attentions,
1422
+ output_hidden_states=output_hidden_states,
1423
+ return_dict=return_dict,
1424
+ )
1425
+
1426
+ if self.config.use_weighted_layer_sum:
1427
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1428
+ hidden_states = torch.stack(hidden_states, dim=1)
1429
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1430
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1431
+ else:
1432
+ hidden_states = outputs[0]
1433
+
1434
+ logits = self.classifier(hidden_states)
1435
+
1436
+ loss = None
1437
+ if labels is not None:
1438
+ loss_fct = CrossEntropyLoss()
1439
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
1440
+
1441
+ if not return_dict:
1442
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1443
+ return output
1444
+
1445
+ return TokenClassifierOutput(
1446
+ loss=loss,
1447
+ logits=logits,
1448
+ hidden_states=outputs.hidden_states,
1449
+ attentions=outputs.attentions,
1450
+ )
1451
+
1452
+
1453
+ class AMSoftmaxLoss(nn.Module):
1454
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
1455
+ super().__init__()
1456
+ self.scale = scale
1457
+ self.margin = margin
1458
+ self.num_labels = num_labels
1459
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
1460
+ self.loss = nn.CrossEntropyLoss()
1461
+
1462
+ def forward(self, hidden_states, labels):
1463
+ labels = labels.flatten()
1464
+ weight = nn.functional.normalize(self.weight, dim=0)
1465
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
1466
+ cos_theta = torch.mm(hidden_states, weight)
1467
+ psi = cos_theta - self.margin
1468
+
1469
+ onehot = nn.functional.one_hot(labels, self.num_labels)
1470
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
1471
+ loss = self.loss(logits, labels)
1472
+
1473
+ return loss
1474
+
1475
+
1476
+ class TDNNLayer(nn.Module):
1477
+ def __init__(self, config, layer_id=0):
1478
+ super().__init__()
1479
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
1480
+ self.out_conv_dim = config.tdnn_dim[layer_id]
1481
+ self.kernel_size = config.tdnn_kernel[layer_id]
1482
+ self.dilation = config.tdnn_dilation[layer_id]
1483
+
1484
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
1485
+ self.activation = nn.ReLU()
1486
+
1487
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1488
+ if is_peft_available():
1489
+ from peft.tuners.lora import LoraLayer
1490
+
1491
+ if is_peft_available():
1492
+ if isinstance(self.kernel, LoraLayer):
1493
+ warnings.warn(
1494
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
1495
+ "You should exclude TDNNLayer from LoRA's target modules.",
1496
+ )
1497
+
1498
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
1499
+ hidden_states = hidden_states.transpose(1, 2)
1500
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
1501
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
1502
+ hidden_states = hidden_states.transpose(1, 2)
1503
+
1504
+ hidden_states = self.activation(hidden_states)
1505
+ return hidden_states
1506
+
1507
+
1508
+ @auto_docstring(
1509
+ custom_intro="""
1510
+ WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.
1511
+ """
1512
+ )
1513
+ class WavLMForXVector(WavLMPreTrainedModel):
1514
+ def __init__(self, config):
1515
+ super().__init__(config)
1516
+
1517
+ self.wavlm = WavLMModel(config)
1518
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1519
+ if config.use_weighted_layer_sum:
1520
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1521
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
1522
+
1523
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
1524
+ self.tdnn = nn.ModuleList(tdnn_layers)
1525
+
1526
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
1527
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
1528
+
1529
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
1530
+
1531
+ self.post_init()
1532
+
1533
+ def freeze_feature_encoder(self):
1534
+ """
1535
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1536
+ not be updated during training.
1537
+ """
1538
+ self.wavlm.feature_extractor._freeze_parameters()
1539
+
1540
+ def freeze_base_model(self):
1541
+ """
1542
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1543
+ be updated during training. Only the classification head will be updated.
1544
+ """
1545
+ for param in self.wavlm.parameters():
1546
+ param.requires_grad = False
1547
+
1548
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
1549
+ """
1550
+ Computes the output length of the TDNN layers
1551
+ """
1552
+
1553
+ def _conv_out_length(input_length, kernel_size, stride):
1554
+ # 1D convolutional layer output length formula taken
1555
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1556
+ return (input_length - kernel_size) // stride + 1
1557
+
1558
+ for kernel_size in self.config.tdnn_kernel:
1559
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
1560
+
1561
+ return input_lengths
1562
+
1563
+ @auto_docstring
1564
+ def forward(
1565
+ self,
1566
+ input_values: torch.Tensor | None,
1567
+ attention_mask: torch.Tensor | None = None,
1568
+ output_attentions: bool | None = None,
1569
+ output_hidden_states: bool | None = None,
1570
+ return_dict: bool | None = None,
1571
+ labels: torch.Tensor | None = None,
1572
+ **kwargs,
1573
+ ) -> tuple | XVectorOutput:
1574
+ r"""
1575
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1576
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1577
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1578
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1579
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1580
+ into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details.
1581
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1582
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1583
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1584
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1585
+ """
1586
+
1587
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1588
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1589
+
1590
+ outputs = self.wavlm(
1591
+ input_values,
1592
+ attention_mask=attention_mask,
1593
+ output_attentions=output_attentions,
1594
+ output_hidden_states=output_hidden_states,
1595
+ return_dict=return_dict,
1596
+ )
1597
+
1598
+ if self.config.use_weighted_layer_sum:
1599
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1600
+ hidden_states = torch.stack(hidden_states, dim=1)
1601
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1602
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1603
+ else:
1604
+ hidden_states = outputs[0]
1605
+
1606
+ hidden_states = self.projector(hidden_states)
1607
+
1608
+ for tdnn_layer in self.tdnn:
1609
+ hidden_states = tdnn_layer(hidden_states)
1610
+
1611
+ # Statistic Pooling
1612
+ if attention_mask is None:
1613
+ mean_features = hidden_states.mean(dim=1)
1614
+ std_features = hidden_states.std(dim=1)
1615
+ else:
1616
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
1617
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
1618
+ mean_features = []
1619
+ std_features = []
1620
+ for i, length in enumerate(tdnn_output_lengths):
1621
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
1622
+ std_features.append(hidden_states[i, :length].std(dim=0))
1623
+ mean_features = torch.stack(mean_features)
1624
+ std_features = torch.stack(std_features)
1625
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
1626
+
1627
+ output_embeddings = self.feature_extractor(statistic_pooling)
1628
+ logits = self.classifier(output_embeddings)
1629
+
1630
+ loss = None
1631
+ if labels is not None:
1632
+ loss = self.objective(logits, labels)
1633
+
1634
+ if not return_dict:
1635
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
1636
+ return ((loss,) + output) if loss is not None else output
1637
+
1638
+ return XVectorOutput(
1639
+ loss=loss,
1640
+ logits=logits,
1641
+ embeddings=output_embeddings,
1642
+ hidden_states=outputs.hidden_states,
1643
+ attentions=outputs.attentions,
1644
+ )
1645
+
1646
+
1647
+ __all__ = [
1648
+ "WavLMForAudioFrameClassification",
1649
+ "WavLMForCTC",
1650
+ "WavLMForSequenceClassification",
1651
+ "WavLMForXVector",
1652
+ "WavLMModel",
1653
+ "WavLMPreTrainedModel",
1654
+ ]
.venv/lib/python3.12/site-packages/transformers/models/wavlm/modular_wavlm.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from ... import initialization as init
8
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
9
+ from ...integrations.fsdp import is_fsdp_managed_module
10
+ from ...modeling_layers import GradientCheckpointingLayer
11
+ from ...modeling_outputs import BaseModelOutput, Wav2Vec2BaseModelOutput
12
+ from ...modeling_utils import PreTrainedModel
13
+ from ...utils import logging
14
+ from ..wav2vec2.modeling_wav2vec2 import (
15
+ Wav2Vec2FeatureProjection,
16
+ Wav2Vec2FeedForward,
17
+ Wav2Vec2ForAudioFrameClassification,
18
+ Wav2Vec2ForCTC,
19
+ Wav2Vec2ForSequenceClassification,
20
+ Wav2Vec2ForXVector,
21
+ Wav2Vec2Model,
22
+ Wav2Vec2PositionalConvEmbedding,
23
+ Wav2Vec2PreTrainedModel,
24
+ )
25
+ from .configuration_wavlm import WavLMConfig
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class WavLMPositionalConvEmbedding(Wav2Vec2PositionalConvEmbedding):
32
+ pass
33
+
34
+
35
+ class WavLMFeatureProjection(Wav2Vec2FeatureProjection):
36
+ pass
37
+
38
+
39
+ class WavLMAttention(nn.Module):
40
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
41
+
42
+ def __init__(
43
+ self,
44
+ embed_dim: int,
45
+ num_heads: int,
46
+ dropout: float | int = 0.0,
47
+ num_buckets: int = 320,
48
+ max_distance: int = 800,
49
+ has_relative_position_bias: bool = True,
50
+ ):
51
+ super().__init__()
52
+ self.embed_dim = embed_dim
53
+ self.num_heads = num_heads
54
+ self.dropout = dropout
55
+ self.head_dim = embed_dim // num_heads
56
+
57
+ if (self.head_dim * num_heads) != self.embed_dim:
58
+ raise ValueError(
59
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
60
+ f" and `num_heads`: {num_heads})."
61
+ )
62
+ self.scaling = self.head_dim**-0.5
63
+
64
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
66
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
67
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
68
+
69
+ self.num_buckets = num_buckets
70
+ self.max_distance = max_distance
71
+
72
+ self.gru_rel_pos_const = nn.Parameter(torch.ones(1, self.num_heads, 1, 1))
73
+ self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)
74
+
75
+ if has_relative_position_bias:
76
+ self.rel_attn_embed = nn.Embedding(self.num_buckets, self.num_heads)
77
+
78
+ def forward(
79
+ self,
80
+ hidden_states: torch.Tensor,
81
+ attention_mask: torch.Tensor | None = None,
82
+ position_bias: torch.Tensor | None = None,
83
+ output_attentions: bool = False,
84
+ index=0,
85
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
86
+ """Attention layer with relative attention"""
87
+ bsz, tgt_len, _ = hidden_states.size()
88
+
89
+ # first pass of attention layer creates position bias
90
+ if position_bias is None:
91
+ position_bias = self.compute_bias(tgt_len, tgt_len)
92
+ position_bias = (
93
+ position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, tgt_len)
94
+ )
95
+
96
+ # Compute relative position bias:
97
+ # 1) get reshape hidden_states
98
+ gated_hidden_states = hidden_states.view(hidden_states.shape[:-1] + (self.num_heads, -1))
99
+ gated_hidden_states = gated_hidden_states.permute(0, 2, 1, 3)
100
+
101
+ # 2) project hidden states
102
+ relative_position_proj = self.gru_rel_pos_linear(gated_hidden_states)
103
+ relative_position_proj = relative_position_proj.view(gated_hidden_states.shape[:-1] + (2, 4)).sum(-1)
104
+
105
+ # 3) compute gate for position bias from projected hidden states
106
+ gate_a, gate_b = torch.sigmoid(relative_position_proj).chunk(2, dim=-1)
107
+ gate_output = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0
108
+
109
+ # 4) apply gate to position bias to compute gated position_bias
110
+ gated_position_bias = gate_output.view(bsz * self.num_heads, -1, 1) * position_bias
111
+ gated_position_bias = gated_position_bias.view((-1, tgt_len, tgt_len))
112
+
113
+ attn_output, attn_weights = self.torch_multi_head_self_attention(
114
+ hidden_states, attention_mask, gated_position_bias, output_attentions
115
+ )
116
+
117
+ return attn_output, attn_weights, position_bias
118
+
119
+ def torch_multi_head_self_attention(
120
+ self,
121
+ hidden_states: torch.FloatTensor,
122
+ attention_mask: torch.LongTensor | torch.BoolTensor,
123
+ gated_position_bias: torch.FloatTensor,
124
+ output_attentions: bool,
125
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor]:
126
+ """simple wrapper around torch's multi_head_attention_forward function"""
127
+ # self-attention assumes q = k = v
128
+ query = key = value = hidden_states.transpose(0, 1)
129
+ key_padding_mask = attention_mask.ne(1) if attention_mask is not None else None
130
+
131
+ # disable bias and add_zero_attn
132
+ bias_k = bias_v = None
133
+ add_zero_attn = False
134
+
135
+ # PyTorch 1.3.0 has F.multi_head_attention_forward defined
136
+ # so no problem with backwards compatibility
137
+ attn_output, attn_weights = F.multi_head_attention_forward(
138
+ query,
139
+ key,
140
+ value,
141
+ self.embed_dim,
142
+ self.num_heads,
143
+ torch.empty([0]),
144
+ torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
145
+ bias_k,
146
+ bias_v,
147
+ add_zero_attn,
148
+ self.dropout,
149
+ self.out_proj.weight,
150
+ self.out_proj.bias,
151
+ self.training,
152
+ key_padding_mask,
153
+ output_attentions,
154
+ gated_position_bias,
155
+ use_separate_proj_weight=True,
156
+ q_proj_weight=self.q_proj.weight,
157
+ k_proj_weight=self.k_proj.weight,
158
+ v_proj_weight=self.v_proj.weight,
159
+ )
160
+
161
+ # [Seq_Len, Batch Size, ...] -> [Batch Size, Seq_Len, ...]
162
+ attn_output = attn_output.transpose(0, 1)
163
+
164
+ if attn_weights is not None:
165
+ # IMPORTANT: Attention weights are averaged weights
166
+ # here which should not be the case. This is an open issue
167
+ # on PyTorch: https://github.com/pytorch/pytorch/issues/32590
168
+ attn_weights = attn_weights[:, None].broadcast_to(
169
+ attn_weights.shape[:1] + (self.num_heads,) + attn_weights.shape[1:]
170
+ )
171
+
172
+ return attn_output, attn_weights
173
+
174
+ def compute_bias(self, query_length: int, key_length: int) -> torch.FloatTensor:
175
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
176
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
177
+ relative_position = memory_position - context_position
178
+ relative_position_bucket = self._relative_positions_bucket(relative_position)
179
+ relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)
180
+ values = self.rel_attn_embed(relative_position_bucket)
181
+ values = values.permute([2, 0, 1])
182
+ return values
183
+
184
+ def _relative_positions_bucket(self, relative_positions: torch.FloatTensor) -> torch.FloatTensor:
185
+ num_buckets = self.num_buckets // 2
186
+
187
+ relative_buckets = (relative_positions > 0).to(torch.long) * num_buckets
188
+ relative_positions = torch.abs(relative_positions)
189
+
190
+ max_exact = num_buckets // 2
191
+ is_small = relative_positions < max_exact
192
+
193
+ relative_positions_if_large = torch.log(relative_positions.float() / max_exact)
194
+ relative_positions_if_large = relative_positions_if_large / math.log(self.max_distance / max_exact)
195
+ relative_positions_if_large = relative_positions_if_large * (num_buckets - max_exact)
196
+ relative_position_if_large = (max_exact + relative_positions_if_large).to(torch.long)
197
+ relative_position_if_large = torch.min(
198
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
199
+ )
200
+
201
+ relative_buckets += torch.where(is_small, relative_positions, relative_position_if_large)
202
+ return relative_buckets
203
+
204
+
205
+ class WavLMFeedForward(Wav2Vec2FeedForward):
206
+ pass
207
+
208
+
209
+ class WavLMEncoderLayer(GradientCheckpointingLayer):
210
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
211
+ super().__init__()
212
+ self.attention = WavLMAttention(
213
+ embed_dim=config.hidden_size,
214
+ num_heads=config.num_attention_heads,
215
+ dropout=config.attention_dropout,
216
+ num_buckets=config.num_buckets,
217
+ max_distance=config.max_bucket_distance,
218
+ has_relative_position_bias=has_relative_position_bias,
219
+ )
220
+ self.dropout = nn.Dropout(config.hidden_dropout)
221
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
222
+ self.feed_forward = WavLMFeedForward(config)
223
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
224
+
225
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False, index=0):
226
+ attn_residual = hidden_states
227
+ hidden_states, attn_weights, position_bias = self.attention(
228
+ hidden_states,
229
+ attention_mask=attention_mask,
230
+ position_bias=position_bias,
231
+ output_attentions=output_attentions,
232
+ index=index,
233
+ )
234
+ hidden_states = self.dropout(hidden_states)
235
+ hidden_states = attn_residual + hidden_states
236
+
237
+ hidden_states = self.layer_norm(hidden_states)
238
+
239
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
240
+ hidden_states = self.final_layer_norm(hidden_states)
241
+
242
+ outputs = (hidden_states, position_bias)
243
+
244
+ if output_attentions:
245
+ outputs += (attn_weights,)
246
+
247
+ return outputs
248
+
249
+
250
+ class WavLMEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
251
+ def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
252
+ super().__init__()
253
+ self.attention = WavLMAttention(
254
+ embed_dim=config.hidden_size,
255
+ num_heads=config.num_attention_heads,
256
+ dropout=config.attention_dropout,
257
+ num_buckets=config.num_buckets,
258
+ max_distance=config.max_bucket_distance,
259
+ has_relative_position_bias=has_relative_position_bias,
260
+ )
261
+ self.dropout = nn.Dropout(config.hidden_dropout)
262
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
263
+ self.feed_forward = WavLMFeedForward(config)
264
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
265
+
266
+ def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False):
267
+ attn_residual = hidden_states
268
+ hidden_states = self.layer_norm(hidden_states)
269
+ hidden_states, attn_weights, position_bias = self.attention(
270
+ hidden_states,
271
+ attention_mask=attention_mask,
272
+ position_bias=position_bias,
273
+ output_attentions=output_attentions,
274
+ )
275
+ hidden_states = self.dropout(hidden_states)
276
+ hidden_states = attn_residual + hidden_states
277
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
278
+
279
+ outputs = (hidden_states, position_bias)
280
+
281
+ if output_attentions:
282
+ outputs += (attn_weights,)
283
+
284
+ return outputs
285
+
286
+
287
+ class WavLMEncoder(nn.Module):
288
+ def __init__(self, config):
289
+ super().__init__()
290
+ self.config = config
291
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
292
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
293
+ self.dropout = nn.Dropout(config.hidden_dropout)
294
+ self.layers = nn.ModuleList(
295
+ [WavLMEncoderLayer(config, has_relative_position_bias=(i == 0)) for i in range(config.num_hidden_layers)]
296
+ )
297
+ self.gradient_checkpointing = False
298
+
299
+ def forward(
300
+ self,
301
+ hidden_states,
302
+ attention_mask=None,
303
+ output_attentions=False,
304
+ output_hidden_states=False,
305
+ return_dict=True,
306
+ ):
307
+ all_hidden_states = () if output_hidden_states else None
308
+ all_self_attentions = () if output_attentions else None
309
+
310
+ if attention_mask is not None:
311
+ # make sure padded tokens output 0
312
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
313
+ hidden_states[~expand_attention_mask] = 0
314
+
315
+ position_embeddings = self.pos_conv_embed(hidden_states)
316
+ hidden_states = hidden_states + position_embeddings
317
+ hidden_states = self.layer_norm(hidden_states)
318
+ hidden_states = self.dropout(hidden_states)
319
+
320
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
321
+ position_bias = None
322
+
323
+ for i, layer in enumerate(self.layers):
324
+ if output_hidden_states:
325
+ all_hidden_states = all_hidden_states + (hidden_states,)
326
+
327
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
328
+ dropout_probability = torch.rand([])
329
+
330
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
331
+ if not skip_the_layer or synced_gpus:
332
+ # under fsdp or deepspeed zero3 all gpus must run in sync
333
+ layer_outputs = layer(
334
+ hidden_states,
335
+ attention_mask=attention_mask,
336
+ position_bias=position_bias,
337
+ output_attentions=output_attentions,
338
+ index=i,
339
+ )
340
+
341
+ hidden_states, position_bias = layer_outputs[:2]
342
+
343
+ if skip_the_layer:
344
+ layer_outputs = (None, None, None)
345
+
346
+ if output_attentions:
347
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
348
+
349
+ if output_hidden_states:
350
+ all_hidden_states = all_hidden_states + (hidden_states,)
351
+
352
+ if not return_dict:
353
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
354
+ return BaseModelOutput(
355
+ last_hidden_state=hidden_states,
356
+ hidden_states=all_hidden_states,
357
+ attentions=all_self_attentions,
358
+ )
359
+
360
+
361
+ class WavLMEncoderStableLayerNorm(nn.Module):
362
+ def __init__(self, config):
363
+ super().__init__()
364
+ self.config = config
365
+ self.pos_conv_embed = WavLMPositionalConvEmbedding(config)
366
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
367
+ self.dropout = nn.Dropout(config.hidden_dropout)
368
+ self.layers = nn.ModuleList(
369
+ [
370
+ WavLMEncoderLayerStableLayerNorm(config, has_relative_position_bias=(i == 0))
371
+ for i in range(config.num_hidden_layers)
372
+ ]
373
+ )
374
+ self.gradient_checkpointing = False
375
+
376
+ def forward(
377
+ self,
378
+ hidden_states,
379
+ attention_mask=None,
380
+ output_attentions=False,
381
+ output_hidden_states=False,
382
+ return_dict=True,
383
+ ):
384
+ all_hidden_states = () if output_hidden_states else None
385
+ all_self_attentions = () if output_attentions else None
386
+
387
+ if attention_mask is not None:
388
+ # make sure padded tokens are not attended to
389
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
390
+ hidden_states[~expand_attention_mask] = 0
391
+
392
+ position_embeddings = self.pos_conv_embed(hidden_states)
393
+ hidden_states = hidden_states + position_embeddings
394
+ hidden_states = self.dropout(hidden_states)
395
+
396
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
397
+ position_bias = None
398
+
399
+ for i, layer in enumerate(self.layers):
400
+ if output_hidden_states:
401
+ all_hidden_states = all_hidden_states + (hidden_states,)
402
+
403
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
404
+ dropout_probability = torch.rand([])
405
+
406
+ skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)
407
+ if not skip_the_layer or synced_gpus:
408
+ # under fsdp or deepspeed zero3 all gpus must run in sync
409
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
410
+ layer_outputs = layer(
411
+ hidden_states,
412
+ attention_mask=attention_mask,
413
+ output_attentions=output_attentions,
414
+ position_bias=position_bias,
415
+ )
416
+ hidden_states, position_bias = layer_outputs[:2]
417
+
418
+ if skip_the_layer:
419
+ layer_outputs = (None, None, None)
420
+
421
+ if output_attentions:
422
+ all_self_attentions = all_self_attentions + (layer_outputs[2],)
423
+
424
+ hidden_states = self.layer_norm(hidden_states)
425
+
426
+ if output_hidden_states:
427
+ all_hidden_states = all_hidden_states + (hidden_states,)
428
+
429
+ if not return_dict:
430
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
431
+ return BaseModelOutput(
432
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
433
+ )
434
+
435
+
436
+ class WavLMGumbelVectorQuantizer(nn.Module):
437
+ """
438
+ Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
439
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
440
+ """
441
+
442
+ def __init__(self, config):
443
+ super().__init__()
444
+ self.num_groups = config.num_codevector_groups
445
+ self.num_vars = config.num_codevectors_per_group
446
+
447
+ if config.codevector_dim % self.num_groups != 0:
448
+ raise ValueError(
449
+ f"`config.codevector_dim {config.codevector_dim} must be divisible"
450
+ f" by `config.num_codevector_groups` {self.num_groups} "
451
+ "for concatenation."
452
+ )
453
+
454
+ # storage for codebook variables (codewords)
455
+ self.codevectors = nn.Parameter(
456
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
457
+ )
458
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
459
+
460
+ # can be decayed for training
461
+ self.temperature = 2
462
+
463
+ @staticmethod
464
+ def _compute_perplexity(probs):
465
+ marginal_probs = probs.mean(dim=0)
466
+ perplexity = torch.exp(-torch.sum(torch.xlogy(marginal_probs, marginal_probs), dim=-1)).sum()
467
+ return perplexity
468
+
469
+ def forward(self, hidden_states):
470
+ batch_size, sequence_length, hidden_size = hidden_states.shape
471
+
472
+ # project to codevector dim
473
+ hidden_states = self.weight_proj(hidden_states)
474
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
475
+
476
+ if self.training:
477
+ # sample code vector probs via gumbel in differentiateable way
478
+ codevector_probs = nn.functional.gumbel_softmax(hidden_states.float(), tau=self.temperature, hard=True)
479
+ codevector_probs = codevector_probs.type_as(hidden_states)
480
+
481
+ # compute perplexity
482
+ codevector_soft_dist = torch.softmax(
483
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
484
+ )
485
+ perplexity = self._compute_perplexity(codevector_soft_dist)
486
+ else:
487
+ # take argmax in non-differentiable way
488
+ # comptute hard codevector distribution (one hot)
489
+ codevector_idx = hidden_states.argmax(dim=-1)
490
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
491
+ -1, codevector_idx.view(-1, 1), 1.0
492
+ )
493
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
494
+
495
+ perplexity = self._compute_perplexity(codevector_probs)
496
+
497
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
498
+ # use probs to retrieve codevectors
499
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
500
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
501
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
502
+
503
+ return codevectors, perplexity
504
+
505
+
506
+ class WavLMPreTrainedModel(PreTrainedModel, Wav2Vec2PreTrainedModel):
507
+ config: WavLMConfig
508
+ base_model_prefix = "wavlm"
509
+ main_input_name = "input_values"
510
+ input_modalities = "audio"
511
+ supports_gradient_checkpointing = True
512
+ _supports_flash_attn = False
513
+ _supports_sdpa = False
514
+ _supports_flex_attn = False
515
+
516
+ @torch.no_grad()
517
+ def _init_weights(self, module):
518
+ """Initialize the weights"""
519
+ # gumbel softmax requires special init
520
+ if isinstance(module, WavLMGumbelVectorQuantizer):
521
+ init.normal_(module.weight_proj.weight, mean=0.0, std=1)
522
+ init.zeros_(module.weight_proj.bias)
523
+ init.uniform_(module.codevectors)
524
+ elif isinstance(module, WavLMPositionalConvEmbedding):
525
+ init.normal_(
526
+ module.conv.weight,
527
+ mean=0,
528
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
529
+ )
530
+ init.constant_(module.conv.bias, 0)
531
+ elif isinstance(module, WavLMFeatureProjection):
532
+ k = math.sqrt(1 / module.projection.in_features)
533
+ init.uniform_(module.projection.weight, a=-k, b=k)
534
+ init.uniform_(module.projection.bias, a=-k, b=k)
535
+ elif isinstance(module, nn.Linear):
536
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
537
+
538
+ if module.bias is not None:
539
+ init.zeros_(module.bias)
540
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
541
+ init.zeros_(module.bias)
542
+ init.ones_(module.weight)
543
+ elif isinstance(module, nn.Conv1d):
544
+ init.kaiming_normal_(module.weight)
545
+
546
+ if module.bias is not None:
547
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
548
+ init.uniform_(module.bias, a=-k, b=k)
549
+
550
+ def _get_adapters(self):
551
+ raise AttributeError("Not needed for WavLM")
552
+
553
+ def init_adapter_layers(self):
554
+ raise AttributeError("Not needed for WavLM")
555
+
556
+ def load_adapter(self):
557
+ raise AttributeError("Not needed for WavLM")
558
+
559
+
560
+ WavLMBaseModelOutput = Wav2Vec2BaseModelOutput
561
+
562
+
563
+ class WavLMModel(Wav2Vec2Model):
564
+ pass
565
+
566
+
567
+ class WavLMForCTC(Wav2Vec2ForCTC):
568
+ pass
569
+
570
+
571
+ class WavLMForSequenceClassification(Wav2Vec2ForSequenceClassification):
572
+ pass
573
+
574
+
575
+ class WavLMForAudioFrameClassification(Wav2Vec2ForAudioFrameClassification):
576
+ pass
577
+
578
+
579
+ class WavLMForXVector(Wav2Vec2ForXVector):
580
+ pass
581
+
582
+
583
+ __all__ = [
584
+ "WavLMForAudioFrameClassification",
585
+ "WavLMForCTC",
586
+ "WavLMForSequenceClassification",
587
+ "WavLMForXVector",
588
+ "WavLMModel",
589
+ "WavLMPreTrainedModel",
590
+ ]
.venv/lib/python3.12/site-packages/transformers/models/whisper/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_whisper import *
22
+ from .feature_extraction_whisper import *
23
+ from .modeling_whisper import *
24
+ from .processing_whisper import *
25
+ from .tokenization_whisper import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (778 Bytes). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/configuration_whisper.cpython-312.pyc ADDED
Binary file (8.61 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/english_normalizer.cpython-312.pyc ADDED
Binary file (24.6 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/feature_extraction_whisper.cpython-312.pyc ADDED
Binary file (17.7 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/generation_whisper.cpython-312.pyc ADDED
Binary file (94.5 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/modeling_whisper.cpython-312.pyc ADDED
Binary file (65 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/processing_whisper.cpython-312.pyc ADDED
Binary file (2.35 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/__pycache__/tokenization_whisper.cpython-312.pyc ADDED
Binary file (47.8 kB). View file
 
.venv/lib/python3.12/site-packages/transformers/models/whisper/configuration_whisper.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Whisper model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ # fmt: off
23
+ NON_SPEECH_TOKENS = [
24
+ 1, 2, 7, 8, 9, 10, 14, 25,
25
+ 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
26
+ 63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
27
+ 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377,
28
+ 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211,
29
+ 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786,
30
+ 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791,
31
+ 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409,
32
+ 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361
33
+ ]
34
+ NON_SPEECH_TOKENS_MULTI = [
35
+ 1, 2, 7, 8, 9, 10, 14, 25,
36
+ 26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
37
+ 63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
38
+ 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627,
39
+ 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647,
40
+ 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793,
41
+ 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675,
42
+ 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865,
43
+ 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362
44
+ ]
45
+ # fmt: on
46
+
47
+
48
+ @auto_docstring(checkpoint="openai/whisper-tiny")
49
+ @strict
50
+ class WhisperConfig(PreTrainedConfig):
51
+ r"""
52
+ max_source_positions (`int`, *optional*, defaults to 1500):
53
+ The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
54
+ max_target_positions (`int`, *optional*, defaults to 448):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ suppress_tokens (`list[int]`, *optional*):
58
+ A list containing the non-speech tokens that will be used by the logit processor in the `generate`
59
+ function. NON_SPEECH_TOKENS and NON_SPEECH_TOKENS_MULTI each correspond to the `english-only` and the
60
+ `multilingual` model.
61
+ begin_suppress_tokens (`list[int]`, *optional*, defaults to `[220,50256]`):
62
+ A list containing tokens that will be suppressed at the beginning of the sampling process. Initialized as
63
+ the token for `" "` (`blank_token_id`) and the `eos_token_id`
64
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
65
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
66
+ instance of [`WhisperForAudioClassification`].
67
+ classifier_proj_size (`int`, *optional*, defaults to 256):
68
+ Dimensionality of the projection before token mean-pooling for classification. Only relevant when using an
69
+ instance of [`WhisperForAudioClassification`].
70
+ apply_spec_augment (`bool`, *optional*, defaults to `False`):
71
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
72
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
73
+ Recognition](https://huggingface.co/papers/1904.08779).
74
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
75
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
76
+ procedure generates `mask_time_prob*len(time_axis)/mask_time_length` independent masks over the axis. If
77
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
78
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
79
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment == True`.
80
+ mask_time_length (`int`, *optional*, defaults to 10):
81
+ Length of vector span along the time axis.
82
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
83
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
84
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
85
+ mask_time_min_masks''
86
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
87
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
88
+ masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
89
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
90
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
91
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
92
+ True`.
93
+ mask_feature_length (`int`, *optional*, defaults to 10):
94
+ Length of vector span along the feature axis.
95
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
96
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
97
+ step, irrespectively of `mask_feature_prob`. Only relevant if
98
+ `mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks`.
99
+ median_filter_width (`int`, *optional*, defaults to 7):
100
+ Width of the median filter used to smoothen to cross-attention outputs when computing token timestamps.
101
+ Should be an odd number.
102
+
103
+ Example:
104
+
105
+ ```python
106
+ >>> from transformers import WhisperConfig, WhisperModel
107
+
108
+ >>> # Initializing a Whisper tiny style configuration
109
+ >>> configuration = WhisperConfig()
110
+
111
+ >>> # Initializing a model (with random weights) from the tiny style configuration
112
+ >>> model = WhisperModel(configuration)
113
+
114
+ >>> # Accessing the model configuration
115
+ >>> configuration = model.config
116
+ ```"""
117
+
118
+ model_type = "whisper"
119
+ keys_to_ignore_at_inference = ["past_key_values"]
120
+ attribute_map = {
121
+ "num_key_value_heads": "encoder_attention_heads",
122
+ "num_attention_heads": "encoder_attention_heads",
123
+ "hidden_size": "d_model",
124
+ "num_hidden_layers": "encoder_layers",
125
+ }
126
+
127
+ vocab_size: int = 51865
128
+ num_mel_bins: int = 80
129
+ encoder_layers: int = 4
130
+ encoder_attention_heads: int = 6
131
+ decoder_layers: int = 4
132
+ decoder_attention_heads: int = 6
133
+ decoder_ffn_dim: int = 1536
134
+ encoder_ffn_dim: int = 1536
135
+ encoder_layerdrop: float | int = 0.0
136
+ decoder_layerdrop: float | int = 0.0
137
+ decoder_start_token_id: int = 50257
138
+ use_cache: bool = True
139
+ is_encoder_decoder: bool = True
140
+ activation_function: str = "gelu"
141
+ d_model: int = 384
142
+ dropout: float | int = 0.0
143
+ attention_dropout: float | int = 0.0
144
+ activation_dropout: float | int = 0.0
145
+ init_std: float = 0.02
146
+ scale_embedding: bool = False
147
+ max_source_positions: int = 1500
148
+ max_target_positions: int = 448
149
+ pad_token_id: int | None = 50256
150
+ bos_token_id: int | None = 50256
151
+ eos_token_id: int | list[int] | None = 50256
152
+ suppress_tokens: list | None = None
153
+ begin_suppress_tokens: list[int] | tuple[int, ...] | None = (220, 50256)
154
+ use_weighted_layer_sum: bool = False
155
+ classifier_proj_size: int = 256
156
+ apply_spec_augment: bool = False
157
+ mask_time_prob: float | int = 0.05
158
+ mask_time_length: int = 10
159
+ mask_time_min_masks: int = 2
160
+ mask_feature_prob: float | int = 0.0
161
+ mask_feature_length: int = 10
162
+ mask_feature_min_masks: int = 0
163
+ median_filter_width: int = 7
164
+ tie_word_embeddings: bool = True
165
+
166
+
167
+ __all__ = ["WhisperConfig"]