ZhengyangZhang commited on
Commit
44361f6
·
verified ·
1 Parent(s): 197b148

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lib/python3.12/site-packages/transformers/models/auto/__init__.py +409 -0
  2. lib/python3.12/site-packages/transformers/models/auto/__pycache__/__init__.cpython-312.pyc +0 -0
  3. lib/python3.12/site-packages/transformers/models/auto/__pycache__/auto_factory.cpython-312.pyc +0 -0
  4. lib/python3.12/site-packages/transformers/models/auto/__pycache__/configuration_auto.cpython-312.pyc +0 -0
  5. lib/python3.12/site-packages/transformers/models/auto/__pycache__/feature_extraction_auto.cpython-312.pyc +0 -0
  6. lib/python3.12/site-packages/transformers/models/auto/__pycache__/image_processing_auto.cpython-312.pyc +0 -0
  7. lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_auto.cpython-312.pyc +0 -0
  8. lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_flax_auto.cpython-312.pyc +0 -0
  9. lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_tf_auto.cpython-312.pyc +0 -0
  10. lib/python3.12/site-packages/transformers/models/auto/__pycache__/processing_auto.cpython-312.pyc +0 -0
  11. lib/python3.12/site-packages/transformers/models/auto/__pycache__/tokenization_auto.cpython-312.pyc +0 -0
  12. lib/python3.12/site-packages/transformers/models/auto/auto_factory.py +842 -0
  13. lib/python3.12/site-packages/transformers/models/auto/configuration_auto.py +1170 -0
  14. lib/python3.12/site-packages/transformers/models/auto/feature_extraction_auto.py +408 -0
  15. lib/python3.12/site-packages/transformers/models/auto/image_processing_auto.py +642 -0
  16. lib/python3.12/site-packages/transformers/models/auto/modeling_auto.py +1951 -0
  17. lib/python3.12/site-packages/transformers/models/auto/modeling_flax_auto.py +383 -0
  18. lib/python3.12/site-packages/transformers/models/auto/modeling_tf_auto.py +728 -0
  19. lib/python3.12/site-packages/transformers/models/auto/processing_auto.py +391 -0
  20. lib/python3.12/site-packages/transformers/models/auto/tokenization_auto.py +1084 -0
  21. lib/python3.12/site-packages/transformers/models/bark/__init__.py +28 -0
  22. lib/python3.12/site-packages/transformers/models/bark/__pycache__/__init__.cpython-312.pyc +0 -0
  23. lib/python3.12/site-packages/transformers/models/bark/__pycache__/configuration_bark.cpython-312.pyc +0 -0
  24. lib/python3.12/site-packages/transformers/models/bark/__pycache__/generation_configuration_bark.cpython-312.pyc +0 -0
  25. lib/python3.12/site-packages/transformers/models/bark/__pycache__/modeling_bark.cpython-312.pyc +0 -0
  26. lib/python3.12/site-packages/transformers/models/bark/__pycache__/processing_bark.cpython-312.pyc +0 -0
  27. lib/python3.12/site-packages/transformers/models/bark/configuration_bark.py +303 -0
  28. lib/python3.12/site-packages/transformers/models/bark/generation_configuration_bark.py +331 -0
  29. lib/python3.12/site-packages/transformers/models/bark/modeling_bark.py +1848 -0
  30. lib/python3.12/site-packages/transformers/models/bark/processing_bark.py +296 -0
  31. lib/python3.12/site-packages/transformers/models/bert/__init__.py +32 -0
  32. lib/python3.12/site-packages/transformers/models/bert/__pycache__/__init__.cpython-312.pyc +0 -0
  33. lib/python3.12/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-312.pyc +0 -0
  34. lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-312.pyc +0 -0
  35. lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-312.pyc +0 -0
  36. lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-312.pyc +0 -0
  37. lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-312.pyc +0 -0
  38. lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-312.pyc +0 -0
  39. lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-312.pyc +0 -0
  40. lib/python3.12/site-packages/transformers/models/bert/configuration_bert.py +154 -0
  41. lib/python3.12/site-packages/transformers/models/bert/modeling_bert.py +2019 -0
  42. lib/python3.12/site-packages/transformers/models/bert/modeling_flax_bert.py +1727 -0
  43. lib/python3.12/site-packages/transformers/models/bert/modeling_tf_bert.py +2126 -0
  44. lib/python3.12/site-packages/transformers/models/bert/tokenization_bert.py +507 -0
  45. lib/python3.12/site-packages/transformers/models/bert/tokenization_bert_fast.py +175 -0
  46. lib/python3.12/site-packages/transformers/models/bert/tokenization_bert_tf.py +257 -0
  47. lib/python3.12/site-packages/transformers/models/clap/__init__.py +29 -0
  48. lib/python3.12/site-packages/transformers/models/clap/__pycache__/__init__.cpython-312.pyc +0 -0
  49. lib/python3.12/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-312.pyc +0 -0
  50. lib/python3.12/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-312.pyc +0 -0
lib/python3.12/site-packages/transformers/models/auto/__init__.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_flax_available,
21
+ is_tf_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "auto_factory": ["get_values"],
28
+ "configuration_auto": ["CONFIG_MAPPING", "MODEL_NAMES_MAPPING", "AutoConfig"],
29
+ "feature_extraction_auto": ["FEATURE_EXTRACTOR_MAPPING", "AutoFeatureExtractor"],
30
+ "image_processing_auto": ["IMAGE_PROCESSOR_MAPPING", "AutoImageProcessor"],
31
+ "processing_auto": ["PROCESSOR_MAPPING", "AutoProcessor"],
32
+ "tokenization_auto": ["TOKENIZER_MAPPING", "AutoTokenizer"],
33
+ }
34
+
35
+ try:
36
+ if not is_torch_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["modeling_auto"] = [
42
+ "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
43
+ "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING",
44
+ "MODEL_FOR_AUDIO_XVECTOR_MAPPING",
45
+ "MODEL_FOR_BACKBONE_MAPPING",
46
+ "MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING",
47
+ "MODEL_FOR_CAUSAL_LM_MAPPING",
48
+ "MODEL_FOR_CTC_MAPPING",
49
+ "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
50
+ "MODEL_FOR_DEPTH_ESTIMATION_MAPPING",
51
+ "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
52
+ "MODEL_FOR_IMAGE_MAPPING",
53
+ "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING",
54
+ "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING",
55
+ "MODEL_FOR_KEYPOINT_DETECTION_MAPPING",
56
+ "MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING",
57
+ "MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
58
+ "MODEL_FOR_MASKED_LM_MAPPING",
59
+ "MODEL_FOR_MASK_GENERATION_MAPPING",
60
+ "MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
61
+ "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
62
+ "MODEL_FOR_OBJECT_DETECTION_MAPPING",
63
+ "MODEL_FOR_PRETRAINING_MAPPING",
64
+ "MODEL_FOR_QUESTION_ANSWERING_MAPPING",
65
+ "MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
66
+ "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
67
+ "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
68
+ "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
69
+ "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
70
+ "MODEL_FOR_TEXT_ENCODING_MAPPING",
71
+ "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING",
72
+ "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING",
73
+ "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
74
+ "MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING",
75
+ "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING",
76
+ "MODEL_FOR_VISION_2_SEQ_MAPPING",
77
+ "MODEL_FOR_RETRIEVAL_MAPPING",
78
+ "MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING",
79
+ "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING",
80
+ "MODEL_MAPPING",
81
+ "MODEL_WITH_LM_HEAD_MAPPING",
82
+ "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
83
+ "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING",
84
+ "MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING",
85
+ "MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING",
86
+ "AutoModel",
87
+ "AutoBackbone",
88
+ "AutoModelForAudioClassification",
89
+ "AutoModelForAudioFrameClassification",
90
+ "AutoModelForAudioXVector",
91
+ "AutoModelForCausalLM",
92
+ "AutoModelForCTC",
93
+ "AutoModelForDepthEstimation",
94
+ "AutoModelForImageClassification",
95
+ "AutoModelForImageSegmentation",
96
+ "AutoModelForImageToImage",
97
+ "AutoModelForInstanceSegmentation",
98
+ "AutoModelForKeypointDetection",
99
+ "AutoModelForMaskGeneration",
100
+ "AutoModelForTextEncoding",
101
+ "AutoModelForMaskedImageModeling",
102
+ "AutoModelForMaskedLM",
103
+ "AutoModelForMultipleChoice",
104
+ "AutoModelForNextSentencePrediction",
105
+ "AutoModelForObjectDetection",
106
+ "AutoModelForPreTraining",
107
+ "AutoModelForQuestionAnswering",
108
+ "AutoModelForSemanticSegmentation",
109
+ "AutoModelForSeq2SeqLM",
110
+ "AutoModelForSequenceClassification",
111
+ "AutoModelForSpeechSeq2Seq",
112
+ "AutoModelForTableQuestionAnswering",
113
+ "AutoModelForTextToSpectrogram",
114
+ "AutoModelForTextToWaveform",
115
+ "AutoModelForTokenClassification",
116
+ "AutoModelForUniversalSegmentation",
117
+ "AutoModelForVideoClassification",
118
+ "AutoModelForVision2Seq",
119
+ "AutoModelForVisualQuestionAnswering",
120
+ "AutoModelForDocumentQuestionAnswering",
121
+ "AutoModelWithLMHead",
122
+ "AutoModelForZeroShotImageClassification",
123
+ "AutoModelForZeroShotObjectDetection",
124
+ "AutoModelForImageTextToText",
125
+ ]
126
+
127
+ try:
128
+ if not is_tf_available():
129
+ raise OptionalDependencyNotAvailable()
130
+ except OptionalDependencyNotAvailable:
131
+ pass
132
+ else:
133
+ _import_structure["modeling_tf_auto"] = [
134
+ "TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
135
+ "TF_MODEL_FOR_CAUSAL_LM_MAPPING",
136
+ "TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
137
+ "TF_MODEL_FOR_MASK_GENERATION_MAPPING",
138
+ "TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
139
+ "TF_MODEL_FOR_MASKED_LM_MAPPING",
140
+ "TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
141
+ "TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
142
+ "TF_MODEL_FOR_PRETRAINING_MAPPING",
143
+ "TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING",
144
+ "TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
145
+ "TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
146
+ "TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
147
+ "TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
148
+ "TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
149
+ "TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
150
+ "TF_MODEL_FOR_TEXT_ENCODING_MAPPING",
151
+ "TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
152
+ "TF_MODEL_FOR_VISION_2_SEQ_MAPPING",
153
+ "TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
154
+ "TF_MODEL_MAPPING",
155
+ "TF_MODEL_WITH_LM_HEAD_MAPPING",
156
+ "TFAutoModel",
157
+ "TFAutoModelForAudioClassification",
158
+ "TFAutoModelForCausalLM",
159
+ "TFAutoModelForImageClassification",
160
+ "TFAutoModelForMaskedImageModeling",
161
+ "TFAutoModelForMaskedLM",
162
+ "TFAutoModelForMaskGeneration",
163
+ "TFAutoModelForMultipleChoice",
164
+ "TFAutoModelForNextSentencePrediction",
165
+ "TFAutoModelForPreTraining",
166
+ "TFAutoModelForDocumentQuestionAnswering",
167
+ "TFAutoModelForQuestionAnswering",
168
+ "TFAutoModelForSemanticSegmentation",
169
+ "TFAutoModelForSeq2SeqLM",
170
+ "TFAutoModelForSequenceClassification",
171
+ "TFAutoModelForSpeechSeq2Seq",
172
+ "TFAutoModelForTableQuestionAnswering",
173
+ "TFAutoModelForTextEncoding",
174
+ "TFAutoModelForTokenClassification",
175
+ "TFAutoModelForVision2Seq",
176
+ "TFAutoModelForZeroShotImageClassification",
177
+ "TFAutoModelWithLMHead",
178
+ ]
179
+
180
+ try:
181
+ if not is_flax_available():
182
+ raise OptionalDependencyNotAvailable()
183
+ except OptionalDependencyNotAvailable:
184
+ pass
185
+ else:
186
+ _import_structure["modeling_flax_auto"] = [
187
+ "FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
188
+ "FLAX_MODEL_FOR_CAUSAL_LM_MAPPING",
189
+ "FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
190
+ "FLAX_MODEL_FOR_MASKED_LM_MAPPING",
191
+ "FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
192
+ "FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
193
+ "FLAX_MODEL_FOR_PRETRAINING_MAPPING",
194
+ "FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING",
195
+ "FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
196
+ "FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
197
+ "FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
198
+ "FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
199
+ "FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING",
200
+ "FLAX_MODEL_MAPPING",
201
+ "FlaxAutoModel",
202
+ "FlaxAutoModelForCausalLM",
203
+ "FlaxAutoModelForImageClassification",
204
+ "FlaxAutoModelForMaskedLM",
205
+ "FlaxAutoModelForMultipleChoice",
206
+ "FlaxAutoModelForNextSentencePrediction",
207
+ "FlaxAutoModelForPreTraining",
208
+ "FlaxAutoModelForQuestionAnswering",
209
+ "FlaxAutoModelForSeq2SeqLM",
210
+ "FlaxAutoModelForSequenceClassification",
211
+ "FlaxAutoModelForSpeechSeq2Seq",
212
+ "FlaxAutoModelForTokenClassification",
213
+ "FlaxAutoModelForVision2Seq",
214
+ ]
215
+
216
+
217
+ if TYPE_CHECKING:
218
+ from .auto_factory import get_values
219
+ from .configuration_auto import CONFIG_MAPPING, MODEL_NAMES_MAPPING, AutoConfig
220
+ from .feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor
221
+ from .image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor
222
+ from .processing_auto import PROCESSOR_MAPPING, AutoProcessor
223
+ from .tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
224
+
225
+ try:
226
+ if not is_torch_available():
227
+ raise OptionalDependencyNotAvailable()
228
+ except OptionalDependencyNotAvailable:
229
+ pass
230
+ else:
231
+ from .modeling_auto import (
232
+ MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
233
+ MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING,
234
+ MODEL_FOR_AUDIO_XVECTOR_MAPPING,
235
+ MODEL_FOR_BACKBONE_MAPPING,
236
+ MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING,
237
+ MODEL_FOR_CAUSAL_LM_MAPPING,
238
+ MODEL_FOR_CTC_MAPPING,
239
+ MODEL_FOR_DEPTH_ESTIMATION_MAPPING,
240
+ MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
241
+ MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
242
+ MODEL_FOR_IMAGE_MAPPING,
243
+ MODEL_FOR_IMAGE_SEGMENTATION_MAPPING,
244
+ MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING,
245
+ MODEL_FOR_IMAGE_TO_IMAGE_MAPPING,
246
+ MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING,
247
+ MODEL_FOR_KEYPOINT_DETECTION_MAPPING,
248
+ MODEL_FOR_MASK_GENERATION_MAPPING,
249
+ MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
250
+ MODEL_FOR_MASKED_LM_MAPPING,
251
+ MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
252
+ MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
253
+ MODEL_FOR_OBJECT_DETECTION_MAPPING,
254
+ MODEL_FOR_PRETRAINING_MAPPING,
255
+ MODEL_FOR_QUESTION_ANSWERING_MAPPING,
256
+ MODEL_FOR_RETRIEVAL_MAPPING,
257
+ MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
258
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
259
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
260
+ MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
261
+ MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
262
+ MODEL_FOR_TEXT_ENCODING_MAPPING,
263
+ MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING,
264
+ MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING,
265
+ MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING,
266
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING,
267
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
268
+ MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING,
269
+ MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
270
+ MODEL_FOR_VISION_2_SEQ_MAPPING,
271
+ MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING,
272
+ MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
273
+ MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING,
274
+ MODEL_MAPPING,
275
+ MODEL_WITH_LM_HEAD_MAPPING,
276
+ AutoBackbone,
277
+ AutoModel,
278
+ AutoModelForAudioClassification,
279
+ AutoModelForAudioFrameClassification,
280
+ AutoModelForAudioXVector,
281
+ AutoModelForCausalLM,
282
+ AutoModelForCTC,
283
+ AutoModelForDepthEstimation,
284
+ AutoModelForDocumentQuestionAnswering,
285
+ AutoModelForImageClassification,
286
+ AutoModelForImageSegmentation,
287
+ AutoModelForImageTextToText,
288
+ AutoModelForImageToImage,
289
+ AutoModelForInstanceSegmentation,
290
+ AutoModelForKeypointDetection,
291
+ AutoModelForMaskedImageModeling,
292
+ AutoModelForMaskedLM,
293
+ AutoModelForMaskGeneration,
294
+ AutoModelForMultipleChoice,
295
+ AutoModelForNextSentencePrediction,
296
+ AutoModelForObjectDetection,
297
+ AutoModelForPreTraining,
298
+ AutoModelForQuestionAnswering,
299
+ AutoModelForSemanticSegmentation,
300
+ AutoModelForSeq2SeqLM,
301
+ AutoModelForSequenceClassification,
302
+ AutoModelForSpeechSeq2Seq,
303
+ AutoModelForTableQuestionAnswering,
304
+ AutoModelForTextEncoding,
305
+ AutoModelForTextToSpectrogram,
306
+ AutoModelForTextToWaveform,
307
+ AutoModelForTokenClassification,
308
+ AutoModelForUniversalSegmentation,
309
+ AutoModelForVideoClassification,
310
+ AutoModelForVision2Seq,
311
+ AutoModelForVisualQuestionAnswering,
312
+ AutoModelForZeroShotImageClassification,
313
+ AutoModelForZeroShotObjectDetection,
314
+ AutoModelWithLMHead,
315
+ )
316
+
317
+ try:
318
+ if not is_tf_available():
319
+ raise OptionalDependencyNotAvailable()
320
+ except OptionalDependencyNotAvailable:
321
+ pass
322
+ else:
323
+ from .modeling_tf_auto import (
324
+ TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
325
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
326
+ TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
327
+ TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
328
+ TF_MODEL_FOR_MASK_GENERATION_MAPPING,
329
+ TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
330
+ TF_MODEL_FOR_MASKED_LM_MAPPING,
331
+ TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
332
+ TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
333
+ TF_MODEL_FOR_PRETRAINING_MAPPING,
334
+ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
335
+ TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
336
+ TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
337
+ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
338
+ TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
339
+ TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
340
+ TF_MODEL_FOR_TEXT_ENCODING_MAPPING,
341
+ TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
342
+ TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
343
+ TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
344
+ TF_MODEL_MAPPING,
345
+ TF_MODEL_WITH_LM_HEAD_MAPPING,
346
+ TFAutoModel,
347
+ TFAutoModelForAudioClassification,
348
+ TFAutoModelForCausalLM,
349
+ TFAutoModelForDocumentQuestionAnswering,
350
+ TFAutoModelForImageClassification,
351
+ TFAutoModelForMaskedImageModeling,
352
+ TFAutoModelForMaskedLM,
353
+ TFAutoModelForMaskGeneration,
354
+ TFAutoModelForMultipleChoice,
355
+ TFAutoModelForNextSentencePrediction,
356
+ TFAutoModelForPreTraining,
357
+ TFAutoModelForQuestionAnswering,
358
+ TFAutoModelForSemanticSegmentation,
359
+ TFAutoModelForSeq2SeqLM,
360
+ TFAutoModelForSequenceClassification,
361
+ TFAutoModelForSpeechSeq2Seq,
362
+ TFAutoModelForTableQuestionAnswering,
363
+ TFAutoModelForTextEncoding,
364
+ TFAutoModelForTokenClassification,
365
+ TFAutoModelForVision2Seq,
366
+ TFAutoModelForZeroShotImageClassification,
367
+ TFAutoModelWithLMHead,
368
+ )
369
+
370
+ try:
371
+ if not is_flax_available():
372
+ raise OptionalDependencyNotAvailable()
373
+ except OptionalDependencyNotAvailable:
374
+ pass
375
+ else:
376
+ from .modeling_flax_auto import (
377
+ FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
378
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
379
+ FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
380
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
381
+ FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
382
+ FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
383
+ FLAX_MODEL_FOR_PRETRAINING_MAPPING,
384
+ FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
385
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
386
+ FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
387
+ FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
388
+ FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
389
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
390
+ FLAX_MODEL_MAPPING,
391
+ FlaxAutoModel,
392
+ FlaxAutoModelForCausalLM,
393
+ FlaxAutoModelForImageClassification,
394
+ FlaxAutoModelForMaskedLM,
395
+ FlaxAutoModelForMultipleChoice,
396
+ FlaxAutoModelForNextSentencePrediction,
397
+ FlaxAutoModelForPreTraining,
398
+ FlaxAutoModelForQuestionAnswering,
399
+ FlaxAutoModelForSeq2SeqLM,
400
+ FlaxAutoModelForSequenceClassification,
401
+ FlaxAutoModelForSpeechSeq2Seq,
402
+ FlaxAutoModelForTokenClassification,
403
+ FlaxAutoModelForVision2Seq,
404
+ )
405
+
406
+ else:
407
+ import sys
408
+
409
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/auto/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (9.81 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/auto_factory.cpython-312.pyc ADDED
Binary file (40.5 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/configuration_auto.cpython-312.pyc ADDED
Binary file (38.1 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/feature_extraction_auto.cpython-312.pyc ADDED
Binary file (17.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/image_processing_auto.cpython-312.pyc ADDED
Binary file (26 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_auto.cpython-312.pyc ADDED
Binary file (51.8 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_flax_auto.cpython-312.pyc ADDED
Binary file (10.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_tf_auto.cpython-312.pyc ADDED
Binary file (20.3 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/processing_auto.cpython-312.pyc ADDED
Binary file (15.4 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/__pycache__/tokenization_auto.cpython-312.pyc ADDED
Binary file (41.1 kB). View file
 
lib/python3.12/site-packages/transformers/models/auto/auto_factory.py ADDED
@@ -0,0 +1,842 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Factory function to build auto-model classes."""
16
+
17
+ import copy
18
+ import importlib
19
+ import json
20
+ import warnings
21
+ from collections import OrderedDict
22
+
23
+ from ...configuration_utils import PretrainedConfig
24
+ from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
25
+ from ...utils import (
26
+ CONFIG_NAME,
27
+ cached_file,
28
+ copy_func,
29
+ extract_commit_hash,
30
+ find_adapter_config_file,
31
+ is_peft_available,
32
+ is_torch_available,
33
+ logging,
34
+ requires_backends,
35
+ )
36
+ from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings
37
+
38
+
39
+ if is_torch_available():
40
+ from ...generation import GenerationMixin
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ CLASS_DOCSTRING = """
47
+ This is a generic model class that will be instantiated as one of the model classes of the library when created
48
+ with the [`~BaseAutoModelClass.from_pretrained`] class method or the [`~BaseAutoModelClass.from_config`] class
49
+ method.
50
+
51
+ This class cannot be instantiated directly using `__init__()` (throws an error).
52
+ """
53
+
54
+ FROM_CONFIG_DOCSTRING = """
55
+ Instantiates one of the model classes of the library from a configuration.
56
+
57
+ Note:
58
+ Loading a model from its configuration file does **not** load the model weights. It only affects the
59
+ model's configuration. Use [`~BaseAutoModelClass.from_pretrained`] to load the model weights.
60
+
61
+ Args:
62
+ config ([`PretrainedConfig`]):
63
+ The model class to instantiate is selected based on the configuration class:
64
+
65
+ List options
66
+ attn_implementation (`str`, *optional*):
67
+ The attention implementation to use in the model (if relevant). Can be any of `"eager"` (manual implementation of the attention), `"sdpa"` (using [`F.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html)), or `"flash_attention_2"` (using [Dao-AILab/flash-attention](https://github.com/Dao-AILab/flash-attention)). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual `"eager"` implementation.
68
+
69
+ Examples:
70
+
71
+ ```python
72
+ >>> from transformers import AutoConfig, BaseAutoModelClass
73
+
74
+ >>> # Download configuration from huggingface.co and cache.
75
+ >>> config = AutoConfig.from_pretrained("checkpoint_placeholder")
76
+ >>> model = BaseAutoModelClass.from_config(config)
77
+ ```
78
+ """
79
+
80
+ FROM_PRETRAINED_TORCH_DOCSTRING = """
81
+ Instantiate one of the model classes of the library from a pretrained model.
82
+
83
+ The model class to instantiate is selected based on the `model_type` property of the config object (either
84
+ passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
85
+ falling back to using pattern matching on `pretrained_model_name_or_path`:
86
+
87
+ List options
88
+
89
+ The model is set in evaluation mode by default using `model.eval()` (so for instance, dropout modules are
90
+ deactivated). To train the model, you should first set it back in training mode with `model.train()`
91
+
92
+ Args:
93
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
94
+ Can be either:
95
+
96
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
97
+ - A path to a *directory* containing model weights saved using
98
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
99
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
100
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
101
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
102
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
103
+ model_args (additional positional arguments, *optional*):
104
+ Will be passed along to the underlying model `__init__()` method.
105
+ config ([`PretrainedConfig`], *optional*):
106
+ Configuration for the model to use instead of an automatically loaded configuration. Configuration can
107
+ be automatically loaded when:
108
+
109
+ - The model is a model provided by the library (loaded with the *model id* string of a pretrained
110
+ model).
111
+ - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
112
+ save directory.
113
+ - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
114
+ configuration JSON file named *config.json* is found in the directory.
115
+ state_dict (*Dict[str, torch.Tensor]*, *optional*):
116
+ A state dictionary to use instead of a state dictionary loaded from saved weights file.
117
+
118
+ This option can be used if you want to create a model from a pretrained configuration but load your own
119
+ weights. In this case though, you should check if using [`~PreTrainedModel.save_pretrained`] and
120
+ [`~PreTrainedModel.from_pretrained`] is not a simpler option.
121
+ cache_dir (`str` or `os.PathLike`, *optional*):
122
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
123
+ standard cache should not be used.
124
+ from_tf (`bool`, *optional*, defaults to `False`):
125
+ Load the model weights from a TensorFlow checkpoint save file (see docstring of
126
+ `pretrained_model_name_or_path` argument).
127
+ force_download (`bool`, *optional*, defaults to `False`):
128
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
129
+ cached versions if they exist.
130
+ resume_download:
131
+ Deprecated and ignored. All downloads are now resumed by default when possible.
132
+ Will be removed in v5 of Transformers.
133
+ proxies (`Dict[str, str]`, *optional*):
134
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
135
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
136
+ output_loading_info(`bool`, *optional*, defaults to `False`):
137
+ Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
138
+ local_files_only(`bool`, *optional*, defaults to `False`):
139
+ Whether or not to only look at local files (e.g., not try downloading the model).
140
+ revision (`str`, *optional*, defaults to `"main"`):
141
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
142
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
143
+ identifier allowed by git.
144
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
145
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
146
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
147
+ execute code present on the Hub on your local machine.
148
+ code_revision (`str`, *optional*, defaults to `"main"`):
149
+ The specific revision to use for the code on the Hub, if the code leaves in a different repository than
150
+ the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
151
+ system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
152
+ allowed by git.
153
+ kwargs (additional keyword arguments, *optional*):
154
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
155
+ `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
156
+ automatically loaded:
157
+
158
+ - If a configuration is provided with `config`, `**kwargs` will be directly passed to the
159
+ underlying model's `__init__` method (we assume all relevant updates to the configuration have
160
+ already been done)
161
+ - If a configuration is not provided, `kwargs` will be first passed to the configuration class
162
+ initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
163
+ corresponds to a configuration attribute will be used to override said attribute with the
164
+ supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
165
+ will be passed to the underlying model's `__init__` function.
166
+
167
+ Examples:
168
+
169
+ ```python
170
+ >>> from transformers import AutoConfig, BaseAutoModelClass
171
+
172
+ >>> # Download model and configuration from huggingface.co and cache.
173
+ >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
174
+
175
+ >>> # Update configuration during loading
176
+ >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
177
+ >>> model.config.output_attentions
178
+ True
179
+
180
+ >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
181
+ >>> config = AutoConfig.from_pretrained("./tf_model/shortcut_placeholder_tf_model_config.json")
182
+ >>> model = BaseAutoModelClass.from_pretrained(
183
+ ... "./tf_model/shortcut_placeholder_tf_checkpoint.ckpt.index", from_tf=True, config=config
184
+ ... )
185
+ ```
186
+ """
187
+
188
+ FROM_PRETRAINED_TF_DOCSTRING = """
189
+ Instantiate one of the model classes of the library from a pretrained model.
190
+
191
+ The model class to instantiate is selected based on the `model_type` property of the config object (either
192
+ passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
193
+ falling back to using pattern matching on `pretrained_model_name_or_path`:
194
+
195
+ List options
196
+
197
+ Args:
198
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
199
+ Can be either:
200
+
201
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
202
+ - A path to a *directory* containing model weights saved using
203
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
204
+ - A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
205
+ case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
206
+ argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
207
+ using the provided conversion scripts and loading the TensorFlow model afterwards.
208
+ model_args (additional positional arguments, *optional*):
209
+ Will be passed along to the underlying model `__init__()` method.
210
+ config ([`PretrainedConfig`], *optional*):
211
+ Configuration for the model to use instead of an automatically loaded configuration. Configuration can
212
+ be automatically loaded when:
213
+
214
+ - The model is a model provided by the library (loaded with the *model id* string of a pretrained
215
+ model).
216
+ - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
217
+ save directory.
218
+ - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
219
+ configuration JSON file named *config.json* is found in the directory.
220
+ cache_dir (`str` or `os.PathLike`, *optional*):
221
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
222
+ standard cache should not be used.
223
+ from_pt (`bool`, *optional*, defaults to `False`):
224
+ Load the model weights from a PyTorch checkpoint save file (see docstring of
225
+ `pretrained_model_name_or_path` argument).
226
+ force_download (`bool`, *optional*, defaults to `False`):
227
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
228
+ cached versions if they exist.
229
+ resume_download:
230
+ Deprecated and ignored. All downloads are now resumed by default when possible.
231
+ Will be removed in v5 of Transformers.
232
+ proxies (`Dict[str, str]`, *optional*):
233
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
234
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
235
+ output_loading_info(`bool`, *optional*, defaults to `False`):
236
+ Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
237
+ local_files_only(`bool`, *optional*, defaults to `False`):
238
+ Whether or not to only look at local files (e.g., not try downloading the model).
239
+ revision (`str`, *optional*, defaults to `"main"`):
240
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
241
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
242
+ identifier allowed by git.
243
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
244
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
245
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
246
+ execute code present on the Hub on your local machine.
247
+ code_revision (`str`, *optional*, defaults to `"main"`):
248
+ The specific revision to use for the code on the Hub, if the code leaves in a different repository than
249
+ the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
250
+ system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
251
+ allowed by git.
252
+ kwargs (additional keyword arguments, *optional*):
253
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
254
+ `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
255
+ automatically loaded:
256
+
257
+ - If a configuration is provided with `config`, `**kwargs` will be directly passed to the
258
+ underlying model's `__init__` method (we assume all relevant updates to the configuration have
259
+ already been done)
260
+ - If a configuration is not provided, `kwargs` will be first passed to the configuration class
261
+ initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
262
+ corresponds to a configuration attribute will be used to override said attribute with the
263
+ supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
264
+ will be passed to the underlying model's `__init__` function.
265
+
266
+ Examples:
267
+
268
+ ```python
269
+ >>> from transformers import AutoConfig, BaseAutoModelClass
270
+
271
+ >>> # Download model and configuration from huggingface.co and cache.
272
+ >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
273
+
274
+ >>> # Update configuration during loading
275
+ >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
276
+ >>> model.config.output_attentions
277
+ True
278
+
279
+ >>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
280
+ >>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
281
+ >>> model = BaseAutoModelClass.from_pretrained(
282
+ ... "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
283
+ ... )
284
+ ```
285
+ """
286
+
287
+ FROM_PRETRAINED_FLAX_DOCSTRING = """
288
+ Instantiate one of the model classes of the library from a pretrained model.
289
+
290
+ The model class to instantiate is selected based on the `model_type` property of the config object (either
291
+ passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
292
+ falling back to using pattern matching on `pretrained_model_name_or_path`:
293
+
294
+ List options
295
+
296
+ Args:
297
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
298
+ Can be either:
299
+
300
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
301
+ - A path to a *directory* containing model weights saved using
302
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
303
+ - A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
304
+ case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
305
+ argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
306
+ using the provided conversion scripts and loading the TensorFlow model afterwards.
307
+ model_args (additional positional arguments, *optional*):
308
+ Will be passed along to the underlying model `__init__()` method.
309
+ config ([`PretrainedConfig`], *optional*):
310
+ Configuration for the model to use instead of an automatically loaded configuration. Configuration can
311
+ be automatically loaded when:
312
+
313
+ - The model is a model provided by the library (loaded with the *model id* string of a pretrained
314
+ model).
315
+ - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
316
+ save directory.
317
+ - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
318
+ configuration JSON file named *config.json* is found in the directory.
319
+ cache_dir (`str` or `os.PathLike`, *optional*):
320
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
321
+ standard cache should not be used.
322
+ from_pt (`bool`, *optional*, defaults to `False`):
323
+ Load the model weights from a PyTorch checkpoint save file (see docstring of
324
+ `pretrained_model_name_or_path` argument).
325
+ force_download (`bool`, *optional*, defaults to `False`):
326
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
327
+ cached versions if they exist.
328
+ resume_download:
329
+ Deprecated and ignored. All downloads are now resumed by default when possible.
330
+ Will be removed in v5 of Transformers.
331
+ proxies (`Dict[str, str]`, *optional*):
332
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
333
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
334
+ output_loading_info(`bool`, *optional*, defaults to `False`):
335
+ Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
336
+ local_files_only(`bool`, *optional*, defaults to `False`):
337
+ Whether or not to only look at local files (e.g., not try downloading the model).
338
+ revision (`str`, *optional*, defaults to `"main"`):
339
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
340
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
341
+ identifier allowed by git.
342
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
343
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
344
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
345
+ execute code present on the Hub on your local machine.
346
+ code_revision (`str`, *optional*, defaults to `"main"`):
347
+ The specific revision to use for the code on the Hub, if the code leaves in a different repository than
348
+ the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
349
+ system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
350
+ allowed by git.
351
+ kwargs (additional keyword arguments, *optional*):
352
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
353
+ `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
354
+ automatically loaded:
355
+
356
+ - If a configuration is provided with `config`, `**kwargs` will be directly passed to the
357
+ underlying model's `__init__` method (we assume all relevant updates to the configuration have
358
+ already been done)
359
+ - If a configuration is not provided, `kwargs` will be first passed to the configuration class
360
+ initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
361
+ corresponds to a configuration attribute will be used to override said attribute with the
362
+ supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
363
+ will be passed to the underlying model's `__init__` function.
364
+
365
+ Examples:
366
+
367
+ ```python
368
+ >>> from transformers import AutoConfig, BaseAutoModelClass
369
+
370
+ >>> # Download model and configuration from huggingface.co and cache.
371
+ >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
372
+
373
+ >>> # Update configuration during loading
374
+ >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
375
+ >>> model.config.output_attentions
376
+ True
377
+
378
+ >>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
379
+ >>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
380
+ >>> model = BaseAutoModelClass.from_pretrained(
381
+ ... "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
382
+ ... )
383
+ ```
384
+ """
385
+
386
+
387
+ def _get_model_class(config, model_mapping):
388
+ supported_models = model_mapping[type(config)]
389
+ if not isinstance(supported_models, (list, tuple)):
390
+ return supported_models
391
+
392
+ name_to_model = {model.__name__: model for model in supported_models}
393
+ architectures = getattr(config, "architectures", [])
394
+ for arch in architectures:
395
+ if arch in name_to_model:
396
+ return name_to_model[arch]
397
+ elif f"TF{arch}" in name_to_model:
398
+ return name_to_model[f"TF{arch}"]
399
+ elif f"Flax{arch}" in name_to_model:
400
+ return name_to_model[f"Flax{arch}"]
401
+
402
+ # If not architecture is set in the config or match the supported models, the first element of the tuple is the
403
+ # defaults.
404
+ return supported_models[0]
405
+
406
+
407
+ class _BaseAutoModelClass:
408
+ # Base class for auto models.
409
+ _model_mapping = None
410
+
411
+ def __init__(self, *args, **kwargs):
412
+ raise EnvironmentError(
413
+ f"{self.__class__.__name__} is designed to be instantiated "
414
+ f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
415
+ f"`{self.__class__.__name__}.from_config(config)` methods."
416
+ )
417
+
418
+ @classmethod
419
+ def from_config(cls, config, **kwargs):
420
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
421
+ has_remote_code = hasattr(config, "auto_map") and cls.__name__ in config.auto_map
422
+ has_local_code = type(config) in cls._model_mapping.keys()
423
+ trust_remote_code = resolve_trust_remote_code(
424
+ trust_remote_code, config._name_or_path, has_local_code, has_remote_code
425
+ )
426
+
427
+ if has_remote_code and trust_remote_code:
428
+ class_ref = config.auto_map[cls.__name__]
429
+ if "--" in class_ref:
430
+ repo_id, class_ref = class_ref.split("--")
431
+ else:
432
+ repo_id = config.name_or_path
433
+ model_class = get_class_from_dynamic_module(class_ref, repo_id, **kwargs)
434
+ cls.register(config.__class__, model_class, exist_ok=True)
435
+ _ = kwargs.pop("code_revision", None)
436
+ model_class = add_generation_mixin_to_remote_model(model_class)
437
+ return model_class._from_config(config, **kwargs)
438
+ elif type(config) in cls._model_mapping.keys():
439
+ model_class = _get_model_class(config, cls._model_mapping)
440
+ return model_class._from_config(config, **kwargs)
441
+
442
+ raise ValueError(
443
+ f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
444
+ f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
445
+ )
446
+
447
+ @classmethod
448
+ def _prepare_config_for_auto_class(cls, config: PretrainedConfig) -> PretrainedConfig:
449
+ """Additional autoclass-specific config post-loading manipulation. May be overridden in subclasses."""
450
+ return config
451
+
452
+ @classmethod
453
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
454
+ config = kwargs.pop("config", None)
455
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
456
+ kwargs["_from_auto"] = True
457
+ hub_kwargs_names = [
458
+ "cache_dir",
459
+ "force_download",
460
+ "local_files_only",
461
+ "proxies",
462
+ "resume_download",
463
+ "revision",
464
+ "subfolder",
465
+ "use_auth_token",
466
+ "token",
467
+ ]
468
+ hub_kwargs = {name: kwargs.pop(name) for name in hub_kwargs_names if name in kwargs}
469
+ code_revision = kwargs.pop("code_revision", None)
470
+ commit_hash = kwargs.pop("_commit_hash", None)
471
+ adapter_kwargs = kwargs.pop("adapter_kwargs", None)
472
+
473
+ token = hub_kwargs.pop("token", None)
474
+ use_auth_token = hub_kwargs.pop("use_auth_token", None)
475
+ if use_auth_token is not None:
476
+ warnings.warn(
477
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
478
+ FutureWarning,
479
+ )
480
+ if token is not None:
481
+ raise ValueError(
482
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
483
+ )
484
+ token = use_auth_token
485
+
486
+ if token is not None:
487
+ hub_kwargs["token"] = token
488
+
489
+ if commit_hash is None:
490
+ if not isinstance(config, PretrainedConfig):
491
+ # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible
492
+ resolved_config_file = cached_file(
493
+ pretrained_model_name_or_path,
494
+ CONFIG_NAME,
495
+ _raise_exceptions_for_gated_repo=False,
496
+ _raise_exceptions_for_missing_entries=False,
497
+ _raise_exceptions_for_connection_errors=False,
498
+ **hub_kwargs,
499
+ )
500
+ commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
501
+ else:
502
+ commit_hash = getattr(config, "_commit_hash", None)
503
+
504
+ if is_peft_available():
505
+ if adapter_kwargs is None:
506
+ adapter_kwargs = {}
507
+ if token is not None:
508
+ adapter_kwargs["token"] = token
509
+
510
+ maybe_adapter_path = find_adapter_config_file(
511
+ pretrained_model_name_or_path, _commit_hash=commit_hash, **adapter_kwargs
512
+ )
513
+
514
+ if maybe_adapter_path is not None:
515
+ with open(maybe_adapter_path, "r", encoding="utf-8") as f:
516
+ adapter_config = json.load(f)
517
+
518
+ adapter_kwargs["_adapter_model_path"] = pretrained_model_name_or_path
519
+ pretrained_model_name_or_path = adapter_config["base_model_name_or_path"]
520
+
521
+ if not isinstance(config, PretrainedConfig):
522
+ kwargs_orig = copy.deepcopy(kwargs)
523
+ # ensure not to pollute the config object with torch_dtype="auto" - since it's
524
+ # meaningless in the context of the config object - torch.dtype values are acceptable
525
+ if kwargs.get("torch_dtype", None) == "auto":
526
+ _ = kwargs.pop("torch_dtype")
527
+ # to not overwrite the quantization_config if config has a quantization_config
528
+ if kwargs.get("quantization_config", None) is not None:
529
+ _ = kwargs.pop("quantization_config")
530
+
531
+ config, kwargs = AutoConfig.from_pretrained(
532
+ pretrained_model_name_or_path,
533
+ return_unused_kwargs=True,
534
+ trust_remote_code=trust_remote_code,
535
+ code_revision=code_revision,
536
+ _commit_hash=commit_hash,
537
+ **hub_kwargs,
538
+ **kwargs,
539
+ )
540
+
541
+ # if torch_dtype=auto was passed here, ensure to pass it on
542
+ if kwargs_orig.get("torch_dtype", None) == "auto":
543
+ kwargs["torch_dtype"] = "auto"
544
+ if kwargs_orig.get("quantization_config", None) is not None:
545
+ kwargs["quantization_config"] = kwargs_orig["quantization_config"]
546
+
547
+ has_remote_code = hasattr(config, "auto_map") and cls.__name__ in config.auto_map
548
+ has_local_code = type(config) in cls._model_mapping.keys()
549
+ trust_remote_code = resolve_trust_remote_code(
550
+ trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
551
+ )
552
+
553
+ # Set the adapter kwargs
554
+ kwargs["adapter_kwargs"] = adapter_kwargs
555
+
556
+ if has_remote_code and trust_remote_code:
557
+ class_ref = config.auto_map[cls.__name__]
558
+ model_class = get_class_from_dynamic_module(
559
+ class_ref, pretrained_model_name_or_path, code_revision=code_revision, **hub_kwargs, **kwargs
560
+ )
561
+ _ = hub_kwargs.pop("code_revision", None)
562
+ cls.register(config.__class__, model_class, exist_ok=True)
563
+ model_class = add_generation_mixin_to_remote_model(model_class)
564
+ return model_class.from_pretrained(
565
+ pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
566
+ )
567
+ elif type(config) in cls._model_mapping.keys():
568
+ model_class = _get_model_class(config, cls._model_mapping)
569
+ if model_class.config_class == config.sub_configs.get("text_config", None):
570
+ config = config.get_text_config()
571
+ return model_class.from_pretrained(
572
+ pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
573
+ )
574
+ raise ValueError(
575
+ f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
576
+ f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
577
+ )
578
+
579
+ @classmethod
580
+ def register(cls, config_class, model_class, exist_ok=False):
581
+ """
582
+ Register a new model for this class.
583
+
584
+ Args:
585
+ config_class ([`PretrainedConfig`]):
586
+ The configuration corresponding to the model to register.
587
+ model_class ([`PreTrainedModel`]):
588
+ The model to register.
589
+ """
590
+ if hasattr(model_class, "config_class") and model_class.config_class.__name__ != config_class.__name__:
591
+ raise ValueError(
592
+ "The model class you are passing has a `config_class` attribute that is not consistent with the "
593
+ f"config class you passed (model has {model_class.config_class} and you passed {config_class}. Fix "
594
+ "one of those so they match!"
595
+ )
596
+ cls._model_mapping.register(config_class, model_class, exist_ok=exist_ok)
597
+
598
+
599
+ class _BaseAutoBackboneClass(_BaseAutoModelClass):
600
+ # Base class for auto backbone models.
601
+ _model_mapping = None
602
+
603
+ @classmethod
604
+ def _load_timm_backbone_from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
605
+ requires_backends(cls, ["vision", "timm"])
606
+ from ...models.timm_backbone import TimmBackboneConfig
607
+
608
+ config = kwargs.pop("config", TimmBackboneConfig())
609
+
610
+ if kwargs.get("out_features", None) is not None:
611
+ raise ValueError("Cannot specify `out_features` for timm backbones")
612
+
613
+ if kwargs.get("output_loading_info", False):
614
+ raise ValueError("Cannot specify `output_loading_info=True` when loading from timm")
615
+
616
+ num_channels = kwargs.pop("num_channels", config.num_channels)
617
+ features_only = kwargs.pop("features_only", config.features_only)
618
+ use_pretrained_backbone = kwargs.pop("use_pretrained_backbone", config.use_pretrained_backbone)
619
+ out_indices = kwargs.pop("out_indices", config.out_indices)
620
+ config = TimmBackboneConfig(
621
+ backbone=pretrained_model_name_or_path,
622
+ num_channels=num_channels,
623
+ features_only=features_only,
624
+ use_pretrained_backbone=use_pretrained_backbone,
625
+ out_indices=out_indices,
626
+ )
627
+ return super().from_config(config, **kwargs)
628
+
629
+ @classmethod
630
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
631
+ use_timm_backbone = kwargs.pop("use_timm_backbone", False)
632
+ if use_timm_backbone:
633
+ return cls._load_timm_backbone_from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
634
+
635
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
636
+
637
+
638
+ def insert_head_doc(docstring, head_doc=""):
639
+ if len(head_doc) > 0:
640
+ return docstring.replace(
641
+ "one of the model classes of the library ",
642
+ f"one of the model classes of the library (with a {head_doc} head) ",
643
+ )
644
+ return docstring.replace(
645
+ "one of the model classes of the library ", "one of the base model classes of the library "
646
+ )
647
+
648
+
649
+ def auto_class_update(cls, checkpoint_for_example="google-bert/bert-base-cased", head_doc=""):
650
+ # Create a new class with the right name from the base class
651
+ model_mapping = cls._model_mapping
652
+ name = cls.__name__
653
+ class_docstring = insert_head_doc(CLASS_DOCSTRING, head_doc=head_doc)
654
+ cls.__doc__ = class_docstring.replace("BaseAutoModelClass", name)
655
+
656
+ # Now we need to copy and re-register `from_config` and `from_pretrained` as class methods otherwise we can't
657
+ # have a specific docstrings for them.
658
+ from_config = copy_func(_BaseAutoModelClass.from_config)
659
+ from_config_docstring = insert_head_doc(FROM_CONFIG_DOCSTRING, head_doc=head_doc)
660
+ from_config_docstring = from_config_docstring.replace("BaseAutoModelClass", name)
661
+ from_config_docstring = from_config_docstring.replace("checkpoint_placeholder", checkpoint_for_example)
662
+ from_config.__doc__ = from_config_docstring
663
+ from_config = replace_list_option_in_docstrings(model_mapping._model_mapping, use_model_types=False)(from_config)
664
+ cls.from_config = classmethod(from_config)
665
+
666
+ if name.startswith("TF"):
667
+ from_pretrained_docstring = FROM_PRETRAINED_TF_DOCSTRING
668
+ elif name.startswith("Flax"):
669
+ from_pretrained_docstring = FROM_PRETRAINED_FLAX_DOCSTRING
670
+ else:
671
+ from_pretrained_docstring = FROM_PRETRAINED_TORCH_DOCSTRING
672
+ from_pretrained = copy_func(_BaseAutoModelClass.from_pretrained)
673
+ from_pretrained_docstring = insert_head_doc(from_pretrained_docstring, head_doc=head_doc)
674
+ from_pretrained_docstring = from_pretrained_docstring.replace("BaseAutoModelClass", name)
675
+ from_pretrained_docstring = from_pretrained_docstring.replace("checkpoint_placeholder", checkpoint_for_example)
676
+ shortcut = checkpoint_for_example.split("/")[-1].split("-")[0]
677
+ from_pretrained_docstring = from_pretrained_docstring.replace("shortcut_placeholder", shortcut)
678
+ from_pretrained.__doc__ = from_pretrained_docstring
679
+ from_pretrained = replace_list_option_in_docstrings(model_mapping._model_mapping)(from_pretrained)
680
+ cls.from_pretrained = classmethod(from_pretrained)
681
+ return cls
682
+
683
+
684
+ def get_values(model_mapping):
685
+ result = []
686
+ for model in model_mapping.values():
687
+ if isinstance(model, (list, tuple)):
688
+ result += list(model)
689
+ else:
690
+ result.append(model)
691
+
692
+ return result
693
+
694
+
695
+ def getattribute_from_module(module, attr):
696
+ if attr is None:
697
+ return None
698
+ if isinstance(attr, tuple):
699
+ return tuple(getattribute_from_module(module, a) for a in attr)
700
+ if hasattr(module, attr):
701
+ return getattr(module, attr)
702
+ # Some of the mappings have entries model_type -> object of another model type. In that case we try to grab the
703
+ # object at the top level.
704
+ transformers_module = importlib.import_module("transformers")
705
+
706
+ if module != transformers_module:
707
+ try:
708
+ return getattribute_from_module(transformers_module, attr)
709
+ except ValueError:
710
+ raise ValueError(f"Could not find {attr} neither in {module} nor in {transformers_module}!")
711
+ else:
712
+ raise ValueError(f"Could not find {attr} in {transformers_module}!")
713
+
714
+
715
+ def add_generation_mixin_to_remote_model(model_class):
716
+ """
717
+ Adds `GenerationMixin` to the inheritance of `model_class`, if `model_class` is a PyTorch model.
718
+
719
+ This function is used for backwards compatibility purposes: in v4.45, we've started a deprecation cycle to make
720
+ `PreTrainedModel` stop inheriting from `GenerationMixin`. Without this function, older models dynamically loaded
721
+ from the Hub may not have the `generate` method after we remove the inheritance.
722
+ """
723
+ # 1. If it is not a PT model (i.e. doesn't inherit Module), do nothing
724
+ if "torch.nn.modules.module.Module" not in str(model_class.__mro__):
725
+ return model_class
726
+
727
+ # 2. If it already **directly** inherits from GenerationMixin, do nothing
728
+ if "GenerationMixin" in str(model_class.__bases__):
729
+ return model_class
730
+
731
+ # 3. Prior to v4.45, we could detect whether a model was `generate`-compatible if it had its own `generate` and/or
732
+ # `prepare_inputs_for_generation` method.
733
+ has_custom_generate = "GenerationMixin" not in str(getattr(model_class, "generate"))
734
+ has_custom_prepare_inputs = "GenerationMixin" not in str(getattr(model_class, "prepare_inputs_for_generation"))
735
+ if has_custom_generate or has_custom_prepare_inputs:
736
+ model_class_with_generation_mixin = type(
737
+ model_class.__name__, (model_class, GenerationMixin), {**model_class.__dict__}
738
+ )
739
+ return model_class_with_generation_mixin
740
+ return model_class
741
+
742
+
743
+ class _LazyAutoMapping(OrderedDict):
744
+ """
745
+ " A mapping config to object (model or tokenizer for instance) that will load keys and values when it is accessed.
746
+
747
+ Args:
748
+ - config_mapping: The map model type to config class
749
+ - model_mapping: The map model type to model (or tokenizer) class
750
+ """
751
+
752
+ def __init__(self, config_mapping, model_mapping):
753
+ self._config_mapping = config_mapping
754
+ self._reverse_config_mapping = {v: k for k, v in config_mapping.items()}
755
+ self._model_mapping = model_mapping
756
+ self._model_mapping._model_mapping = self
757
+ self._extra_content = {}
758
+ self._modules = {}
759
+
760
+ def __len__(self):
761
+ common_keys = set(self._config_mapping.keys()).intersection(self._model_mapping.keys())
762
+ return len(common_keys) + len(self._extra_content)
763
+
764
+ def __getitem__(self, key):
765
+ if key in self._extra_content:
766
+ return self._extra_content[key]
767
+ model_type = self._reverse_config_mapping[key.__name__]
768
+ if model_type in self._model_mapping:
769
+ model_name = self._model_mapping[model_type]
770
+ return self._load_attr_from_module(model_type, model_name)
771
+
772
+ # Maybe there was several model types associated with this config.
773
+ model_types = [k for k, v in self._config_mapping.items() if v == key.__name__]
774
+ for mtype in model_types:
775
+ if mtype in self._model_mapping:
776
+ model_name = self._model_mapping[mtype]
777
+ return self._load_attr_from_module(mtype, model_name)
778
+ raise KeyError(key)
779
+
780
+ def _load_attr_from_module(self, model_type, attr):
781
+ module_name = model_type_to_module_name(model_type)
782
+ if module_name not in self._modules:
783
+ self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
784
+ return getattribute_from_module(self._modules[module_name], attr)
785
+
786
+ def keys(self):
787
+ mapping_keys = [
788
+ self._load_attr_from_module(key, name)
789
+ for key, name in self._config_mapping.items()
790
+ if key in self._model_mapping.keys()
791
+ ]
792
+ return mapping_keys + list(self._extra_content.keys())
793
+
794
+ def get(self, key, default):
795
+ try:
796
+ return self.__getitem__(key)
797
+ except KeyError:
798
+ return default
799
+
800
+ def __bool__(self):
801
+ return bool(self.keys())
802
+
803
+ def values(self):
804
+ mapping_values = [
805
+ self._load_attr_from_module(key, name)
806
+ for key, name in self._model_mapping.items()
807
+ if key in self._config_mapping.keys()
808
+ ]
809
+ return mapping_values + list(self._extra_content.values())
810
+
811
+ def items(self):
812
+ mapping_items = [
813
+ (
814
+ self._load_attr_from_module(key, self._config_mapping[key]),
815
+ self._load_attr_from_module(key, self._model_mapping[key]),
816
+ )
817
+ for key in self._model_mapping.keys()
818
+ if key in self._config_mapping.keys()
819
+ ]
820
+ return mapping_items + list(self._extra_content.items())
821
+
822
+ def __iter__(self):
823
+ return iter(self.keys())
824
+
825
+ def __contains__(self, item):
826
+ if item in self._extra_content:
827
+ return True
828
+ if not hasattr(item, "__name__") or item.__name__ not in self._reverse_config_mapping:
829
+ return False
830
+ model_type = self._reverse_config_mapping[item.__name__]
831
+ return model_type in self._model_mapping
832
+
833
+ def register(self, key, value, exist_ok=False):
834
+ """
835
+ Register a new model in this mapping.
836
+ """
837
+ if hasattr(key, "__name__") and key.__name__ in self._reverse_config_mapping:
838
+ model_type = self._reverse_config_mapping[key.__name__]
839
+ if model_type in self._model_mapping.keys() and not exist_ok:
840
+ raise ValueError(f"'{key}' is already used by a Transformers model.")
841
+
842
+ self._extra_content[key] = value
lib/python3.12/site-packages/transformers/models/auto/configuration_auto.py ADDED
@@ -0,0 +1,1170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Auto Config class."""
16
+
17
+ import importlib
18
+ import os
19
+ import re
20
+ import warnings
21
+ from collections import OrderedDict
22
+ from typing import List, Union
23
+
24
+ from ...configuration_utils import PretrainedConfig
25
+ from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
26
+ from ...utils import CONFIG_NAME, logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ CONFIG_MAPPING_NAMES = OrderedDict(
33
+ [
34
+ # Add configs here
35
+ ("albert", "AlbertConfig"),
36
+ ("align", "AlignConfig"),
37
+ ("altclip", "AltCLIPConfig"),
38
+ ("aria", "AriaConfig"),
39
+ ("aria_text", "AriaTextConfig"),
40
+ ("audio-spectrogram-transformer", "ASTConfig"),
41
+ ("autoformer", "AutoformerConfig"),
42
+ ("aya_vision", "AyaVisionConfig"),
43
+ ("bamba", "BambaConfig"),
44
+ ("bark", "BarkConfig"),
45
+ ("bart", "BartConfig"),
46
+ ("beit", "BeitConfig"),
47
+ ("bert", "BertConfig"),
48
+ ("bert-generation", "BertGenerationConfig"),
49
+ ("big_bird", "BigBirdConfig"),
50
+ ("bigbird_pegasus", "BigBirdPegasusConfig"),
51
+ ("biogpt", "BioGptConfig"),
52
+ ("bit", "BitConfig"),
53
+ ("blenderbot", "BlenderbotConfig"),
54
+ ("blenderbot-small", "BlenderbotSmallConfig"),
55
+ ("blip", "BlipConfig"),
56
+ ("blip-2", "Blip2Config"),
57
+ ("bloom", "BloomConfig"),
58
+ ("bridgetower", "BridgeTowerConfig"),
59
+ ("bros", "BrosConfig"),
60
+ ("camembert", "CamembertConfig"),
61
+ ("canine", "CanineConfig"),
62
+ ("chameleon", "ChameleonConfig"),
63
+ ("chinese_clip", "ChineseCLIPConfig"),
64
+ ("chinese_clip_vision_model", "ChineseCLIPVisionConfig"),
65
+ ("clap", "ClapConfig"),
66
+ ("clip", "CLIPConfig"),
67
+ ("clip_text_model", "CLIPTextConfig"),
68
+ ("clip_vision_model", "CLIPVisionConfig"),
69
+ ("clipseg", "CLIPSegConfig"),
70
+ ("clvp", "ClvpConfig"),
71
+ ("code_llama", "LlamaConfig"),
72
+ ("codegen", "CodeGenConfig"),
73
+ ("cohere", "CohereConfig"),
74
+ ("cohere2", "Cohere2Config"),
75
+ ("colpali", "ColPaliConfig"),
76
+ ("conditional_detr", "ConditionalDetrConfig"),
77
+ ("convbert", "ConvBertConfig"),
78
+ ("convnext", "ConvNextConfig"),
79
+ ("convnextv2", "ConvNextV2Config"),
80
+ ("cpmant", "CpmAntConfig"),
81
+ ("ctrl", "CTRLConfig"),
82
+ ("cvt", "CvtConfig"),
83
+ ("dab-detr", "DabDetrConfig"),
84
+ ("dac", "DacConfig"),
85
+ ("data2vec-audio", "Data2VecAudioConfig"),
86
+ ("data2vec-text", "Data2VecTextConfig"),
87
+ ("data2vec-vision", "Data2VecVisionConfig"),
88
+ ("dbrx", "DbrxConfig"),
89
+ ("deberta", "DebertaConfig"),
90
+ ("deberta-v2", "DebertaV2Config"),
91
+ ("decision_transformer", "DecisionTransformerConfig"),
92
+ ("deepseek_v3", "DeepseekV3Config"),
93
+ ("deformable_detr", "DeformableDetrConfig"),
94
+ ("deit", "DeiTConfig"),
95
+ ("depth_anything", "DepthAnythingConfig"),
96
+ ("depth_pro", "DepthProConfig"),
97
+ ("deta", "DetaConfig"),
98
+ ("detr", "DetrConfig"),
99
+ ("diffllama", "DiffLlamaConfig"),
100
+ ("dinat", "DinatConfig"),
101
+ ("dinov2", "Dinov2Config"),
102
+ ("dinov2_with_registers", "Dinov2WithRegistersConfig"),
103
+ ("distilbert", "DistilBertConfig"),
104
+ ("donut-swin", "DonutSwinConfig"),
105
+ ("dpr", "DPRConfig"),
106
+ ("dpt", "DPTConfig"),
107
+ ("efficientformer", "EfficientFormerConfig"),
108
+ ("efficientnet", "EfficientNetConfig"),
109
+ ("electra", "ElectraConfig"),
110
+ ("emu3", "Emu3Config"),
111
+ ("encodec", "EncodecConfig"),
112
+ ("encoder-decoder", "EncoderDecoderConfig"),
113
+ ("ernie", "ErnieConfig"),
114
+ ("ernie_m", "ErnieMConfig"),
115
+ ("esm", "EsmConfig"),
116
+ ("falcon", "FalconConfig"),
117
+ ("falcon_mamba", "FalconMambaConfig"),
118
+ ("fastspeech2_conformer", "FastSpeech2ConformerConfig"),
119
+ ("flaubert", "FlaubertConfig"),
120
+ ("flava", "FlavaConfig"),
121
+ ("fnet", "FNetConfig"),
122
+ ("focalnet", "FocalNetConfig"),
123
+ ("fsmt", "FSMTConfig"),
124
+ ("funnel", "FunnelConfig"),
125
+ ("fuyu", "FuyuConfig"),
126
+ ("gemma", "GemmaConfig"),
127
+ ("gemma2", "Gemma2Config"),
128
+ ("gemma3", "Gemma3Config"),
129
+ ("gemma3_text", "Gemma3TextConfig"),
130
+ ("git", "GitConfig"),
131
+ ("glm", "GlmConfig"),
132
+ ("glpn", "GLPNConfig"),
133
+ ("got_ocr2", "GotOcr2Config"),
134
+ ("gpt-sw3", "GPT2Config"),
135
+ ("gpt2", "GPT2Config"),
136
+ ("gpt_bigcode", "GPTBigCodeConfig"),
137
+ ("gpt_neo", "GPTNeoConfig"),
138
+ ("gpt_neox", "GPTNeoXConfig"),
139
+ ("gpt_neox_japanese", "GPTNeoXJapaneseConfig"),
140
+ ("gptj", "GPTJConfig"),
141
+ ("gptsan-japanese", "GPTSanJapaneseConfig"),
142
+ ("granite", "GraniteConfig"),
143
+ ("granitemoe", "GraniteMoeConfig"),
144
+ ("granitemoeshared", "GraniteMoeSharedConfig"),
145
+ ("granitevision", "LlavaNextConfig"),
146
+ ("graphormer", "GraphormerConfig"),
147
+ ("grounding-dino", "GroundingDinoConfig"),
148
+ ("groupvit", "GroupViTConfig"),
149
+ ("helium", "HeliumConfig"),
150
+ ("hiera", "HieraConfig"),
151
+ ("hubert", "HubertConfig"),
152
+ ("ibert", "IBertConfig"),
153
+ ("idefics", "IdeficsConfig"),
154
+ ("idefics2", "Idefics2Config"),
155
+ ("idefics3", "Idefics3Config"),
156
+ ("idefics3_vision", "Idefics3VisionConfig"),
157
+ ("ijepa", "IJepaConfig"),
158
+ ("imagegpt", "ImageGPTConfig"),
159
+ ("informer", "InformerConfig"),
160
+ ("instructblip", "InstructBlipConfig"),
161
+ ("instructblipvideo", "InstructBlipVideoConfig"),
162
+ ("jamba", "JambaConfig"),
163
+ ("jetmoe", "JetMoeConfig"),
164
+ ("jukebox", "JukeboxConfig"),
165
+ ("kosmos-2", "Kosmos2Config"),
166
+ ("layoutlm", "LayoutLMConfig"),
167
+ ("layoutlmv2", "LayoutLMv2Config"),
168
+ ("layoutlmv3", "LayoutLMv3Config"),
169
+ ("led", "LEDConfig"),
170
+ ("levit", "LevitConfig"),
171
+ ("lilt", "LiltConfig"),
172
+ ("llama", "LlamaConfig"),
173
+ ("llama4", "Llama4Config"),
174
+ ("llama4_text", "Llama4TextConfig"),
175
+ ("llava", "LlavaConfig"),
176
+ ("llava_next", "LlavaNextConfig"),
177
+ ("llava_next_video", "LlavaNextVideoConfig"),
178
+ ("llava_onevision", "LlavaOnevisionConfig"),
179
+ ("longformer", "LongformerConfig"),
180
+ ("longt5", "LongT5Config"),
181
+ ("luke", "LukeConfig"),
182
+ ("lxmert", "LxmertConfig"),
183
+ ("m2m_100", "M2M100Config"),
184
+ ("mamba", "MambaConfig"),
185
+ ("mamba2", "Mamba2Config"),
186
+ ("marian", "MarianConfig"),
187
+ ("markuplm", "MarkupLMConfig"),
188
+ ("mask2former", "Mask2FormerConfig"),
189
+ ("maskformer", "MaskFormerConfig"),
190
+ ("maskformer-swin", "MaskFormerSwinConfig"),
191
+ ("mbart", "MBartConfig"),
192
+ ("mctct", "MCTCTConfig"),
193
+ ("mega", "MegaConfig"),
194
+ ("megatron-bert", "MegatronBertConfig"),
195
+ ("mgp-str", "MgpstrConfig"),
196
+ ("mimi", "MimiConfig"),
197
+ ("mistral", "MistralConfig"),
198
+ ("mistral3", "Mistral3Config"),
199
+ ("mixtral", "MixtralConfig"),
200
+ ("mllama", "MllamaConfig"),
201
+ ("mobilebert", "MobileBertConfig"),
202
+ ("mobilenet_v1", "MobileNetV1Config"),
203
+ ("mobilenet_v2", "MobileNetV2Config"),
204
+ ("mobilevit", "MobileViTConfig"),
205
+ ("mobilevitv2", "MobileViTV2Config"),
206
+ ("modernbert", "ModernBertConfig"),
207
+ ("moonshine", "MoonshineConfig"),
208
+ ("moshi", "MoshiConfig"),
209
+ ("mpnet", "MPNetConfig"),
210
+ ("mpt", "MptConfig"),
211
+ ("mra", "MraConfig"),
212
+ ("mt5", "MT5Config"),
213
+ ("musicgen", "MusicgenConfig"),
214
+ ("musicgen_melody", "MusicgenMelodyConfig"),
215
+ ("mvp", "MvpConfig"),
216
+ ("nat", "NatConfig"),
217
+ ("nemotron", "NemotronConfig"),
218
+ ("nezha", "NezhaConfig"),
219
+ ("nllb-moe", "NllbMoeConfig"),
220
+ ("nougat", "VisionEncoderDecoderConfig"),
221
+ ("nystromformer", "NystromformerConfig"),
222
+ ("olmo", "OlmoConfig"),
223
+ ("olmo2", "Olmo2Config"),
224
+ ("olmoe", "OlmoeConfig"),
225
+ ("omdet-turbo", "OmDetTurboConfig"),
226
+ ("oneformer", "OneFormerConfig"),
227
+ ("open-llama", "OpenLlamaConfig"),
228
+ ("openai-gpt", "OpenAIGPTConfig"),
229
+ ("opt", "OPTConfig"),
230
+ ("owlv2", "Owlv2Config"),
231
+ ("owlvit", "OwlViTConfig"),
232
+ ("paligemma", "PaliGemmaConfig"),
233
+ ("patchtsmixer", "PatchTSMixerConfig"),
234
+ ("patchtst", "PatchTSTConfig"),
235
+ ("pegasus", "PegasusConfig"),
236
+ ("pegasus_x", "PegasusXConfig"),
237
+ ("perceiver", "PerceiverConfig"),
238
+ ("persimmon", "PersimmonConfig"),
239
+ ("phi", "PhiConfig"),
240
+ ("phi3", "Phi3Config"),
241
+ ("phi4_multimodal", "Phi4MultimodalConfig"),
242
+ ("phimoe", "PhimoeConfig"),
243
+ ("pix2struct", "Pix2StructConfig"),
244
+ ("pixtral", "PixtralVisionConfig"),
245
+ ("plbart", "PLBartConfig"),
246
+ ("poolformer", "PoolFormerConfig"),
247
+ ("pop2piano", "Pop2PianoConfig"),
248
+ ("prompt_depth_anything", "PromptDepthAnythingConfig"),
249
+ ("prophetnet", "ProphetNetConfig"),
250
+ ("pvt", "PvtConfig"),
251
+ ("pvt_v2", "PvtV2Config"),
252
+ ("qdqbert", "QDQBertConfig"),
253
+ ("qwen2", "Qwen2Config"),
254
+ ("qwen2_5_vl", "Qwen2_5_VLConfig"),
255
+ ("qwen2_audio", "Qwen2AudioConfig"),
256
+ ("qwen2_audio_encoder", "Qwen2AudioEncoderConfig"),
257
+ ("qwen2_moe", "Qwen2MoeConfig"),
258
+ ("qwen2_vl", "Qwen2VLConfig"),
259
+ ("qwen3", "Qwen3Config"),
260
+ ("qwen3_moe", "Qwen3MoeConfig"),
261
+ ("rag", "RagConfig"),
262
+ ("realm", "RealmConfig"),
263
+ ("recurrent_gemma", "RecurrentGemmaConfig"),
264
+ ("reformer", "ReformerConfig"),
265
+ ("regnet", "RegNetConfig"),
266
+ ("rembert", "RemBertConfig"),
267
+ ("resnet", "ResNetConfig"),
268
+ ("retribert", "RetriBertConfig"),
269
+ ("roberta", "RobertaConfig"),
270
+ ("roberta-prelayernorm", "RobertaPreLayerNormConfig"),
271
+ ("roc_bert", "RoCBertConfig"),
272
+ ("roformer", "RoFormerConfig"),
273
+ ("rt_detr", "RTDetrConfig"),
274
+ ("rt_detr_resnet", "RTDetrResNetConfig"),
275
+ ("rt_detr_v2", "RTDetrV2Config"),
276
+ ("rwkv", "RwkvConfig"),
277
+ ("sam", "SamConfig"),
278
+ ("sam_vision_model", "SamVisionConfig"),
279
+ ("seamless_m4t", "SeamlessM4TConfig"),
280
+ ("seamless_m4t_v2", "SeamlessM4Tv2Config"),
281
+ ("segformer", "SegformerConfig"),
282
+ ("seggpt", "SegGptConfig"),
283
+ ("sew", "SEWConfig"),
284
+ ("sew-d", "SEWDConfig"),
285
+ ("shieldgemma2", "ShieldGemma2Config"),
286
+ ("siglip", "SiglipConfig"),
287
+ ("siglip2", "Siglip2Config"),
288
+ ("siglip_vision_model", "SiglipVisionConfig"),
289
+ ("smolvlm", "SmolVLMConfig"),
290
+ ("smolvlm_vision", "SmolVLMVisionConfig"),
291
+ ("speech-encoder-decoder", "SpeechEncoderDecoderConfig"),
292
+ ("speech_to_text", "Speech2TextConfig"),
293
+ ("speech_to_text_2", "Speech2Text2Config"),
294
+ ("speecht5", "SpeechT5Config"),
295
+ ("splinter", "SplinterConfig"),
296
+ ("squeezebert", "SqueezeBertConfig"),
297
+ ("stablelm", "StableLmConfig"),
298
+ ("starcoder2", "Starcoder2Config"),
299
+ ("superglue", "SuperGlueConfig"),
300
+ ("superpoint", "SuperPointConfig"),
301
+ ("swiftformer", "SwiftFormerConfig"),
302
+ ("swin", "SwinConfig"),
303
+ ("swin2sr", "Swin2SRConfig"),
304
+ ("swinv2", "Swinv2Config"),
305
+ ("switch_transformers", "SwitchTransformersConfig"),
306
+ ("t5", "T5Config"),
307
+ ("table-transformer", "TableTransformerConfig"),
308
+ ("tapas", "TapasConfig"),
309
+ ("textnet", "TextNetConfig"),
310
+ ("time_series_transformer", "TimeSeriesTransformerConfig"),
311
+ ("timesformer", "TimesformerConfig"),
312
+ ("timm_backbone", "TimmBackboneConfig"),
313
+ ("timm_wrapper", "TimmWrapperConfig"),
314
+ ("trajectory_transformer", "TrajectoryTransformerConfig"),
315
+ ("transfo-xl", "TransfoXLConfig"),
316
+ ("trocr", "TrOCRConfig"),
317
+ ("tvlt", "TvltConfig"),
318
+ ("tvp", "TvpConfig"),
319
+ ("udop", "UdopConfig"),
320
+ ("umt5", "UMT5Config"),
321
+ ("unispeech", "UniSpeechConfig"),
322
+ ("unispeech-sat", "UniSpeechSatConfig"),
323
+ ("univnet", "UnivNetConfig"),
324
+ ("upernet", "UperNetConfig"),
325
+ ("van", "VanConfig"),
326
+ ("video_llava", "VideoLlavaConfig"),
327
+ ("videomae", "VideoMAEConfig"),
328
+ ("vilt", "ViltConfig"),
329
+ ("vipllava", "VipLlavaConfig"),
330
+ ("vision-encoder-decoder", "VisionEncoderDecoderConfig"),
331
+ ("vision-text-dual-encoder", "VisionTextDualEncoderConfig"),
332
+ ("visual_bert", "VisualBertConfig"),
333
+ ("vit", "ViTConfig"),
334
+ ("vit_hybrid", "ViTHybridConfig"),
335
+ ("vit_mae", "ViTMAEConfig"),
336
+ ("vit_msn", "ViTMSNConfig"),
337
+ ("vitdet", "VitDetConfig"),
338
+ ("vitmatte", "VitMatteConfig"),
339
+ ("vitpose", "VitPoseConfig"),
340
+ ("vitpose_backbone", "VitPoseBackboneConfig"),
341
+ ("vits", "VitsConfig"),
342
+ ("vivit", "VivitConfig"),
343
+ ("wav2vec2", "Wav2Vec2Config"),
344
+ ("wav2vec2-bert", "Wav2Vec2BertConfig"),
345
+ ("wav2vec2-conformer", "Wav2Vec2ConformerConfig"),
346
+ ("wavlm", "WavLMConfig"),
347
+ ("whisper", "WhisperConfig"),
348
+ ("xclip", "XCLIPConfig"),
349
+ ("xglm", "XGLMConfig"),
350
+ ("xlm", "XLMConfig"),
351
+ ("xlm-prophetnet", "XLMProphetNetConfig"),
352
+ ("xlm-roberta", "XLMRobertaConfig"),
353
+ ("xlm-roberta-xl", "XLMRobertaXLConfig"),
354
+ ("xlnet", "XLNetConfig"),
355
+ ("xmod", "XmodConfig"),
356
+ ("yolos", "YolosConfig"),
357
+ ("yoso", "YosoConfig"),
358
+ ("zamba", "ZambaConfig"),
359
+ ("zamba2", "Zamba2Config"),
360
+ ("zoedepth", "ZoeDepthConfig"),
361
+ ]
362
+ )
363
+
364
+
365
+ MODEL_NAMES_MAPPING = OrderedDict(
366
+ [
367
+ # Add full (and cased) model names here
368
+ ("albert", "ALBERT"),
369
+ ("align", "ALIGN"),
370
+ ("altclip", "AltCLIP"),
371
+ ("aria", "Aria"),
372
+ ("aria_text", "AriaText"),
373
+ ("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
374
+ ("autoformer", "Autoformer"),
375
+ ("aya_vision", "AyaVision"),
376
+ ("bamba", "Bamba"),
377
+ ("bark", "Bark"),
378
+ ("bart", "BART"),
379
+ ("barthez", "BARThez"),
380
+ ("bartpho", "BARTpho"),
381
+ ("beit", "BEiT"),
382
+ ("bert", "BERT"),
383
+ ("bert-generation", "Bert Generation"),
384
+ ("bert-japanese", "BertJapanese"),
385
+ ("bertweet", "BERTweet"),
386
+ ("big_bird", "BigBird"),
387
+ ("bigbird_pegasus", "BigBird-Pegasus"),
388
+ ("biogpt", "BioGpt"),
389
+ ("bit", "BiT"),
390
+ ("blenderbot", "Blenderbot"),
391
+ ("blenderbot-small", "BlenderbotSmall"),
392
+ ("blip", "BLIP"),
393
+ ("blip-2", "BLIP-2"),
394
+ ("bloom", "BLOOM"),
395
+ ("bort", "BORT"),
396
+ ("bridgetower", "BridgeTower"),
397
+ ("bros", "BROS"),
398
+ ("byt5", "ByT5"),
399
+ ("camembert", "CamemBERT"),
400
+ ("canine", "CANINE"),
401
+ ("chameleon", "Chameleon"),
402
+ ("chinese_clip", "Chinese-CLIP"),
403
+ ("chinese_clip_vision_model", "ChineseCLIPVisionModel"),
404
+ ("clap", "CLAP"),
405
+ ("clip", "CLIP"),
406
+ ("clip_text_model", "CLIPTextModel"),
407
+ ("clip_vision_model", "CLIPVisionModel"),
408
+ ("clipseg", "CLIPSeg"),
409
+ ("clvp", "CLVP"),
410
+ ("code_llama", "CodeLlama"),
411
+ ("codegen", "CodeGen"),
412
+ ("cohere", "Cohere"),
413
+ ("cohere2", "Cohere2"),
414
+ ("colpali", "ColPali"),
415
+ ("conditional_detr", "Conditional DETR"),
416
+ ("convbert", "ConvBERT"),
417
+ ("convnext", "ConvNeXT"),
418
+ ("convnextv2", "ConvNeXTV2"),
419
+ ("cpm", "CPM"),
420
+ ("cpmant", "CPM-Ant"),
421
+ ("ctrl", "CTRL"),
422
+ ("cvt", "CvT"),
423
+ ("dab-detr", "DAB-DETR"),
424
+ ("dac", "DAC"),
425
+ ("data2vec-audio", "Data2VecAudio"),
426
+ ("data2vec-text", "Data2VecText"),
427
+ ("data2vec-vision", "Data2VecVision"),
428
+ ("dbrx", "DBRX"),
429
+ ("deberta", "DeBERTa"),
430
+ ("deberta-v2", "DeBERTa-v2"),
431
+ ("decision_transformer", "Decision Transformer"),
432
+ ("deepseek_v3", "DeepSeek-V3"),
433
+ ("deformable_detr", "Deformable DETR"),
434
+ ("deit", "DeiT"),
435
+ ("deplot", "DePlot"),
436
+ ("depth_anything", "Depth Anything"),
437
+ ("depth_anything_v2", "Depth Anything V2"),
438
+ ("depth_pro", "DepthPro"),
439
+ ("deta", "DETA"),
440
+ ("detr", "DETR"),
441
+ ("dialogpt", "DialoGPT"),
442
+ ("diffllama", "DiffLlama"),
443
+ ("dinat", "DiNAT"),
444
+ ("dinov2", "DINOv2"),
445
+ ("dinov2_with_registers", "DINOv2 with Registers"),
446
+ ("distilbert", "DistilBERT"),
447
+ ("dit", "DiT"),
448
+ ("donut-swin", "DonutSwin"),
449
+ ("dpr", "DPR"),
450
+ ("dpt", "DPT"),
451
+ ("efficientformer", "EfficientFormer"),
452
+ ("efficientnet", "EfficientNet"),
453
+ ("electra", "ELECTRA"),
454
+ ("emu3", "Emu3"),
455
+ ("encodec", "EnCodec"),
456
+ ("encoder-decoder", "Encoder decoder"),
457
+ ("ernie", "ERNIE"),
458
+ ("ernie_m", "ErnieM"),
459
+ ("esm", "ESM"),
460
+ ("falcon", "Falcon"),
461
+ ("falcon3", "Falcon3"),
462
+ ("falcon_mamba", "FalconMamba"),
463
+ ("fastspeech2_conformer", "FastSpeech2Conformer"),
464
+ ("flan-t5", "FLAN-T5"),
465
+ ("flan-ul2", "FLAN-UL2"),
466
+ ("flaubert", "FlauBERT"),
467
+ ("flava", "FLAVA"),
468
+ ("fnet", "FNet"),
469
+ ("focalnet", "FocalNet"),
470
+ ("fsmt", "FairSeq Machine-Translation"),
471
+ ("funnel", "Funnel Transformer"),
472
+ ("fuyu", "Fuyu"),
473
+ ("gemma", "Gemma"),
474
+ ("gemma2", "Gemma2"),
475
+ ("gemma3", "Gemma3ForConditionalGeneration"),
476
+ ("gemma3_text", "Gemma3ForCausalLM"),
477
+ ("git", "GIT"),
478
+ ("glm", "GLM"),
479
+ ("glpn", "GLPN"),
480
+ ("got_ocr2", "GOT-OCR2"),
481
+ ("gpt-sw3", "GPT-Sw3"),
482
+ ("gpt2", "OpenAI GPT-2"),
483
+ ("gpt_bigcode", "GPTBigCode"),
484
+ ("gpt_neo", "GPT Neo"),
485
+ ("gpt_neox", "GPT NeoX"),
486
+ ("gpt_neox_japanese", "GPT NeoX Japanese"),
487
+ ("gptj", "GPT-J"),
488
+ ("gptsan-japanese", "GPTSAN-japanese"),
489
+ ("granite", "Granite"),
490
+ ("granitemoe", "GraniteMoeMoe"),
491
+ ("granitemoeshared", "GraniteMoeSharedMoe"),
492
+ ("granitevision", "LLaVA-NeXT"),
493
+ ("graphormer", "Graphormer"),
494
+ ("grounding-dino", "Grounding DINO"),
495
+ ("groupvit", "GroupViT"),
496
+ ("helium", "Helium"),
497
+ ("herbert", "HerBERT"),
498
+ ("hiera", "Hiera"),
499
+ ("hubert", "Hubert"),
500
+ ("ibert", "I-BERT"),
501
+ ("idefics", "IDEFICS"),
502
+ ("idefics2", "Idefics2"),
503
+ ("idefics3", "Idefics3"),
504
+ ("idefics3_vision", "Idefics3VisionTransformer"),
505
+ ("ijepa", "I-JEPA"),
506
+ ("imagegpt", "ImageGPT"),
507
+ ("informer", "Informer"),
508
+ ("instructblip", "InstructBLIP"),
509
+ ("instructblipvideo", "InstructBlipVideo"),
510
+ ("jamba", "Jamba"),
511
+ ("jetmoe", "JetMoe"),
512
+ ("jukebox", "Jukebox"),
513
+ ("kosmos-2", "KOSMOS-2"),
514
+ ("layoutlm", "LayoutLM"),
515
+ ("layoutlmv2", "LayoutLMv2"),
516
+ ("layoutlmv3", "LayoutLMv3"),
517
+ ("layoutxlm", "LayoutXLM"),
518
+ ("led", "LED"),
519
+ ("levit", "LeViT"),
520
+ ("lilt", "LiLT"),
521
+ ("llama", "LLaMA"),
522
+ ("llama2", "Llama2"),
523
+ ("llama3", "Llama3"),
524
+ ("llama4", "Llama4"),
525
+ ("llama4_text", "Llama4ForCausalLM"),
526
+ ("llava", "LLaVa"),
527
+ ("llava_next", "LLaVA-NeXT"),
528
+ ("llava_next_video", "LLaVa-NeXT-Video"),
529
+ ("llava_onevision", "LLaVA-Onevision"),
530
+ ("longformer", "Longformer"),
531
+ ("longt5", "LongT5"),
532
+ ("luke", "LUKE"),
533
+ ("lxmert", "LXMERT"),
534
+ ("m2m_100", "M2M100"),
535
+ ("madlad-400", "MADLAD-400"),
536
+ ("mamba", "Mamba"),
537
+ ("mamba2", "mamba2"),
538
+ ("marian", "Marian"),
539
+ ("markuplm", "MarkupLM"),
540
+ ("mask2former", "Mask2Former"),
541
+ ("maskformer", "MaskFormer"),
542
+ ("maskformer-swin", "MaskFormerSwin"),
543
+ ("matcha", "MatCha"),
544
+ ("mbart", "mBART"),
545
+ ("mbart50", "mBART-50"),
546
+ ("mctct", "M-CTC-T"),
547
+ ("mega", "MEGA"),
548
+ ("megatron-bert", "Megatron-BERT"),
549
+ ("megatron_gpt2", "Megatron-GPT2"),
550
+ ("mgp-str", "MGP-STR"),
551
+ ("mimi", "Mimi"),
552
+ ("mistral", "Mistral"),
553
+ ("mistral3", "Mistral3"),
554
+ ("mixtral", "Mixtral"),
555
+ ("mllama", "Mllama"),
556
+ ("mluke", "mLUKE"),
557
+ ("mms", "MMS"),
558
+ ("mobilebert", "MobileBERT"),
559
+ ("mobilenet_v1", "MobileNetV1"),
560
+ ("mobilenet_v2", "MobileNetV2"),
561
+ ("mobilevit", "MobileViT"),
562
+ ("mobilevitv2", "MobileViTV2"),
563
+ ("modernbert", "ModernBERT"),
564
+ ("moonshine", "Moonshine"),
565
+ ("moshi", "Moshi"),
566
+ ("mpnet", "MPNet"),
567
+ ("mpt", "MPT"),
568
+ ("mra", "MRA"),
569
+ ("mt5", "MT5"),
570
+ ("musicgen", "MusicGen"),
571
+ ("musicgen_melody", "MusicGen Melody"),
572
+ ("mvp", "MVP"),
573
+ ("myt5", "myt5"),
574
+ ("nat", "NAT"),
575
+ ("nemotron", "Nemotron"),
576
+ ("nezha", "Nezha"),
577
+ ("nllb", "NLLB"),
578
+ ("nllb-moe", "NLLB-MOE"),
579
+ ("nougat", "Nougat"),
580
+ ("nystromformer", "Nyströmformer"),
581
+ ("olmo", "OLMo"),
582
+ ("olmo2", "OLMo2"),
583
+ ("olmoe", "OLMoE"),
584
+ ("omdet-turbo", "OmDet-Turbo"),
585
+ ("oneformer", "OneFormer"),
586
+ ("open-llama", "OpenLlama"),
587
+ ("openai-gpt", "OpenAI GPT"),
588
+ ("opt", "OPT"),
589
+ ("owlv2", "OWLv2"),
590
+ ("owlvit", "OWL-ViT"),
591
+ ("paligemma", "PaliGemma"),
592
+ ("patchtsmixer", "PatchTSMixer"),
593
+ ("patchtst", "PatchTST"),
594
+ ("pegasus", "Pegasus"),
595
+ ("pegasus_x", "PEGASUS-X"),
596
+ ("perceiver", "Perceiver"),
597
+ ("persimmon", "Persimmon"),
598
+ ("phi", "Phi"),
599
+ ("phi3", "Phi3"),
600
+ ("phi4_multimodal", "Phi4Multimodal"),
601
+ ("phimoe", "Phimoe"),
602
+ ("phobert", "PhoBERT"),
603
+ ("pix2struct", "Pix2Struct"),
604
+ ("pixtral", "Pixtral"),
605
+ ("plbart", "PLBart"),
606
+ ("poolformer", "PoolFormer"),
607
+ ("pop2piano", "Pop2Piano"),
608
+ ("prompt_depth_anything", "PromptDepthAnything"),
609
+ ("prophetnet", "ProphetNet"),
610
+ ("pvt", "PVT"),
611
+ ("pvt_v2", "PVTv2"),
612
+ ("qdqbert", "QDQBert"),
613
+ ("qwen2", "Qwen2"),
614
+ ("qwen2_5_vl", "Qwen2_5_VL"),
615
+ ("qwen2_audio", "Qwen2Audio"),
616
+ ("qwen2_audio_encoder", "Qwen2AudioEncoder"),
617
+ ("qwen2_moe", "Qwen2MoE"),
618
+ ("qwen2_vl", "Qwen2VL"),
619
+ ("qwen3", "Qwen3"),
620
+ ("qwen3_moe", "Qwen3MoE"),
621
+ ("rag", "RAG"),
622
+ ("realm", "REALM"),
623
+ ("recurrent_gemma", "RecurrentGemma"),
624
+ ("reformer", "Reformer"),
625
+ ("regnet", "RegNet"),
626
+ ("rembert", "RemBERT"),
627
+ ("resnet", "ResNet"),
628
+ ("retribert", "RetriBERT"),
629
+ ("roberta", "RoBERTa"),
630
+ ("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
631
+ ("roc_bert", "RoCBert"),
632
+ ("roformer", "RoFormer"),
633
+ ("rt_detr", "RT-DETR"),
634
+ ("rt_detr_resnet", "RT-DETR-ResNet"),
635
+ ("rt_detr_v2", "RT-DETRv2"),
636
+ ("rwkv", "RWKV"),
637
+ ("sam", "SAM"),
638
+ ("sam_vision_model", "SamVisionModel"),
639
+ ("seamless_m4t", "SeamlessM4T"),
640
+ ("seamless_m4t_v2", "SeamlessM4Tv2"),
641
+ ("segformer", "SegFormer"),
642
+ ("seggpt", "SegGPT"),
643
+ ("sew", "SEW"),
644
+ ("sew-d", "SEW-D"),
645
+ ("shieldgemma2", "Shieldgemma2"),
646
+ ("siglip", "SigLIP"),
647
+ ("siglip2", "SigLIP2"),
648
+ ("siglip2_vision_model", "Siglip2VisionModel"),
649
+ ("siglip_vision_model", "SiglipVisionModel"),
650
+ ("smolvlm", "SmolVLM"),
651
+ ("smolvlm_vision", "SmolVLMVisionTransformer"),
652
+ ("speech-encoder-decoder", "Speech Encoder decoder"),
653
+ ("speech_to_text", "Speech2Text"),
654
+ ("speech_to_text_2", "Speech2Text2"),
655
+ ("speecht5", "SpeechT5"),
656
+ ("splinter", "Splinter"),
657
+ ("squeezebert", "SqueezeBERT"),
658
+ ("stablelm", "StableLm"),
659
+ ("starcoder2", "Starcoder2"),
660
+ ("superglue", "SuperGlue"),
661
+ ("superpoint", "SuperPoint"),
662
+ ("swiftformer", "SwiftFormer"),
663
+ ("swin", "Swin Transformer"),
664
+ ("swin2sr", "Swin2SR"),
665
+ ("swinv2", "Swin Transformer V2"),
666
+ ("switch_transformers", "SwitchTransformers"),
667
+ ("t5", "T5"),
668
+ ("t5v1.1", "T5v1.1"),
669
+ ("table-transformer", "Table Transformer"),
670
+ ("tapas", "TAPAS"),
671
+ ("tapex", "TAPEX"),
672
+ ("textnet", "TextNet"),
673
+ ("time_series_transformer", "Time Series Transformer"),
674
+ ("timesformer", "TimeSformer"),
675
+ ("timm_backbone", "TimmBackbone"),
676
+ ("timm_wrapper", "TimmWrapperModel"),
677
+ ("trajectory_transformer", "Trajectory Transformer"),
678
+ ("transfo-xl", "Transformer-XL"),
679
+ ("trocr", "TrOCR"),
680
+ ("tvlt", "TVLT"),
681
+ ("tvp", "TVP"),
682
+ ("udop", "UDOP"),
683
+ ("ul2", "UL2"),
684
+ ("umt5", "UMT5"),
685
+ ("unispeech", "UniSpeech"),
686
+ ("unispeech-sat", "UniSpeechSat"),
687
+ ("univnet", "UnivNet"),
688
+ ("upernet", "UPerNet"),
689
+ ("van", "VAN"),
690
+ ("video_llava", "VideoLlava"),
691
+ ("videomae", "VideoMAE"),
692
+ ("vilt", "ViLT"),
693
+ ("vipllava", "VipLlava"),
694
+ ("vision-encoder-decoder", "Vision Encoder decoder"),
695
+ ("vision-text-dual-encoder", "VisionTextDualEncoder"),
696
+ ("visual_bert", "VisualBERT"),
697
+ ("vit", "ViT"),
698
+ ("vit_hybrid", "ViT Hybrid"),
699
+ ("vit_mae", "ViTMAE"),
700
+ ("vit_msn", "ViTMSN"),
701
+ ("vitdet", "VitDet"),
702
+ ("vitmatte", "ViTMatte"),
703
+ ("vitpose", "ViTPose"),
704
+ ("vitpose_backbone", "ViTPoseBackbone"),
705
+ ("vits", "VITS"),
706
+ ("vivit", "ViViT"),
707
+ ("wav2vec2", "Wav2Vec2"),
708
+ ("wav2vec2-bert", "Wav2Vec2-BERT"),
709
+ ("wav2vec2-conformer", "Wav2Vec2-Conformer"),
710
+ ("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
711
+ ("wavlm", "WavLM"),
712
+ ("whisper", "Whisper"),
713
+ ("xclip", "X-CLIP"),
714
+ ("xglm", "XGLM"),
715
+ ("xlm", "XLM"),
716
+ ("xlm-prophetnet", "XLM-ProphetNet"),
717
+ ("xlm-roberta", "XLM-RoBERTa"),
718
+ ("xlm-roberta-xl", "XLM-RoBERTa-XL"),
719
+ ("xlm-v", "XLM-V"),
720
+ ("xlnet", "XLNet"),
721
+ ("xls_r", "XLS-R"),
722
+ ("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
723
+ ("xmod", "X-MOD"),
724
+ ("yolos", "YOLOS"),
725
+ ("yoso", "YOSO"),
726
+ ("zamba", "Zamba"),
727
+ ("zamba2", "Zamba2"),
728
+ ("zoedepth", "ZoeDepth"),
729
+ ]
730
+ )
731
+
732
+ # This is tied to the processing `-` -> `_` in `model_type_to_module_name`. For example, instead of putting
733
+ # `transfo-xl` (as in `CONFIG_MAPPING_NAMES`), we should use `transfo_xl`.
734
+ DEPRECATED_MODELS = [
735
+ "bort",
736
+ "deta",
737
+ "efficientformer",
738
+ "ernie_m",
739
+ "gptsan_japanese",
740
+ "graphormer",
741
+ "jukebox",
742
+ "mctct",
743
+ "mega",
744
+ "mmbt",
745
+ "nat",
746
+ "nezha",
747
+ "open_llama",
748
+ "qdqbert",
749
+ "realm",
750
+ "retribert",
751
+ "speech_to_text_2",
752
+ "tapex",
753
+ "trajectory_transformer",
754
+ "transfo_xl",
755
+ "tvlt",
756
+ "van",
757
+ "vit_hybrid",
758
+ "xlm_prophetnet",
759
+ ]
760
+
761
+ SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
762
+ [
763
+ ("openai-gpt", "openai"),
764
+ ("data2vec-audio", "data2vec"),
765
+ ("data2vec-text", "data2vec"),
766
+ ("data2vec-vision", "data2vec"),
767
+ ("donut-swin", "donut"),
768
+ ("kosmos-2", "kosmos2"),
769
+ ("maskformer-swin", "maskformer"),
770
+ ("xclip", "x_clip"),
771
+ ("clip_vision_model", "clip"),
772
+ ("qwen2_audio_encoder", "qwen2_audio"),
773
+ ("clip_text_model", "clip"),
774
+ ("aria_text", "aria"),
775
+ ("gemma3_text", "gemma3"),
776
+ ("idefics3_vision", "idefics3"),
777
+ ("siglip_vision_model", "siglip"),
778
+ ("smolvlm_vision", "smolvlm"),
779
+ ("chinese_clip_vision_model", "chinese_clip"),
780
+ ("rt_detr_resnet", "rt_detr"),
781
+ ("granitevision", "llava_next"),
782
+ ("sam_vision_model", "sam"),
783
+ ("llama4_text", "llama4"),
784
+ ]
785
+ )
786
+
787
+
788
+ def model_type_to_module_name(key):
789
+ """Converts a config key to the corresponding module."""
790
+ # Special treatment
791
+ if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME:
792
+ key = SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key]
793
+
794
+ if key in DEPRECATED_MODELS:
795
+ key = f"deprecated.{key}"
796
+ return key
797
+
798
+ key = key.replace("-", "_")
799
+ if key in DEPRECATED_MODELS:
800
+ key = f"deprecated.{key}"
801
+
802
+ return key
803
+
804
+
805
+ def config_class_to_model_type(config):
806
+ """Converts a config class name to the corresponding model type"""
807
+ for key, cls in CONFIG_MAPPING_NAMES.items():
808
+ if cls == config:
809
+ return key
810
+ # if key not found check in extra content
811
+ for key, cls in CONFIG_MAPPING._extra_content.items():
812
+ if cls.__name__ == config:
813
+ return key
814
+ return None
815
+
816
+
817
+ class _LazyConfigMapping(OrderedDict):
818
+ """
819
+ A dictionary that lazily load its values when they are requested.
820
+ """
821
+
822
+ def __init__(self, mapping):
823
+ self._mapping = mapping
824
+ self._extra_content = {}
825
+ self._modules = {}
826
+
827
+ def __getitem__(self, key):
828
+ if key in self._extra_content:
829
+ return self._extra_content[key]
830
+ if key not in self._mapping:
831
+ raise KeyError(key)
832
+ value = self._mapping[key]
833
+ module_name = model_type_to_module_name(key)
834
+ if module_name not in self._modules:
835
+ self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
836
+ if hasattr(self._modules[module_name], value):
837
+ return getattr(self._modules[module_name], value)
838
+
839
+ # Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the
840
+ # object at the top level.
841
+ transformers_module = importlib.import_module("transformers")
842
+ return getattr(transformers_module, value)
843
+
844
+ def keys(self):
845
+ return list(self._mapping.keys()) + list(self._extra_content.keys())
846
+
847
+ def values(self):
848
+ return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values())
849
+
850
+ def items(self):
851
+ return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
852
+
853
+ def __iter__(self):
854
+ return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
855
+
856
+ def __contains__(self, item):
857
+ return item in self._mapping or item in self._extra_content
858
+
859
+ def register(self, key, value, exist_ok=False):
860
+ """
861
+ Register a new configuration in this mapping.
862
+ """
863
+ if key in self._mapping.keys() and not exist_ok:
864
+ raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.")
865
+ self._extra_content[key] = value
866
+
867
+
868
+ CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES)
869
+
870
+
871
+ class _LazyLoadAllMappings(OrderedDict):
872
+ """
873
+ A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values,
874
+ etc.)
875
+
876
+ Args:
877
+ mapping: The mapping to load.
878
+ """
879
+
880
+ def __init__(self, mapping):
881
+ self._mapping = mapping
882
+ self._initialized = False
883
+ self._data = {}
884
+
885
+ def _initialize(self):
886
+ if self._initialized:
887
+ return
888
+
889
+ for model_type, map_name in self._mapping.items():
890
+ module_name = model_type_to_module_name(model_type)
891
+ module = importlib.import_module(f".{module_name}", "transformers.models")
892
+ mapping = getattr(module, map_name)
893
+ self._data.update(mapping)
894
+
895
+ self._initialized = True
896
+
897
+ def __getitem__(self, key):
898
+ self._initialize()
899
+ return self._data[key]
900
+
901
+ def keys(self):
902
+ self._initialize()
903
+ return self._data.keys()
904
+
905
+ def values(self):
906
+ self._initialize()
907
+ return self._data.values()
908
+
909
+ def items(self):
910
+ self._initialize()
911
+ return self._data.keys()
912
+
913
+ def __iter__(self):
914
+ self._initialize()
915
+ return iter(self._data)
916
+
917
+ def __contains__(self, item):
918
+ self._initialize()
919
+ return item in self._data
920
+
921
+
922
+ def _get_class_name(model_class: Union[str, List[str]]):
923
+ if isinstance(model_class, (list, tuple)):
924
+ return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
925
+ return f"[`{model_class}`]"
926
+
927
+
928
+ def _list_model_options(indent, config_to_class=None, use_model_types=True):
929
+ if config_to_class is None and not use_model_types:
930
+ raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.")
931
+ if use_model_types:
932
+ if config_to_class is None:
933
+ model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
934
+ else:
935
+ model_type_to_name = {
936
+ model_type: _get_class_name(model_class)
937
+ for model_type, model_class in config_to_class.items()
938
+ if model_type in MODEL_NAMES_MAPPING
939
+ }
940
+ lines = [
941
+ f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
942
+ for model_type in sorted(model_type_to_name.keys())
943
+ ]
944
+ else:
945
+ config_to_name = {
946
+ CONFIG_MAPPING_NAMES[config]: _get_class_name(clas)
947
+ for config, clas in config_to_class.items()
948
+ if config in CONFIG_MAPPING_NAMES
949
+ }
950
+ config_to_model_name = {
951
+ config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
952
+ }
953
+ lines = [
954
+ f"{indent}- [`{config_name}`] configuration class:"
955
+ f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
956
+ for config_name in sorted(config_to_name.keys())
957
+ ]
958
+ return "\n".join(lines)
959
+
960
+
961
+ def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True):
962
+ def docstring_decorator(fn):
963
+ docstrings = fn.__doc__
964
+ if docstrings is None:
965
+ # Example: -OO
966
+ return fn
967
+ lines = docstrings.split("\n")
968
+ i = 0
969
+ while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None:
970
+ i += 1
971
+ if i < len(lines):
972
+ indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
973
+ if use_model_types:
974
+ indent = f"{indent} "
975
+ lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
976
+ docstrings = "\n".join(lines)
977
+ else:
978
+ raise ValueError(
979
+ f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
980
+ f" docstring is:\n{docstrings}"
981
+ )
982
+ fn.__doc__ = docstrings
983
+ return fn
984
+
985
+ return docstring_decorator
986
+
987
+
988
+ class AutoConfig:
989
+ r"""
990
+ This is a generic configuration class that will be instantiated as one of the configuration classes of the library
991
+ when created with the [`~AutoConfig.from_pretrained`] class method.
992
+
993
+ This class cannot be instantiated directly using `__init__()` (throws an error).
994
+ """
995
+
996
+ def __init__(self):
997
+ raise EnvironmentError(
998
+ "AutoConfig is designed to be instantiated "
999
+ "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
1000
+ )
1001
+
1002
+ @classmethod
1003
+ def for_model(cls, model_type: str, *args, **kwargs):
1004
+ if model_type in CONFIG_MAPPING:
1005
+ config_class = CONFIG_MAPPING[model_type]
1006
+ return config_class(*args, **kwargs)
1007
+ raise ValueError(
1008
+ f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
1009
+ )
1010
+
1011
+ @classmethod
1012
+ @replace_list_option_in_docstrings()
1013
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
1014
+ r"""
1015
+ Instantiate one of the configuration classes of the library from a pretrained model configuration.
1016
+
1017
+ The configuration class to instantiate is selected based on the `model_type` property of the config object that
1018
+ is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
1019
+
1020
+ List options
1021
+
1022
+ Args:
1023
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
1024
+ Can be either:
1025
+
1026
+ - A string, the *model id* of a pretrained model configuration hosted inside a model repo on
1027
+ huggingface.co.
1028
+ - A path to a *directory* containing a configuration file saved using the
1029
+ [`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
1030
+ e.g., `./my_model_directory/`.
1031
+ - A path or url to a saved configuration JSON *file*, e.g.,
1032
+ `./my_model_directory/configuration.json`.
1033
+ cache_dir (`str` or `os.PathLike`, *optional*):
1034
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
1035
+ standard cache should not be used.
1036
+ force_download (`bool`, *optional*, defaults to `False`):
1037
+ Whether or not to force the (re-)download the model weights and configuration files and override the
1038
+ cached versions if they exist.
1039
+ resume_download:
1040
+ Deprecated and ignored. All downloads are now resumed by default when possible.
1041
+ Will be removed in v5 of Transformers.
1042
+ proxies (`Dict[str, str]`, *optional*):
1043
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
1044
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
1045
+ revision (`str`, *optional*, defaults to `"main"`):
1046
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
1047
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
1048
+ identifier allowed by git.
1049
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
1050
+ If `False`, then this function returns just the final configuration object.
1051
+
1052
+ If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
1053
+ dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
1054
+ part of `kwargs` which has not been used to update `config` and is otherwise ignored.
1055
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
1056
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
1057
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
1058
+ execute code present on the Hub on your local machine.
1059
+ kwargs(additional keyword arguments, *optional*):
1060
+ The values in kwargs of any keys which are configuration attributes will be used to override the loaded
1061
+ values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
1062
+ by the `return_unused_kwargs` keyword parameter.
1063
+
1064
+ Examples:
1065
+
1066
+ ```python
1067
+ >>> from transformers import AutoConfig
1068
+
1069
+ >>> # Download configuration from huggingface.co and cache.
1070
+ >>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
1071
+
1072
+ >>> # Download configuration from huggingface.co (user-uploaded) and cache.
1073
+ >>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
1074
+
1075
+ >>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
1076
+ >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
1077
+
1078
+ >>> # Load a specific configuration file.
1079
+ >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
1080
+
1081
+ >>> # Change some config attributes when loading a pretrained config.
1082
+ >>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
1083
+ >>> config.output_attentions
1084
+ True
1085
+
1086
+ >>> config, unused_kwargs = AutoConfig.from_pretrained(
1087
+ ... "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
1088
+ ... )
1089
+ >>> config.output_attentions
1090
+ True
1091
+
1092
+ >>> unused_kwargs
1093
+ {'foo': False}
1094
+ ```"""
1095
+ use_auth_token = kwargs.pop("use_auth_token", None)
1096
+ if use_auth_token is not None:
1097
+ warnings.warn(
1098
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
1099
+ FutureWarning,
1100
+ )
1101
+ if kwargs.get("token", None) is not None:
1102
+ raise ValueError(
1103
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
1104
+ )
1105
+ kwargs["token"] = use_auth_token
1106
+
1107
+ kwargs["_from_auto"] = True
1108
+ kwargs["name_or_path"] = pretrained_model_name_or_path
1109
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
1110
+ code_revision = kwargs.pop("code_revision", None)
1111
+
1112
+ config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
1113
+ has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]
1114
+ has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING
1115
+ trust_remote_code = resolve_trust_remote_code(
1116
+ trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
1117
+ )
1118
+
1119
+ if has_remote_code and trust_remote_code:
1120
+ class_ref = config_dict["auto_map"]["AutoConfig"]
1121
+ config_class = get_class_from_dynamic_module(
1122
+ class_ref, pretrained_model_name_or_path, code_revision=code_revision, **kwargs
1123
+ )
1124
+ if os.path.isdir(pretrained_model_name_or_path):
1125
+ config_class.register_for_auto_class()
1126
+ return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
1127
+ elif "model_type" in config_dict:
1128
+ try:
1129
+ config_class = CONFIG_MAPPING[config_dict["model_type"]]
1130
+ except KeyError:
1131
+ raise ValueError(
1132
+ f"The checkpoint you are trying to load has model type `{config_dict['model_type']}` "
1133
+ "but Transformers does not recognize this architecture. This could be because of an "
1134
+ "issue with the checkpoint, or because your version of Transformers is out of date.\n\n"
1135
+ "You can update Transformers with the command `pip install --upgrade transformers`. If this "
1136
+ "does not work, and the checkpoint is very new, then there may not be a release version "
1137
+ "that supports this model yet. In this case, you can get the most up-to-date code by installing "
1138
+ "Transformers from source with the command "
1139
+ "`pip install git+https://github.com/huggingface/transformers.git`"
1140
+ )
1141
+ return config_class.from_dict(config_dict, **unused_kwargs)
1142
+ else:
1143
+ # Fallback: use pattern matching on the string.
1144
+ # We go from longer names to shorter names to catch roberta before bert (for instance)
1145
+ for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True):
1146
+ if pattern in str(pretrained_model_name_or_path):
1147
+ return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
1148
+
1149
+ raise ValueError(
1150
+ f"Unrecognized model in {pretrained_model_name_or_path}. "
1151
+ f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
1152
+ f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
1153
+ )
1154
+
1155
+ @staticmethod
1156
+ def register(model_type, config, exist_ok=False):
1157
+ """
1158
+ Register a new configuration for this class.
1159
+
1160
+ Args:
1161
+ model_type (`str`): The model type like "bert" or "gpt".
1162
+ config ([`PretrainedConfig`]): The config to register.
1163
+ """
1164
+ if issubclass(config, PretrainedConfig) and config.model_type != model_type:
1165
+ raise ValueError(
1166
+ "The config you are passing has a `model_type` attribute that is not consistent with the model type "
1167
+ f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they "
1168
+ "match!"
1169
+ )
1170
+ CONFIG_MAPPING.register(model_type, config, exist_ok=exist_ok)
lib/python3.12/site-packages/transformers/models/auto/feature_extraction_auto.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """AutoFeatureExtractor class."""
16
+
17
+ import importlib
18
+ import json
19
+ import os
20
+ import warnings
21
+ from collections import OrderedDict
22
+ from typing import Dict, Optional, Union
23
+
24
+ # Build the list of all feature extractors
25
+ from ...configuration_utils import PretrainedConfig
26
+ from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
27
+ from ...feature_extraction_utils import FeatureExtractionMixin
28
+ from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, cached_file, logging
29
+ from .auto_factory import _LazyAutoMapping
30
+ from .configuration_auto import (
31
+ CONFIG_MAPPING_NAMES,
32
+ AutoConfig,
33
+ model_type_to_module_name,
34
+ replace_list_option_in_docstrings,
35
+ )
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ FEATURE_EXTRACTOR_MAPPING_NAMES = OrderedDict(
41
+ [
42
+ ("audio-spectrogram-transformer", "ASTFeatureExtractor"),
43
+ ("beit", "BeitFeatureExtractor"),
44
+ ("chinese_clip", "ChineseCLIPFeatureExtractor"),
45
+ ("clap", "ClapFeatureExtractor"),
46
+ ("clip", "CLIPFeatureExtractor"),
47
+ ("clipseg", "ViTFeatureExtractor"),
48
+ ("clvp", "ClvpFeatureExtractor"),
49
+ ("conditional_detr", "ConditionalDetrFeatureExtractor"),
50
+ ("convnext", "ConvNextFeatureExtractor"),
51
+ ("cvt", "ConvNextFeatureExtractor"),
52
+ ("dac", "DacFeatureExtractor"),
53
+ ("data2vec-audio", "Wav2Vec2FeatureExtractor"),
54
+ ("data2vec-vision", "BeitFeatureExtractor"),
55
+ ("deformable_detr", "DeformableDetrFeatureExtractor"),
56
+ ("deit", "DeiTFeatureExtractor"),
57
+ ("detr", "DetrFeatureExtractor"),
58
+ ("dinat", "ViTFeatureExtractor"),
59
+ ("donut-swin", "DonutFeatureExtractor"),
60
+ ("dpt", "DPTFeatureExtractor"),
61
+ ("encodec", "EncodecFeatureExtractor"),
62
+ ("flava", "FlavaFeatureExtractor"),
63
+ ("glpn", "GLPNFeatureExtractor"),
64
+ ("groupvit", "CLIPFeatureExtractor"),
65
+ ("hubert", "Wav2Vec2FeatureExtractor"),
66
+ ("imagegpt", "ImageGPTFeatureExtractor"),
67
+ ("layoutlmv2", "LayoutLMv2FeatureExtractor"),
68
+ ("layoutlmv3", "LayoutLMv3FeatureExtractor"),
69
+ ("levit", "LevitFeatureExtractor"),
70
+ ("maskformer", "MaskFormerFeatureExtractor"),
71
+ ("mctct", "MCTCTFeatureExtractor"),
72
+ ("mimi", "EncodecFeatureExtractor"),
73
+ ("mobilenet_v1", "MobileNetV1FeatureExtractor"),
74
+ ("mobilenet_v2", "MobileNetV2FeatureExtractor"),
75
+ ("mobilevit", "MobileViTFeatureExtractor"),
76
+ ("moonshine", "Wav2Vec2FeatureExtractor"),
77
+ ("moshi", "EncodecFeatureExtractor"),
78
+ ("nat", "ViTFeatureExtractor"),
79
+ ("owlvit", "OwlViTFeatureExtractor"),
80
+ ("perceiver", "PerceiverFeatureExtractor"),
81
+ ("phi4_multimodal", "Phi4MultimodalFeatureExtractor"),
82
+ ("poolformer", "PoolFormerFeatureExtractor"),
83
+ ("pop2piano", "Pop2PianoFeatureExtractor"),
84
+ ("regnet", "ConvNextFeatureExtractor"),
85
+ ("resnet", "ConvNextFeatureExtractor"),
86
+ ("seamless_m4t", "SeamlessM4TFeatureExtractor"),
87
+ ("seamless_m4t_v2", "SeamlessM4TFeatureExtractor"),
88
+ ("segformer", "SegformerFeatureExtractor"),
89
+ ("sew", "Wav2Vec2FeatureExtractor"),
90
+ ("sew-d", "Wav2Vec2FeatureExtractor"),
91
+ ("speech_to_text", "Speech2TextFeatureExtractor"),
92
+ ("speecht5", "SpeechT5FeatureExtractor"),
93
+ ("swiftformer", "ViTFeatureExtractor"),
94
+ ("swin", "ViTFeatureExtractor"),
95
+ ("swinv2", "ViTFeatureExtractor"),
96
+ ("table-transformer", "DetrFeatureExtractor"),
97
+ ("timesformer", "VideoMAEFeatureExtractor"),
98
+ ("tvlt", "TvltFeatureExtractor"),
99
+ ("unispeech", "Wav2Vec2FeatureExtractor"),
100
+ ("unispeech-sat", "Wav2Vec2FeatureExtractor"),
101
+ ("univnet", "UnivNetFeatureExtractor"),
102
+ ("van", "ConvNextFeatureExtractor"),
103
+ ("videomae", "VideoMAEFeatureExtractor"),
104
+ ("vilt", "ViltFeatureExtractor"),
105
+ ("vit", "ViTFeatureExtractor"),
106
+ ("vit_mae", "ViTFeatureExtractor"),
107
+ ("vit_msn", "ViTFeatureExtractor"),
108
+ ("wav2vec2", "Wav2Vec2FeatureExtractor"),
109
+ ("wav2vec2-bert", "Wav2Vec2FeatureExtractor"),
110
+ ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"),
111
+ ("wavlm", "Wav2Vec2FeatureExtractor"),
112
+ ("whisper", "WhisperFeatureExtractor"),
113
+ ("xclip", "CLIPFeatureExtractor"),
114
+ ("yolos", "YolosFeatureExtractor"),
115
+ ]
116
+ )
117
+
118
+ FEATURE_EXTRACTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
119
+
120
+
121
+ def feature_extractor_class_from_name(class_name: str):
122
+ for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
123
+ if class_name in extractors:
124
+ module_name = model_type_to_module_name(module_name)
125
+
126
+ module = importlib.import_module(f".{module_name}", "transformers.models")
127
+ try:
128
+ return getattr(module, class_name)
129
+ except AttributeError:
130
+ continue
131
+
132
+ for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
133
+ if getattr(extractor, "__name__", None) == class_name:
134
+ return extractor
135
+
136
+ # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
137
+ # init and we return the proper dummy to get an appropriate error message.
138
+ main_module = importlib.import_module("transformers")
139
+ if hasattr(main_module, class_name):
140
+ return getattr(main_module, class_name)
141
+
142
+ return None
143
+
144
+
145
+ def get_feature_extractor_config(
146
+ pretrained_model_name_or_path: Union[str, os.PathLike],
147
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
148
+ force_download: bool = False,
149
+ resume_download: Optional[bool] = None,
150
+ proxies: Optional[Dict[str, str]] = None,
151
+ token: Optional[Union[bool, str]] = None,
152
+ revision: Optional[str] = None,
153
+ local_files_only: bool = False,
154
+ **kwargs,
155
+ ):
156
+ """
157
+ Loads the tokenizer configuration from a pretrained model tokenizer configuration.
158
+
159
+ Args:
160
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
161
+ This can be either:
162
+
163
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
164
+ huggingface.co.
165
+ - a path to a *directory* containing a configuration file saved using the
166
+ [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
167
+
168
+ cache_dir (`str` or `os.PathLike`, *optional*):
169
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
170
+ cache should not be used.
171
+ force_download (`bool`, *optional*, defaults to `False`):
172
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
173
+ exist.
174
+ resume_download:
175
+ Deprecated and ignored. All downloads are now resumed by default when possible.
176
+ Will be removed in v5 of Transformers.
177
+ proxies (`Dict[str, str]`, *optional*):
178
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
179
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
180
+ token (`str` or *bool*, *optional*):
181
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
182
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
183
+ revision (`str`, *optional*, defaults to `"main"`):
184
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
185
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
186
+ identifier allowed by git.
187
+ local_files_only (`bool`, *optional*, defaults to `False`):
188
+ If `True`, will only try to load the tokenizer configuration from local files.
189
+
190
+ <Tip>
191
+
192
+ Passing `token=True` is required when you want to use a private model.
193
+
194
+ </Tip>
195
+
196
+ Returns:
197
+ `Dict`: The configuration of the tokenizer.
198
+
199
+ Examples:
200
+
201
+ ```python
202
+ # Download configuration from huggingface.co and cache.
203
+ tokenizer_config = get_tokenizer_config("google-bert/bert-base-uncased")
204
+ # This model does not have a tokenizer config so the result will be an empty dict.
205
+ tokenizer_config = get_tokenizer_config("FacebookAI/xlm-roberta-base")
206
+
207
+ # Save a pretrained tokenizer locally and you can reload its config
208
+ from transformers import AutoTokenizer
209
+
210
+ tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
211
+ tokenizer.save_pretrained("tokenizer-test")
212
+ tokenizer_config = get_tokenizer_config("tokenizer-test")
213
+ ```"""
214
+ use_auth_token = kwargs.pop("use_auth_token", None)
215
+ if use_auth_token is not None:
216
+ warnings.warn(
217
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
218
+ FutureWarning,
219
+ )
220
+ if token is not None:
221
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
222
+ token = use_auth_token
223
+
224
+ resolved_config_file = cached_file(
225
+ pretrained_model_name_or_path,
226
+ FEATURE_EXTRACTOR_NAME,
227
+ cache_dir=cache_dir,
228
+ force_download=force_download,
229
+ resume_download=resume_download,
230
+ proxies=proxies,
231
+ token=token,
232
+ revision=revision,
233
+ local_files_only=local_files_only,
234
+ _raise_exceptions_for_gated_repo=False,
235
+ _raise_exceptions_for_missing_entries=False,
236
+ _raise_exceptions_for_connection_errors=False,
237
+ )
238
+ if resolved_config_file is None:
239
+ logger.info(
240
+ "Could not locate the feature extractor configuration file, will try to use the model config instead."
241
+ )
242
+ return {}
243
+
244
+ with open(resolved_config_file, encoding="utf-8") as reader:
245
+ return json.load(reader)
246
+
247
+
248
+ class AutoFeatureExtractor:
249
+ r"""
250
+ This is a generic feature extractor class that will be instantiated as one of the feature extractor classes of the
251
+ library when created with the [`AutoFeatureExtractor.from_pretrained`] class method.
252
+
253
+ This class cannot be instantiated directly using `__init__()` (throws an error).
254
+ """
255
+
256
+ def __init__(self):
257
+ raise EnvironmentError(
258
+ "AutoFeatureExtractor is designed to be instantiated "
259
+ "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method."
260
+ )
261
+
262
+ @classmethod
263
+ @replace_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
264
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
265
+ r"""
266
+ Instantiate one of the feature extractor classes of the library from a pretrained model vocabulary.
267
+
268
+ The feature extractor class to instantiate is selected based on the `model_type` property of the config object
269
+ (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
270
+ missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
271
+
272
+ List options
273
+
274
+ Params:
275
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
276
+ This can be either:
277
+
278
+ - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
279
+ huggingface.co.
280
+ - a path to a *directory* containing a feature extractor file saved using the
281
+ [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
282
+ `./my_model_directory/`.
283
+ - a path or url to a saved feature extractor JSON *file*, e.g.,
284
+ `./my_model_directory/preprocessor_config.json`.
285
+ cache_dir (`str` or `os.PathLike`, *optional*):
286
+ Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
287
+ standard cache should not be used.
288
+ force_download (`bool`, *optional*, defaults to `False`):
289
+ Whether or not to force to (re-)download the feature extractor files and override the cached versions
290
+ if they exist.
291
+ resume_download:
292
+ Deprecated and ignored. All downloads are now resumed by default when possible.
293
+ Will be removed in v5 of Transformers.
294
+ proxies (`Dict[str, str]`, *optional*):
295
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
296
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
297
+ token (`str` or *bool*, *optional*):
298
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
299
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
300
+ revision (`str`, *optional*, defaults to `"main"`):
301
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
302
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
303
+ identifier allowed by git.
304
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
305
+ If `False`, then this function returns just the final feature extractor object. If `True`, then this
306
+ functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
307
+ consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
308
+ `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
309
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
310
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
311
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
312
+ execute code present on the Hub on your local machine.
313
+ kwargs (`Dict[str, Any]`, *optional*):
314
+ The values in kwargs of any keys which are feature extractor attributes will be used to override the
315
+ loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
316
+ controlled by the `return_unused_kwargs` keyword parameter.
317
+
318
+ <Tip>
319
+
320
+ Passing `token=True` is required when you want to use a private model.
321
+
322
+ </Tip>
323
+
324
+ Examples:
325
+
326
+ ```python
327
+ >>> from transformers import AutoFeatureExtractor
328
+
329
+ >>> # Download feature extractor from huggingface.co and cache.
330
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
331
+
332
+ >>> # If feature extractor files are in a directory (e.g. feature extractor was saved using *save_pretrained('./test/saved_model/')*)
333
+ >>> # feature_extractor = AutoFeatureExtractor.from_pretrained("./test/saved_model/")
334
+ ```"""
335
+ use_auth_token = kwargs.pop("use_auth_token", None)
336
+ if use_auth_token is not None:
337
+ warnings.warn(
338
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
339
+ FutureWarning,
340
+ )
341
+ if kwargs.get("token", None) is not None:
342
+ raise ValueError(
343
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
344
+ )
345
+ kwargs["token"] = use_auth_token
346
+
347
+ config = kwargs.pop("config", None)
348
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
349
+ kwargs["_from_auto"] = True
350
+
351
+ config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
352
+ feature_extractor_class = config_dict.get("feature_extractor_type", None)
353
+ feature_extractor_auto_map = None
354
+ if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
355
+ feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
356
+
357
+ # If we don't find the feature extractor class in the feature extractor config, let's try the model config.
358
+ if feature_extractor_class is None and feature_extractor_auto_map is None:
359
+ if not isinstance(config, PretrainedConfig):
360
+ config = AutoConfig.from_pretrained(
361
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
362
+ )
363
+ # It could be in `config.feature_extractor_type``
364
+ feature_extractor_class = getattr(config, "feature_extractor_type", None)
365
+ if hasattr(config, "auto_map") and "AutoFeatureExtractor" in config.auto_map:
366
+ feature_extractor_auto_map = config.auto_map["AutoFeatureExtractor"]
367
+
368
+ if feature_extractor_class is not None:
369
+ feature_extractor_class = feature_extractor_class_from_name(feature_extractor_class)
370
+
371
+ has_remote_code = feature_extractor_auto_map is not None
372
+ has_local_code = feature_extractor_class is not None or type(config) in FEATURE_EXTRACTOR_MAPPING
373
+ trust_remote_code = resolve_trust_remote_code(
374
+ trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
375
+ )
376
+
377
+ if has_remote_code and trust_remote_code:
378
+ feature_extractor_class = get_class_from_dynamic_module(
379
+ feature_extractor_auto_map, pretrained_model_name_or_path, **kwargs
380
+ )
381
+ _ = kwargs.pop("code_revision", None)
382
+ if os.path.isdir(pretrained_model_name_or_path):
383
+ feature_extractor_class.register_for_auto_class()
384
+ return feature_extractor_class.from_dict(config_dict, **kwargs)
385
+ elif feature_extractor_class is not None:
386
+ return feature_extractor_class.from_dict(config_dict, **kwargs)
387
+ # Last try: we use the FEATURE_EXTRACTOR_MAPPING.
388
+ elif type(config) in FEATURE_EXTRACTOR_MAPPING:
389
+ feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[type(config)]
390
+ return feature_extractor_class.from_dict(config_dict, **kwargs)
391
+
392
+ raise ValueError(
393
+ f"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a "
394
+ f"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following "
395
+ f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys())}"
396
+ )
397
+
398
+ @staticmethod
399
+ def register(config_class, feature_extractor_class, exist_ok=False):
400
+ """
401
+ Register a new feature extractor for this class.
402
+
403
+ Args:
404
+ config_class ([`PretrainedConfig`]):
405
+ The configuration corresponding to the model to register.
406
+ feature_extractor_class ([`FeatureExtractorMixin`]): The feature extractor to register.
407
+ """
408
+ FEATURE_EXTRACTOR_MAPPING.register(config_class, feature_extractor_class, exist_ok=exist_ok)
lib/python3.12/site-packages/transformers/models/auto/image_processing_auto.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """AutoImageProcessor class."""
16
+
17
+ import importlib
18
+ import json
19
+ import os
20
+ import warnings
21
+ from collections import OrderedDict
22
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
23
+
24
+ # Build the list of all image processors
25
+ from ...configuration_utils import PretrainedConfig
26
+ from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
27
+ from ...image_processing_utils import ImageProcessingMixin
28
+ from ...image_processing_utils_fast import BaseImageProcessorFast
29
+ from ...utils import (
30
+ CONFIG_NAME,
31
+ IMAGE_PROCESSOR_NAME,
32
+ cached_file,
33
+ is_timm_config_dict,
34
+ is_timm_local_checkpoint,
35
+ is_torchvision_available,
36
+ is_vision_available,
37
+ logging,
38
+ )
39
+ from .auto_factory import _LazyAutoMapping
40
+ from .configuration_auto import (
41
+ CONFIG_MAPPING_NAMES,
42
+ AutoConfig,
43
+ model_type_to_module_name,
44
+ replace_list_option_in_docstrings,
45
+ )
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ if TYPE_CHECKING:
52
+ # This significantly improves completion suggestion performance when
53
+ # the transformers package is used with Microsoft's Pylance language server.
54
+ IMAGE_PROCESSOR_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict()
55
+ else:
56
+ IMAGE_PROCESSOR_MAPPING_NAMES = OrderedDict(
57
+ [
58
+ ("align", ("EfficientNetImageProcessor",)),
59
+ ("aria", ("AriaImageProcessor",)),
60
+ ("beit", ("BeitImageProcessor",)),
61
+ ("bit", ("BitImageProcessor",)),
62
+ ("blip", ("BlipImageProcessor", "BlipImageProcessorFast")),
63
+ ("blip-2", ("BlipImageProcessor", "BlipImageProcessorFast")),
64
+ ("bridgetower", ("BridgeTowerImageProcessor",)),
65
+ ("chameleon", ("ChameleonImageProcessor",)),
66
+ ("chinese_clip", ("ChineseCLIPImageProcessor",)),
67
+ ("clip", ("CLIPImageProcessor", "CLIPImageProcessorFast")),
68
+ ("clipseg", ("ViTImageProcessor", "ViTImageProcessorFast")),
69
+ ("conditional_detr", ("ConditionalDetrImageProcessor",)),
70
+ ("convnext", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")),
71
+ ("convnextv2", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")),
72
+ ("cvt", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")),
73
+ ("data2vec-vision", ("BeitImageProcessor",)),
74
+ ("deformable_detr", ("DeformableDetrImageProcessor", "DeformableDetrImageProcessorFast")),
75
+ ("deit", ("DeiTImageProcessor", "DeiTImageProcessorFast")),
76
+ ("depth_anything", ("DPTImageProcessor",)),
77
+ ("depth_pro", ("DepthProImageProcessor", "DepthProImageProcessorFast")),
78
+ ("deta", ("DetaImageProcessor",)),
79
+ ("detr", ("DetrImageProcessor", "DetrImageProcessorFast")),
80
+ ("dinat", ("ViTImageProcessor", "ViTImageProcessorFast")),
81
+ ("dinov2", ("BitImageProcessor",)),
82
+ ("donut-swin", ("DonutImageProcessor",)),
83
+ ("dpt", ("DPTImageProcessor",)),
84
+ ("efficientformer", ("EfficientFormerImageProcessor",)),
85
+ ("efficientnet", ("EfficientNetImageProcessor",)),
86
+ ("flava", ("FlavaImageProcessor",)),
87
+ ("focalnet", ("BitImageProcessor",)),
88
+ ("fuyu", ("FuyuImageProcessor",)),
89
+ ("gemma3", ("Gemma3ImageProcessor", "Gemma3ImageProcessorFast")),
90
+ ("git", ("CLIPImageProcessor", "CLIPImageProcessorFast")),
91
+ ("glpn", ("GLPNImageProcessor",)),
92
+ ("got_ocr2", ("GotOcr2ImageProcessor", "GotOcr2ImageProcessorFast")),
93
+ ("grounding-dino", ("GroundingDinoImageProcessor",)),
94
+ ("groupvit", ("CLIPImageProcessor", "CLIPImageProcessorFast")),
95
+ ("hiera", ("BitImageProcessor",)),
96
+ ("idefics", ("IdeficsImageProcessor",)),
97
+ ("idefics2", ("Idefics2ImageProcessor",)),
98
+ ("idefics3", ("Idefics3ImageProcessor",)),
99
+ ("ijepa", ("ViTImageProcessor", "ViTImageProcessorFast")),
100
+ ("imagegpt", ("ImageGPTImageProcessor",)),
101
+ ("instructblip", ("BlipImageProcessor", "BlipImageProcessorFast")),
102
+ ("instructblipvideo", ("InstructBlipVideoImageProcessor",)),
103
+ ("kosmos-2", ("CLIPImageProcessor", "CLIPImageProcessorFast")),
104
+ ("layoutlmv2", ("LayoutLMv2ImageProcessor",)),
105
+ ("layoutlmv3", ("LayoutLMv3ImageProcessor",)),
106
+ ("levit", ("LevitImageProcessor",)),
107
+ ("llama4", ("Llama4ImageProcessor", "Llama4ImageProcessorFast")),
108
+ ("llava", ("LlavaImageProcessor", "LlavaImageProcessorFast")),
109
+ ("llava_next", ("LlavaNextImageProcessor", "LlavaNextImageProcessorFast")),
110
+ ("llava_next_video", ("LlavaNextVideoImageProcessor",)),
111
+ ("llava_onevision", ("LlavaOnevisionImageProcessor", "LlavaOnevisionImageProcessorFast")),
112
+ ("mask2former", ("Mask2FormerImageProcessor",)),
113
+ ("maskformer", ("MaskFormerImageProcessor",)),
114
+ ("mgp-str", ("ViTImageProcessor", "ViTImageProcessorFast")),
115
+ ("mistral3", ("PixtralImageProcessor", "PixtralImageProcessorFast")),
116
+ ("mllama", ("MllamaImageProcessor",)),
117
+ ("mobilenet_v1", ("MobileNetV1ImageProcessor",)),
118
+ ("mobilenet_v2", ("MobileNetV2ImageProcessor",)),
119
+ ("mobilevit", ("MobileViTImageProcessor",)),
120
+ ("mobilevitv2", ("MobileViTImageProcessor",)),
121
+ ("nat", ("ViTImageProcessor", "ViTImageProcessorFast")),
122
+ ("nougat", ("NougatImageProcessor",)),
123
+ ("oneformer", ("OneFormerImageProcessor",)),
124
+ ("owlv2", ("Owlv2ImageProcessor",)),
125
+ ("owlvit", ("OwlViTImageProcessor",)),
126
+ ("paligemma", ("SiglipImageProcessor", "SiglipImageProcessorFast")),
127
+ ("perceiver", ("PerceiverImageProcessor",)),
128
+ ("phi4_multimodal", "Phi4MultimodalImageProcessorFast"),
129
+ ("pix2struct", ("Pix2StructImageProcessor",)),
130
+ ("pixtral", ("PixtralImageProcessor", "PixtralImageProcessorFast")),
131
+ ("poolformer", ("PoolFormerImageProcessor",)),
132
+ ("prompt_depth_anything", ("PromptDepthAnythingImageProcessor",)),
133
+ ("pvt", ("PvtImageProcessor",)),
134
+ ("pvt_v2", ("PvtImageProcessor",)),
135
+ ("qwen2_5_vl", ("Qwen2VLImageProcessor", "Qwen2VLImageProcessorFast")),
136
+ ("qwen2_vl", ("Qwen2VLImageProcessor", "Qwen2VLImageProcessorFast")),
137
+ ("regnet", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")),
138
+ ("resnet", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")),
139
+ ("rt_detr", ("RTDetrImageProcessor", "RTDetrImageProcessorFast")),
140
+ ("sam", ("SamImageProcessor",)),
141
+ ("segformer", ("SegformerImageProcessor",)),
142
+ ("seggpt", ("SegGptImageProcessor",)),
143
+ ("shieldgemma2", ("Gemma3ImageProcessor", "Gemma3ImageProcessorFast")),
144
+ ("siglip", ("SiglipImageProcessor", "SiglipImageProcessorFast")),
145
+ ("siglip2", ("Siglip2ImageProcessor", "Siglip2ImageProcessorFast")),
146
+ ("superglue", ("SuperGlueImageProcessor",)),
147
+ ("swiftformer", ("ViTImageProcessor", "ViTImageProcessorFast")),
148
+ ("swin", ("ViTImageProcessor", "ViTImageProcessorFast")),
149
+ ("swin2sr", ("Swin2SRImageProcessor",)),
150
+ ("swinv2", ("ViTImageProcessor", "ViTImageProcessorFast")),
151
+ ("table-transformer", ("DetrImageProcessor",)),
152
+ ("timesformer", ("VideoMAEImageProcessor",)),
153
+ ("timm_wrapper", ("TimmWrapperImageProcessor",)),
154
+ ("tvlt", ("TvltImageProcessor",)),
155
+ ("tvp", ("TvpImageProcessor",)),
156
+ ("udop", ("LayoutLMv3ImageProcessor",)),
157
+ ("upernet", ("SegformerImageProcessor",)),
158
+ ("van", ("ConvNextImageProcessor", "ConvNextImageProcessorFast")),
159
+ ("videomae", ("VideoMAEImageProcessor",)),
160
+ ("vilt", ("ViltImageProcessor",)),
161
+ ("vipllava", ("CLIPImageProcessor", "CLIPImageProcessorFast")),
162
+ ("vit", ("ViTImageProcessor", "ViTImageProcessorFast")),
163
+ ("vit_hybrid", ("ViTHybridImageProcessor",)),
164
+ ("vit_mae", ("ViTImageProcessor", "ViTImageProcessorFast")),
165
+ ("vit_msn", ("ViTImageProcessor", "ViTImageProcessorFast")),
166
+ ("vitmatte", ("VitMatteImageProcessor",)),
167
+ ("xclip", ("CLIPImageProcessor", "CLIPImageProcessorFast")),
168
+ ("yolos", ("YolosImageProcessor",)),
169
+ ("zoedepth", ("ZoeDepthImageProcessor",)),
170
+ ]
171
+ )
172
+
173
+ for model_type, image_processors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
174
+ slow_image_processor_class, *fast_image_processor_class = image_processors
175
+ if not is_vision_available():
176
+ slow_image_processor_class = None
177
+
178
+ # If the fast image processor is not defined, or torchvision is not available, we set it to None
179
+ if not fast_image_processor_class or fast_image_processor_class[0] is None or not is_torchvision_available():
180
+ fast_image_processor_class = None
181
+ else:
182
+ fast_image_processor_class = fast_image_processor_class[0]
183
+
184
+ IMAGE_PROCESSOR_MAPPING_NAMES[model_type] = (slow_image_processor_class, fast_image_processor_class)
185
+
186
+ IMAGE_PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)
187
+
188
+
189
+ def get_image_processor_class_from_name(class_name: str):
190
+ if class_name == "BaseImageProcessorFast":
191
+ return BaseImageProcessorFast
192
+
193
+ for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
194
+ if class_name in extractors:
195
+ module_name = model_type_to_module_name(module_name)
196
+
197
+ module = importlib.import_module(f".{module_name}", "transformers.models")
198
+ try:
199
+ return getattr(module, class_name)
200
+ except AttributeError:
201
+ continue
202
+
203
+ for _, extractors in IMAGE_PROCESSOR_MAPPING._extra_content.items():
204
+ for extractor in extractors:
205
+ if getattr(extractor, "__name__", None) == class_name:
206
+ return extractor
207
+
208
+ # We did not find the class, but maybe it's because a dep is missing. In that case, the class will be in the main
209
+ # init and we return the proper dummy to get an appropriate error message.
210
+ main_module = importlib.import_module("transformers")
211
+ if hasattr(main_module, class_name):
212
+ return getattr(main_module, class_name)
213
+
214
+ return None
215
+
216
+
217
+ def get_image_processor_config(
218
+ pretrained_model_name_or_path: Union[str, os.PathLike],
219
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
220
+ force_download: bool = False,
221
+ resume_download: Optional[bool] = None,
222
+ proxies: Optional[Dict[str, str]] = None,
223
+ token: Optional[Union[bool, str]] = None,
224
+ revision: Optional[str] = None,
225
+ local_files_only: bool = False,
226
+ **kwargs,
227
+ ):
228
+ """
229
+ Loads the image processor configuration from a pretrained model image processor configuration.
230
+
231
+ Args:
232
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
233
+ This can be either:
234
+
235
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
236
+ huggingface.co.
237
+ - a path to a *directory* containing a configuration file saved using the
238
+ [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
239
+
240
+ cache_dir (`str` or `os.PathLike`, *optional*):
241
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
242
+ cache should not be used.
243
+ force_download (`bool`, *optional*, defaults to `False`):
244
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
245
+ exist.
246
+ resume_download:
247
+ Deprecated and ignored. All downloads are now resumed by default when possible.
248
+ Will be removed in v5 of Transformers.
249
+ proxies (`Dict[str, str]`, *optional*):
250
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
251
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
252
+ token (`str` or *bool*, *optional*):
253
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
254
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
255
+ revision (`str`, *optional*, defaults to `"main"`):
256
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
257
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
258
+ identifier allowed by git.
259
+ local_files_only (`bool`, *optional*, defaults to `False`):
260
+ If `True`, will only try to load the image processor configuration from local files.
261
+
262
+ <Tip>
263
+
264
+ Passing `token=True` is required when you want to use a private model.
265
+
266
+ </Tip>
267
+
268
+ Returns:
269
+ `Dict`: The configuration of the image processor.
270
+
271
+ Examples:
272
+
273
+ ```python
274
+ # Download configuration from huggingface.co and cache.
275
+ image_processor_config = get_image_processor_config("google-bert/bert-base-uncased")
276
+ # This model does not have a image processor config so the result will be an empty dict.
277
+ image_processor_config = get_image_processor_config("FacebookAI/xlm-roberta-base")
278
+
279
+ # Save a pretrained image processor locally and you can reload its config
280
+ from transformers import AutoTokenizer
281
+
282
+ image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
283
+ image_processor.save_pretrained("image-processor-test")
284
+ image_processor_config = get_image_processor_config("image-processor-test")
285
+ ```"""
286
+ use_auth_token = kwargs.pop("use_auth_token", None)
287
+ if use_auth_token is not None:
288
+ warnings.warn(
289
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
290
+ FutureWarning,
291
+ )
292
+ if token is not None:
293
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
294
+ token = use_auth_token
295
+
296
+ resolved_config_file = cached_file(
297
+ pretrained_model_name_or_path,
298
+ IMAGE_PROCESSOR_NAME,
299
+ cache_dir=cache_dir,
300
+ force_download=force_download,
301
+ resume_download=resume_download,
302
+ proxies=proxies,
303
+ token=token,
304
+ revision=revision,
305
+ local_files_only=local_files_only,
306
+ _raise_exceptions_for_gated_repo=False,
307
+ _raise_exceptions_for_missing_entries=False,
308
+ _raise_exceptions_for_connection_errors=False,
309
+ )
310
+ if resolved_config_file is None:
311
+ logger.info(
312
+ "Could not locate the image processor configuration file, will try to use the model config instead."
313
+ )
314
+ return {}
315
+
316
+ with open(resolved_config_file, encoding="utf-8") as reader:
317
+ return json.load(reader)
318
+
319
+
320
+ def _warning_fast_image_processor_available(fast_class):
321
+ logger.warning(
322
+ f"Fast image processor class {fast_class} is available for this model. "
323
+ "Using slow image processor class. To use the fast image processor class set `use_fast=True`."
324
+ )
325
+
326
+
327
+ class AutoImageProcessor:
328
+ r"""
329
+ This is a generic image processor class that will be instantiated as one of the image processor classes of the
330
+ library when created with the [`AutoImageProcessor.from_pretrained`] class method.
331
+
332
+ This class cannot be instantiated directly using `__init__()` (throws an error).
333
+ """
334
+
335
+ def __init__(self):
336
+ raise EnvironmentError(
337
+ "AutoImageProcessor is designed to be instantiated "
338
+ "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method."
339
+ )
340
+
341
+ @classmethod
342
+ @replace_list_option_in_docstrings(IMAGE_PROCESSOR_MAPPING_NAMES)
343
+ def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
344
+ r"""
345
+ Instantiate one of the image processor classes of the library from a pretrained model vocabulary.
346
+
347
+ The image processor class to instantiate is selected based on the `model_type` property of the config object
348
+ (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
349
+ missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
350
+
351
+ List options
352
+
353
+ Params:
354
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
355
+ This can be either:
356
+
357
+ - a string, the *model id* of a pretrained image_processor hosted inside a model repo on
358
+ huggingface.co.
359
+ - a path to a *directory* containing a image processor file saved using the
360
+ [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
361
+ `./my_model_directory/`.
362
+ - a path or url to a saved image processor JSON *file*, e.g.,
363
+ `./my_model_directory/preprocessor_config.json`.
364
+ cache_dir (`str` or `os.PathLike`, *optional*):
365
+ Path to a directory in which a downloaded pretrained model image processor should be cached if the
366
+ standard cache should not be used.
367
+ force_download (`bool`, *optional*, defaults to `False`):
368
+ Whether or not to force to (re-)download the image processor files and override the cached versions if
369
+ they exist.
370
+ resume_download:
371
+ Deprecated and ignored. All downloads are now resumed by default when possible.
372
+ Will be removed in v5 of Transformers.
373
+ proxies (`Dict[str, str]`, *optional*):
374
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
375
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
376
+ token (`str` or *bool*, *optional*):
377
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
378
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
379
+ revision (`str`, *optional*, defaults to `"main"`):
380
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
381
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
382
+ identifier allowed by git.
383
+ use_fast (`bool`, *optional*, defaults to `False`):
384
+ Use a fast torchvision-base image processor if it is supported for a given model.
385
+ If a fast image processor is not available for a given model, a normal numpy-based image processor
386
+ is returned instead.
387
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
388
+ If `False`, then this function returns just the final image processor object. If `True`, then this
389
+ functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
390
+ consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
391
+ `kwargs` which has not been used to update `image_processor` and is otherwise ignored.
392
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
393
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
394
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
395
+ execute code present on the Hub on your local machine.
396
+ image_processor_filename (`str`, *optional*, defaults to `"config.json"`):
397
+ The name of the file in the model directory to use for the image processor config.
398
+ kwargs (`Dict[str, Any]`, *optional*):
399
+ The values in kwargs of any keys which are image processor attributes will be used to override the
400
+ loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
401
+ controlled by the `return_unused_kwargs` keyword parameter.
402
+
403
+ <Tip>
404
+
405
+ Passing `token=True` is required when you want to use a private model.
406
+
407
+ </Tip>
408
+
409
+ Examples:
410
+
411
+ ```python
412
+ >>> from transformers import AutoImageProcessor
413
+
414
+ >>> # Download image processor from huggingface.co and cache.
415
+ >>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
416
+
417
+ >>> # If image processor files are in a directory (e.g. image processor was saved using *save_pretrained('./test/saved_model/')*)
418
+ >>> # image_processor = AutoImageProcessor.from_pretrained("./test/saved_model/")
419
+ ```"""
420
+ use_auth_token = kwargs.pop("use_auth_token", None)
421
+ if use_auth_token is not None:
422
+ warnings.warn(
423
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
424
+ FutureWarning,
425
+ )
426
+ if kwargs.get("token", None) is not None:
427
+ raise ValueError(
428
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
429
+ )
430
+ kwargs["token"] = use_auth_token
431
+
432
+ config = kwargs.pop("config", None)
433
+ # TODO: @yoni, change in v4.48 (use_fast set to True by default)
434
+ use_fast = kwargs.pop("use_fast", None)
435
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
436
+ kwargs["_from_auto"] = True
437
+
438
+ # Resolve the image processor config filename
439
+ if "image_processor_filename" in kwargs:
440
+ image_processor_filename = kwargs.pop("image_processor_filename")
441
+ elif is_timm_local_checkpoint(pretrained_model_name_or_path):
442
+ image_processor_filename = CONFIG_NAME
443
+ else:
444
+ image_processor_filename = IMAGE_PROCESSOR_NAME
445
+
446
+ # Load the image processor config
447
+ try:
448
+ # Main path for all transformers models and local TimmWrapper checkpoints
449
+ config_dict, _ = ImageProcessingMixin.get_image_processor_dict(
450
+ pretrained_model_name_or_path, image_processor_filename=image_processor_filename, **kwargs
451
+ )
452
+ except Exception as initial_exception:
453
+ # Fallback path for Hub TimmWrapper checkpoints. Timm models' image processing is saved in `config.json`
454
+ # instead of `preprocessor_config.json`. Because this is an Auto class and we don't have any information
455
+ # except the model name, the only way to check if a remote checkpoint is a timm model is to try to
456
+ # load `config.json` and if it fails with some error, we raise the initial exception.
457
+ try:
458
+ config_dict, _ = ImageProcessingMixin.get_image_processor_dict(
459
+ pretrained_model_name_or_path, image_processor_filename=CONFIG_NAME, **kwargs
460
+ )
461
+ except Exception:
462
+ raise initial_exception
463
+
464
+ # In case we have a config_dict, but it's not a timm config dict, we raise the initial exception,
465
+ # because only timm models have image processing in `config.json`.
466
+ if not is_timm_config_dict(config_dict):
467
+ raise initial_exception
468
+
469
+ image_processor_type = config_dict.get("image_processor_type", None)
470
+ image_processor_auto_map = None
471
+ if "AutoImageProcessor" in config_dict.get("auto_map", {}):
472
+ image_processor_auto_map = config_dict["auto_map"]["AutoImageProcessor"]
473
+
474
+ # If we still don't have the image processor class, check if we're loading from a previous feature extractor config
475
+ # and if so, infer the image processor class from there.
476
+ if image_processor_type is None and image_processor_auto_map is None:
477
+ feature_extractor_class = config_dict.pop("feature_extractor_type", None)
478
+ if feature_extractor_class is not None:
479
+ image_processor_type = feature_extractor_class.replace("FeatureExtractor", "ImageProcessor")
480
+ if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
481
+ feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
482
+ image_processor_auto_map = feature_extractor_auto_map.replace("FeatureExtractor", "ImageProcessor")
483
+
484
+ # If we don't find the image processor class in the image processor config, let's try the model config.
485
+ if image_processor_type is None and image_processor_auto_map is None:
486
+ if not isinstance(config, PretrainedConfig):
487
+ config = AutoConfig.from_pretrained(
488
+ pretrained_model_name_or_path,
489
+ trust_remote_code=trust_remote_code,
490
+ **kwargs,
491
+ )
492
+ # It could be in `config.image_processor_type``
493
+ image_processor_type = getattr(config, "image_processor_type", None)
494
+ if hasattr(config, "auto_map") and "AutoImageProcessor" in config.auto_map:
495
+ image_processor_auto_map = config.auto_map["AutoImageProcessor"]
496
+
497
+ image_processor_class = None
498
+ # TODO: @yoni, change logic in v4.52 (when use_fast set to True by default)
499
+ if image_processor_type is not None:
500
+ # if use_fast is not set and the processor was saved with a fast processor, we use it, otherwise we use the slow processor.
501
+ if use_fast is None:
502
+ use_fast = image_processor_type.endswith("Fast")
503
+ if not use_fast:
504
+ logger.warning_once(
505
+ "Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. "
506
+ "`use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. "
507
+ "This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`."
508
+ )
509
+ # Update class name to reflect the use_fast option. If class is not found, we fall back to the slow version.
510
+ if use_fast and not is_torchvision_available():
511
+ logger.warning_once(
512
+ "Using `use_fast=True` but `torchvision` is not available. Falling back to the slow image processor."
513
+ )
514
+ use_fast = False
515
+ if use_fast:
516
+ if not image_processor_type.endswith("Fast"):
517
+ image_processor_type += "Fast"
518
+ for _, image_processors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
519
+ if image_processor_type in image_processors:
520
+ break
521
+ else:
522
+ image_processor_type = image_processor_type[:-4]
523
+ use_fast = False
524
+ logger.warning_once(
525
+ "`use_fast` is set to `True` but the image processor class does not have a fast version. "
526
+ " Falling back to the slow version."
527
+ )
528
+ image_processor_class = get_image_processor_class_from_name(image_processor_type)
529
+ else:
530
+ image_processor_type = (
531
+ image_processor_type[:-4] if image_processor_type.endswith("Fast") else image_processor_type
532
+ )
533
+ image_processor_class = get_image_processor_class_from_name(image_processor_type)
534
+
535
+ has_remote_code = image_processor_auto_map is not None
536
+ has_local_code = image_processor_class is not None or type(config) in IMAGE_PROCESSOR_MAPPING
537
+ trust_remote_code = resolve_trust_remote_code(
538
+ trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
539
+ )
540
+
541
+ if image_processor_auto_map is not None and not isinstance(image_processor_auto_map, tuple):
542
+ # In some configs, only the slow image processor class is stored
543
+ image_processor_auto_map = (image_processor_auto_map, None)
544
+
545
+ if has_remote_code and trust_remote_code:
546
+ if not use_fast and image_processor_auto_map[1] is not None:
547
+ _warning_fast_image_processor_available(image_processor_auto_map[1])
548
+
549
+ if use_fast and image_processor_auto_map[1] is not None:
550
+ class_ref = image_processor_auto_map[1]
551
+ else:
552
+ class_ref = image_processor_auto_map[0]
553
+ image_processor_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
554
+ _ = kwargs.pop("code_revision", None)
555
+ if os.path.isdir(pretrained_model_name_or_path):
556
+ image_processor_class.register_for_auto_class()
557
+ return image_processor_class.from_dict(config_dict, **kwargs)
558
+ elif image_processor_class is not None:
559
+ return image_processor_class.from_dict(config_dict, **kwargs)
560
+ # Last try: we use the IMAGE_PROCESSOR_MAPPING.
561
+ elif type(config) in IMAGE_PROCESSOR_MAPPING:
562
+ image_processor_tuple = IMAGE_PROCESSOR_MAPPING[type(config)]
563
+
564
+ image_processor_class_py, image_processor_class_fast = image_processor_tuple
565
+
566
+ if not use_fast and image_processor_class_fast is not None:
567
+ _warning_fast_image_processor_available(image_processor_class_fast)
568
+
569
+ if image_processor_class_fast and (use_fast or image_processor_class_py is None):
570
+ return image_processor_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
571
+ else:
572
+ if image_processor_class_py is not None:
573
+ return image_processor_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
574
+ else:
575
+ raise ValueError(
576
+ "This image processor cannot be instantiated. Please make sure you have `Pillow` installed."
577
+ )
578
+
579
+ raise ValueError(
580
+ f"Unrecognized image processor in {pretrained_model_name_or_path}. Should have a "
581
+ f"`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following "
582
+ f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}"
583
+ )
584
+
585
+ @staticmethod
586
+ def register(
587
+ config_class,
588
+ image_processor_class=None,
589
+ slow_image_processor_class=None,
590
+ fast_image_processor_class=None,
591
+ exist_ok=False,
592
+ ):
593
+ """
594
+ Register a new image processor for this class.
595
+
596
+ Args:
597
+ config_class ([`PretrainedConfig`]):
598
+ The configuration corresponding to the model to register.
599
+ image_processor_class ([`ImageProcessingMixin`]): The image processor to register.
600
+ """
601
+ if image_processor_class is not None:
602
+ if slow_image_processor_class is not None:
603
+ raise ValueError("Cannot specify both image_processor_class and slow_image_processor_class")
604
+ warnings.warn(
605
+ "The image_processor_class argument is deprecated and will be removed in v4.42. Please use `slow_image_processor_class`, or `fast_image_processor_class` instead",
606
+ FutureWarning,
607
+ )
608
+ slow_image_processor_class = image_processor_class
609
+
610
+ if slow_image_processor_class is None and fast_image_processor_class is None:
611
+ raise ValueError("You need to specify either slow_image_processor_class or fast_image_processor_class")
612
+ if slow_image_processor_class is not None and issubclass(slow_image_processor_class, BaseImageProcessorFast):
613
+ raise ValueError("You passed a fast image processor in as the `slow_image_processor_class`.")
614
+ if fast_image_processor_class is not None and not issubclass(
615
+ fast_image_processor_class, BaseImageProcessorFast
616
+ ):
617
+ raise ValueError("The `fast_image_processor_class` should inherit from `BaseImageProcessorFast`.")
618
+
619
+ if (
620
+ slow_image_processor_class is not None
621
+ and fast_image_processor_class is not None
622
+ and issubclass(fast_image_processor_class, BaseImageProcessorFast)
623
+ and fast_image_processor_class.slow_image_processor_class != slow_image_processor_class
624
+ ):
625
+ raise ValueError(
626
+ "The fast processor class you are passing has a `slow_image_processor_class` attribute that is not "
627
+ "consistent with the slow processor class you passed (fast tokenizer has "
628
+ f"{fast_image_processor_class.slow_image_processor_class} and you passed {slow_image_processor_class}. Fix one of those "
629
+ "so they match!"
630
+ )
631
+
632
+ # Avoid resetting a set slow/fast image processor if we are passing just the other ones.
633
+ if config_class in IMAGE_PROCESSOR_MAPPING._extra_content:
634
+ existing_slow, existing_fast = IMAGE_PROCESSOR_MAPPING[config_class]
635
+ if slow_image_processor_class is None:
636
+ slow_image_processor_class = existing_slow
637
+ if fast_image_processor_class is None:
638
+ fast_image_processor_class = existing_fast
639
+
640
+ IMAGE_PROCESSOR_MAPPING.register(
641
+ config_class, (slow_image_processor_class, fast_image_processor_class), exist_ok=exist_ok
642
+ )
lib/python3.12/site-packages/transformers/models/auto/modeling_auto.py ADDED
@@ -0,0 +1,1951 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Auto Model class."""
16
+
17
+ import warnings
18
+ from collections import OrderedDict
19
+
20
+ from ...utils import logging
21
+ from .auto_factory import (
22
+ _BaseAutoBackboneClass,
23
+ _BaseAutoModelClass,
24
+ _LazyAutoMapping,
25
+ auto_class_update,
26
+ )
27
+ from .configuration_auto import CONFIG_MAPPING_NAMES
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ MODEL_MAPPING_NAMES = OrderedDict(
33
+ [
34
+ # Base model mapping
35
+ ("albert", "AlbertModel"),
36
+ ("align", "AlignModel"),
37
+ ("altclip", "AltCLIPModel"),
38
+ ("aria", "AriaForConditionalGeneration"),
39
+ ("aria_text", "AriaTextModel"),
40
+ ("audio-spectrogram-transformer", "ASTModel"),
41
+ ("autoformer", "AutoformerModel"),
42
+ ("bamba", "BambaModel"),
43
+ ("bark", "BarkModel"),
44
+ ("bart", "BartModel"),
45
+ ("beit", "BeitModel"),
46
+ ("bert", "BertModel"),
47
+ ("bert-generation", "BertGenerationEncoder"),
48
+ ("big_bird", "BigBirdModel"),
49
+ ("bigbird_pegasus", "BigBirdPegasusModel"),
50
+ ("biogpt", "BioGptModel"),
51
+ ("bit", "BitModel"),
52
+ ("blenderbot", "BlenderbotModel"),
53
+ ("blenderbot-small", "BlenderbotSmallModel"),
54
+ ("blip", "BlipModel"),
55
+ ("blip-2", "Blip2Model"),
56
+ ("bloom", "BloomModel"),
57
+ ("bridgetower", "BridgeTowerModel"),
58
+ ("bros", "BrosModel"),
59
+ ("camembert", "CamembertModel"),
60
+ ("canine", "CanineModel"),
61
+ ("chameleon", "ChameleonModel"),
62
+ ("chinese_clip", "ChineseCLIPModel"),
63
+ ("chinese_clip_vision_model", "ChineseCLIPVisionModel"),
64
+ ("clap", "ClapModel"),
65
+ ("clip", "CLIPModel"),
66
+ ("clip_text_model", "CLIPTextModel"),
67
+ ("clip_vision_model", "CLIPVisionModel"),
68
+ ("clipseg", "CLIPSegModel"),
69
+ ("clvp", "ClvpModelForConditionalGeneration"),
70
+ ("code_llama", "LlamaModel"),
71
+ ("codegen", "CodeGenModel"),
72
+ ("cohere", "CohereModel"),
73
+ ("cohere2", "Cohere2Model"),
74
+ ("conditional_detr", "ConditionalDetrModel"),
75
+ ("convbert", "ConvBertModel"),
76
+ ("convnext", "ConvNextModel"),
77
+ ("convnextv2", "ConvNextV2Model"),
78
+ ("cpmant", "CpmAntModel"),
79
+ ("ctrl", "CTRLModel"),
80
+ ("cvt", "CvtModel"),
81
+ ("dab-detr", "DabDetrModel"),
82
+ ("dac", "DacModel"),
83
+ ("data2vec-audio", "Data2VecAudioModel"),
84
+ ("data2vec-text", "Data2VecTextModel"),
85
+ ("data2vec-vision", "Data2VecVisionModel"),
86
+ ("dbrx", "DbrxModel"),
87
+ ("deberta", "DebertaModel"),
88
+ ("deberta-v2", "DebertaV2Model"),
89
+ ("decision_transformer", "DecisionTransformerModel"),
90
+ ("deepseek_v3", "DeepseekV3Model"),
91
+ ("deformable_detr", "DeformableDetrModel"),
92
+ ("deit", "DeiTModel"),
93
+ ("depth_pro", "DepthProModel"),
94
+ ("deta", "DetaModel"),
95
+ ("detr", "DetrModel"),
96
+ ("diffllama", "DiffLlamaModel"),
97
+ ("dinat", "DinatModel"),
98
+ ("dinov2", "Dinov2Model"),
99
+ ("dinov2_with_registers", "Dinov2WithRegistersModel"),
100
+ ("distilbert", "DistilBertModel"),
101
+ ("donut-swin", "DonutSwinModel"),
102
+ ("dpr", "DPRQuestionEncoder"),
103
+ ("dpt", "DPTModel"),
104
+ ("efficientformer", "EfficientFormerModel"),
105
+ ("efficientnet", "EfficientNetModel"),
106
+ ("electra", "ElectraModel"),
107
+ ("encodec", "EncodecModel"),
108
+ ("ernie", "ErnieModel"),
109
+ ("ernie_m", "ErnieMModel"),
110
+ ("esm", "EsmModel"),
111
+ ("falcon", "FalconModel"),
112
+ ("falcon_mamba", "FalconMambaModel"),
113
+ ("fastspeech2_conformer", "FastSpeech2ConformerModel"),
114
+ ("flaubert", "FlaubertModel"),
115
+ ("flava", "FlavaModel"),
116
+ ("fnet", "FNetModel"),
117
+ ("focalnet", "FocalNetModel"),
118
+ ("fsmt", "FSMTModel"),
119
+ ("funnel", ("FunnelModel", "FunnelBaseModel")),
120
+ ("gemma", "GemmaModel"),
121
+ ("gemma2", "Gemma2Model"),
122
+ ("gemma3_text", "Gemma3TextModel"),
123
+ ("git", "GitModel"),
124
+ ("glm", "GlmModel"),
125
+ ("glpn", "GLPNModel"),
126
+ ("got_ocr2", "GotOcr2ForConditionalGeneration"),
127
+ ("gpt-sw3", "GPT2Model"),
128
+ ("gpt2", "GPT2Model"),
129
+ ("gpt_bigcode", "GPTBigCodeModel"),
130
+ ("gpt_neo", "GPTNeoModel"),
131
+ ("gpt_neox", "GPTNeoXModel"),
132
+ ("gpt_neox_japanese", "GPTNeoXJapaneseModel"),
133
+ ("gptj", "GPTJModel"),
134
+ ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
135
+ ("granite", "GraniteModel"),
136
+ ("granitemoe", "GraniteMoeModel"),
137
+ ("granitemoeshared", "GraniteMoeSharedModel"),
138
+ ("graphormer", "GraphormerModel"),
139
+ ("grounding-dino", "GroundingDinoModel"),
140
+ ("groupvit", "GroupViTModel"),
141
+ ("helium", "HeliumModel"),
142
+ ("hiera", "HieraModel"),
143
+ ("hubert", "HubertModel"),
144
+ ("ibert", "IBertModel"),
145
+ ("idefics", "IdeficsModel"),
146
+ ("idefics2", "Idefics2Model"),
147
+ ("idefics3", "Idefics3Model"),
148
+ ("idefics3_vision", "Idefics3VisionTransformer"),
149
+ ("ijepa", "IJepaModel"),
150
+ ("imagegpt", "ImageGPTModel"),
151
+ ("informer", "InformerModel"),
152
+ ("jamba", "JambaModel"),
153
+ ("jetmoe", "JetMoeModel"),
154
+ ("jukebox", "JukeboxModel"),
155
+ ("kosmos-2", "Kosmos2Model"),
156
+ ("layoutlm", "LayoutLMModel"),
157
+ ("layoutlmv2", "LayoutLMv2Model"),
158
+ ("layoutlmv3", "LayoutLMv3Model"),
159
+ ("led", "LEDModel"),
160
+ ("levit", "LevitModel"),
161
+ ("lilt", "LiltModel"),
162
+ ("llama", "LlamaModel"),
163
+ ("llama4", "Llama4ForConditionalGeneration"),
164
+ ("longformer", "LongformerModel"),
165
+ ("longt5", "LongT5Model"),
166
+ ("luke", "LukeModel"),
167
+ ("lxmert", "LxmertModel"),
168
+ ("m2m_100", "M2M100Model"),
169
+ ("mamba", "MambaModel"),
170
+ ("mamba2", "Mamba2Model"),
171
+ ("marian", "MarianModel"),
172
+ ("markuplm", "MarkupLMModel"),
173
+ ("mask2former", "Mask2FormerModel"),
174
+ ("maskformer", "MaskFormerModel"),
175
+ ("maskformer-swin", "MaskFormerSwinModel"),
176
+ ("mbart", "MBartModel"),
177
+ ("mctct", "MCTCTModel"),
178
+ ("mega", "MegaModel"),
179
+ ("megatron-bert", "MegatronBertModel"),
180
+ ("mgp-str", "MgpstrForSceneTextRecognition"),
181
+ ("mimi", "MimiModel"),
182
+ ("mistral", "MistralModel"),
183
+ ("mixtral", "MixtralModel"),
184
+ ("mobilebert", "MobileBertModel"),
185
+ ("mobilenet_v1", "MobileNetV1Model"),
186
+ ("mobilenet_v2", "MobileNetV2Model"),
187
+ ("mobilevit", "MobileViTModel"),
188
+ ("mobilevitv2", "MobileViTV2Model"),
189
+ ("modernbert", "ModernBertModel"),
190
+ ("moonshine", "MoonshineModel"),
191
+ ("moshi", "MoshiModel"),
192
+ ("mpnet", "MPNetModel"),
193
+ ("mpt", "MptModel"),
194
+ ("mra", "MraModel"),
195
+ ("mt5", "MT5Model"),
196
+ ("musicgen", "MusicgenModel"),
197
+ ("musicgen_melody", "MusicgenMelodyModel"),
198
+ ("mvp", "MvpModel"),
199
+ ("nat", "NatModel"),
200
+ ("nemotron", "NemotronModel"),
201
+ ("nezha", "NezhaModel"),
202
+ ("nllb-moe", "NllbMoeModel"),
203
+ ("nystromformer", "NystromformerModel"),
204
+ ("olmo", "OlmoModel"),
205
+ ("olmo2", "Olmo2Model"),
206
+ ("olmoe", "OlmoeModel"),
207
+ ("omdet-turbo", "OmDetTurboForObjectDetection"),
208
+ ("oneformer", "OneFormerModel"),
209
+ ("open-llama", "OpenLlamaModel"),
210
+ ("openai-gpt", "OpenAIGPTModel"),
211
+ ("opt", "OPTModel"),
212
+ ("owlv2", "Owlv2Model"),
213
+ ("owlvit", "OwlViTModel"),
214
+ ("patchtsmixer", "PatchTSMixerModel"),
215
+ ("patchtst", "PatchTSTModel"),
216
+ ("pegasus", "PegasusModel"),
217
+ ("pegasus_x", "PegasusXModel"),
218
+ ("perceiver", "PerceiverModel"),
219
+ ("persimmon", "PersimmonModel"),
220
+ ("phi", "PhiModel"),
221
+ ("phi3", "Phi3Model"),
222
+ ("phi4_multimodal", "Phi4MultimodalModel"),
223
+ ("phimoe", "PhimoeModel"),
224
+ ("pixtral", "PixtralVisionModel"),
225
+ ("plbart", "PLBartModel"),
226
+ ("poolformer", "PoolFormerModel"),
227
+ ("prophetnet", "ProphetNetModel"),
228
+ ("pvt", "PvtModel"),
229
+ ("pvt_v2", "PvtV2Model"),
230
+ ("qdqbert", "QDQBertModel"),
231
+ ("qwen2", "Qwen2Model"),
232
+ ("qwen2_5_vl", "Qwen2_5_VLModel"),
233
+ ("qwen2_audio_encoder", "Qwen2AudioEncoder"),
234
+ ("qwen2_moe", "Qwen2MoeModel"),
235
+ ("qwen2_vl", "Qwen2VLModel"),
236
+ ("qwen3", "Qwen3Model"),
237
+ ("qwen3_moe", "Qwen3MoeModel"),
238
+ ("recurrent_gemma", "RecurrentGemmaModel"),
239
+ ("reformer", "ReformerModel"),
240
+ ("regnet", "RegNetModel"),
241
+ ("rembert", "RemBertModel"),
242
+ ("resnet", "ResNetModel"),
243
+ ("retribert", "RetriBertModel"),
244
+ ("roberta", "RobertaModel"),
245
+ ("roberta-prelayernorm", "RobertaPreLayerNormModel"),
246
+ ("roc_bert", "RoCBertModel"),
247
+ ("roformer", "RoFormerModel"),
248
+ ("rt_detr", "RTDetrModel"),
249
+ ("rt_detr_v2", "RTDetrV2Model"),
250
+ ("rwkv", "RwkvModel"),
251
+ ("sam", "SamModel"),
252
+ ("sam_vision_model", "SamVisionModel"),
253
+ ("seamless_m4t", "SeamlessM4TModel"),
254
+ ("seamless_m4t_v2", "SeamlessM4Tv2Model"),
255
+ ("segformer", "SegformerModel"),
256
+ ("seggpt", "SegGptModel"),
257
+ ("sew", "SEWModel"),
258
+ ("sew-d", "SEWDModel"),
259
+ ("siglip", "SiglipModel"),
260
+ ("siglip2", "Siglip2Model"),
261
+ ("siglip_vision_model", "SiglipVisionModel"),
262
+ ("smolvlm", "SmolVLMModel"),
263
+ ("smolvlm_vision", "SmolVLMVisionTransformer"),
264
+ ("speech_to_text", "Speech2TextModel"),
265
+ ("speecht5", "SpeechT5Model"),
266
+ ("splinter", "SplinterModel"),
267
+ ("squeezebert", "SqueezeBertModel"),
268
+ ("stablelm", "StableLmModel"),
269
+ ("starcoder2", "Starcoder2Model"),
270
+ ("superglue", "SuperGlueForKeypointMatching"),
271
+ ("swiftformer", "SwiftFormerModel"),
272
+ ("swin", "SwinModel"),
273
+ ("swin2sr", "Swin2SRModel"),
274
+ ("swinv2", "Swinv2Model"),
275
+ ("switch_transformers", "SwitchTransformersModel"),
276
+ ("t5", "T5Model"),
277
+ ("table-transformer", "TableTransformerModel"),
278
+ ("tapas", "TapasModel"),
279
+ ("textnet", "TextNetModel"),
280
+ ("time_series_transformer", "TimeSeriesTransformerModel"),
281
+ ("timesformer", "TimesformerModel"),
282
+ ("timm_backbone", "TimmBackbone"),
283
+ ("timm_wrapper", "TimmWrapperModel"),
284
+ ("trajectory_transformer", "TrajectoryTransformerModel"),
285
+ ("transfo-xl", "TransfoXLModel"),
286
+ ("tvlt", "TvltModel"),
287
+ ("tvp", "TvpModel"),
288
+ ("udop", "UdopModel"),
289
+ ("umt5", "UMT5Model"),
290
+ ("unispeech", "UniSpeechModel"),
291
+ ("unispeech-sat", "UniSpeechSatModel"),
292
+ ("univnet", "UnivNetModel"),
293
+ ("van", "VanModel"),
294
+ ("videomae", "VideoMAEModel"),
295
+ ("vilt", "ViltModel"),
296
+ ("vision-text-dual-encoder", "VisionTextDualEncoderModel"),
297
+ ("visual_bert", "VisualBertModel"),
298
+ ("vit", "ViTModel"),
299
+ ("vit_hybrid", "ViTHybridModel"),
300
+ ("vit_mae", "ViTMAEModel"),
301
+ ("vit_msn", "ViTMSNModel"),
302
+ ("vitdet", "VitDetModel"),
303
+ ("vits", "VitsModel"),
304
+ ("vivit", "VivitModel"),
305
+ ("wav2vec2", "Wav2Vec2Model"),
306
+ ("wav2vec2-bert", "Wav2Vec2BertModel"),
307
+ ("wav2vec2-conformer", "Wav2Vec2ConformerModel"),
308
+ ("wavlm", "WavLMModel"),
309
+ ("whisper", "WhisperModel"),
310
+ ("xclip", "XCLIPModel"),
311
+ ("xglm", "XGLMModel"),
312
+ ("xlm", "XLMModel"),
313
+ ("xlm-prophetnet", "XLMProphetNetModel"),
314
+ ("xlm-roberta", "XLMRobertaModel"),
315
+ ("xlm-roberta-xl", "XLMRobertaXLModel"),
316
+ ("xlnet", "XLNetModel"),
317
+ ("xmod", "XmodModel"),
318
+ ("yolos", "YolosModel"),
319
+ ("yoso", "YosoModel"),
320
+ ("zamba", "ZambaModel"),
321
+ ("zamba2", "Zamba2Model"),
322
+ ]
323
+ )
324
+
325
+ MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
326
+ [
327
+ # Model for pre-training mapping
328
+ ("albert", "AlbertForPreTraining"),
329
+ ("bart", "BartForConditionalGeneration"),
330
+ ("bert", "BertForPreTraining"),
331
+ ("big_bird", "BigBirdForPreTraining"),
332
+ ("bloom", "BloomForCausalLM"),
333
+ ("camembert", "CamembertForMaskedLM"),
334
+ ("colpali", "ColPaliForRetrieval"),
335
+ ("ctrl", "CTRLLMHeadModel"),
336
+ ("data2vec-text", "Data2VecTextForMaskedLM"),
337
+ ("deberta", "DebertaForMaskedLM"),
338
+ ("deberta-v2", "DebertaV2ForMaskedLM"),
339
+ ("distilbert", "DistilBertForMaskedLM"),
340
+ ("electra", "ElectraForPreTraining"),
341
+ ("ernie", "ErnieForPreTraining"),
342
+ ("falcon_mamba", "FalconMambaForCausalLM"),
343
+ ("flaubert", "FlaubertWithLMHeadModel"),
344
+ ("flava", "FlavaForPreTraining"),
345
+ ("fnet", "FNetForPreTraining"),
346
+ ("fsmt", "FSMTForConditionalGeneration"),
347
+ ("funnel", "FunnelForPreTraining"),
348
+ ("gemma3", "Gemma3ForConditionalGeneration"),
349
+ ("gpt-sw3", "GPT2LMHeadModel"),
350
+ ("gpt2", "GPT2LMHeadModel"),
351
+ ("gpt_bigcode", "GPTBigCodeForCausalLM"),
352
+ ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
353
+ ("hiera", "HieraForPreTraining"),
354
+ ("ibert", "IBertForMaskedLM"),
355
+ ("idefics", "IdeficsForVisionText2Text"),
356
+ ("idefics2", "Idefics2ForConditionalGeneration"),
357
+ ("idefics3", "Idefics3ForConditionalGeneration"),
358
+ ("layoutlm", "LayoutLMForMaskedLM"),
359
+ ("llava", "LlavaForConditionalGeneration"),
360
+ ("llava_next", "LlavaNextForConditionalGeneration"),
361
+ ("llava_next_video", "LlavaNextVideoForConditionalGeneration"),
362
+ ("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
363
+ ("longformer", "LongformerForMaskedLM"),
364
+ ("luke", "LukeForMaskedLM"),
365
+ ("lxmert", "LxmertForPreTraining"),
366
+ ("mamba", "MambaForCausalLM"),
367
+ ("mamba2", "Mamba2ForCausalLM"),
368
+ ("mega", "MegaForMaskedLM"),
369
+ ("megatron-bert", "MegatronBertForPreTraining"),
370
+ ("mistral3", "Mistral3ForConditionalGeneration"),
371
+ ("mllama", "MllamaForConditionalGeneration"),
372
+ ("mobilebert", "MobileBertForPreTraining"),
373
+ ("mpnet", "MPNetForMaskedLM"),
374
+ ("mpt", "MptForCausalLM"),
375
+ ("mra", "MraForMaskedLM"),
376
+ ("mvp", "MvpForConditionalGeneration"),
377
+ ("nezha", "NezhaForPreTraining"),
378
+ ("nllb-moe", "NllbMoeForConditionalGeneration"),
379
+ ("openai-gpt", "OpenAIGPTLMHeadModel"),
380
+ ("paligemma", "PaliGemmaForConditionalGeneration"),
381
+ ("qwen2_audio", "Qwen2AudioForConditionalGeneration"),
382
+ ("retribert", "RetriBertModel"),
383
+ ("roberta", "RobertaForMaskedLM"),
384
+ ("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
385
+ ("roc_bert", "RoCBertForPreTraining"),
386
+ ("rwkv", "RwkvForCausalLM"),
387
+ ("splinter", "SplinterForPreTraining"),
388
+ ("squeezebert", "SqueezeBertForMaskedLM"),
389
+ ("switch_transformers", "SwitchTransformersForConditionalGeneration"),
390
+ ("t5", "T5ForConditionalGeneration"),
391
+ ("tapas", "TapasForMaskedLM"),
392
+ ("transfo-xl", "TransfoXLLMHeadModel"),
393
+ ("tvlt", "TvltForPreTraining"),
394
+ ("unispeech", "UniSpeechForPreTraining"),
395
+ ("unispeech-sat", "UniSpeechSatForPreTraining"),
396
+ ("video_llava", "VideoLlavaForConditionalGeneration"),
397
+ ("videomae", "VideoMAEForPreTraining"),
398
+ ("vipllava", "VipLlavaForConditionalGeneration"),
399
+ ("visual_bert", "VisualBertForPreTraining"),
400
+ ("vit_mae", "ViTMAEForPreTraining"),
401
+ ("wav2vec2", "Wav2Vec2ForPreTraining"),
402
+ ("wav2vec2-conformer", "Wav2Vec2ConformerForPreTraining"),
403
+ ("xlm", "XLMWithLMHeadModel"),
404
+ ("xlm-roberta", "XLMRobertaForMaskedLM"),
405
+ ("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
406
+ ("xlnet", "XLNetLMHeadModel"),
407
+ ("xmod", "XmodForMaskedLM"),
408
+ ]
409
+ )
410
+
411
+ MODEL_WITH_LM_HEAD_MAPPING_NAMES = OrderedDict(
412
+ [
413
+ # Model with LM heads mapping
414
+ ("albert", "AlbertForMaskedLM"),
415
+ ("bart", "BartForConditionalGeneration"),
416
+ ("bert", "BertForMaskedLM"),
417
+ ("big_bird", "BigBirdForMaskedLM"),
418
+ ("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"),
419
+ ("blenderbot-small", "BlenderbotSmallForConditionalGeneration"),
420
+ ("bloom", "BloomForCausalLM"),
421
+ ("camembert", "CamembertForMaskedLM"),
422
+ ("codegen", "CodeGenForCausalLM"),
423
+ ("convbert", "ConvBertForMaskedLM"),
424
+ ("cpmant", "CpmAntForCausalLM"),
425
+ ("ctrl", "CTRLLMHeadModel"),
426
+ ("data2vec-text", "Data2VecTextForMaskedLM"),
427
+ ("deberta", "DebertaForMaskedLM"),
428
+ ("deberta-v2", "DebertaV2ForMaskedLM"),
429
+ ("distilbert", "DistilBertForMaskedLM"),
430
+ ("electra", "ElectraForMaskedLM"),
431
+ ("encoder-decoder", "EncoderDecoderModel"),
432
+ ("ernie", "ErnieForMaskedLM"),
433
+ ("esm", "EsmForMaskedLM"),
434
+ ("falcon_mamba", "FalconMambaForCausalLM"),
435
+ ("flaubert", "FlaubertWithLMHeadModel"),
436
+ ("fnet", "FNetForMaskedLM"),
437
+ ("fsmt", "FSMTForConditionalGeneration"),
438
+ ("funnel", "FunnelForMaskedLM"),
439
+ ("git", "GitForCausalLM"),
440
+ ("gpt-sw3", "GPT2LMHeadModel"),
441
+ ("gpt2", "GPT2LMHeadModel"),
442
+ ("gpt_bigcode", "GPTBigCodeForCausalLM"),
443
+ ("gpt_neo", "GPTNeoForCausalLM"),
444
+ ("gpt_neox", "GPTNeoXForCausalLM"),
445
+ ("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"),
446
+ ("gptj", "GPTJForCausalLM"),
447
+ ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
448
+ ("ibert", "IBertForMaskedLM"),
449
+ ("layoutlm", "LayoutLMForMaskedLM"),
450
+ ("led", "LEDForConditionalGeneration"),
451
+ ("longformer", "LongformerForMaskedLM"),
452
+ ("longt5", "LongT5ForConditionalGeneration"),
453
+ ("luke", "LukeForMaskedLM"),
454
+ ("m2m_100", "M2M100ForConditionalGeneration"),
455
+ ("mamba", "MambaForCausalLM"),
456
+ ("mamba2", "Mamba2ForCausalLM"),
457
+ ("marian", "MarianMTModel"),
458
+ ("mega", "MegaForMaskedLM"),
459
+ ("megatron-bert", "MegatronBertForCausalLM"),
460
+ ("mobilebert", "MobileBertForMaskedLM"),
461
+ ("moonshine", "MoonshineForConditionalGeneration"),
462
+ ("mpnet", "MPNetForMaskedLM"),
463
+ ("mpt", "MptForCausalLM"),
464
+ ("mra", "MraForMaskedLM"),
465
+ ("mvp", "MvpForConditionalGeneration"),
466
+ ("nezha", "NezhaForMaskedLM"),
467
+ ("nllb-moe", "NllbMoeForConditionalGeneration"),
468
+ ("nystromformer", "NystromformerForMaskedLM"),
469
+ ("openai-gpt", "OpenAIGPTLMHeadModel"),
470
+ ("pegasus_x", "PegasusXForConditionalGeneration"),
471
+ ("plbart", "PLBartForConditionalGeneration"),
472
+ ("pop2piano", "Pop2PianoForConditionalGeneration"),
473
+ ("qdqbert", "QDQBertForMaskedLM"),
474
+ ("reformer", "ReformerModelWithLMHead"),
475
+ ("rembert", "RemBertForMaskedLM"),
476
+ ("roberta", "RobertaForMaskedLM"),
477
+ ("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
478
+ ("roc_bert", "RoCBertForMaskedLM"),
479
+ ("roformer", "RoFormerForMaskedLM"),
480
+ ("rwkv", "RwkvForCausalLM"),
481
+ ("speech_to_text", "Speech2TextForConditionalGeneration"),
482
+ ("squeezebert", "SqueezeBertForMaskedLM"),
483
+ ("switch_transformers", "SwitchTransformersForConditionalGeneration"),
484
+ ("t5", "T5ForConditionalGeneration"),
485
+ ("tapas", "TapasForMaskedLM"),
486
+ ("transfo-xl", "TransfoXLLMHeadModel"),
487
+ ("wav2vec2", "Wav2Vec2ForMaskedLM"),
488
+ ("whisper", "WhisperForConditionalGeneration"),
489
+ ("xlm", "XLMWithLMHeadModel"),
490
+ ("xlm-roberta", "XLMRobertaForMaskedLM"),
491
+ ("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
492
+ ("xlnet", "XLNetLMHeadModel"),
493
+ ("xmod", "XmodForMaskedLM"),
494
+ ("yoso", "YosoForMaskedLM"),
495
+ ]
496
+ )
497
+
498
+ MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
499
+ [
500
+ # Model for Causal LM mapping
501
+ ("aria_text", "AriaTextForCausalLM"),
502
+ ("bamba", "BambaForCausalLM"),
503
+ ("bart", "BartForCausalLM"),
504
+ ("bert", "BertLMHeadModel"),
505
+ ("bert-generation", "BertGenerationDecoder"),
506
+ ("big_bird", "BigBirdForCausalLM"),
507
+ ("bigbird_pegasus", "BigBirdPegasusForCausalLM"),
508
+ ("biogpt", "BioGptForCausalLM"),
509
+ ("blenderbot", "BlenderbotForCausalLM"),
510
+ ("blenderbot-small", "BlenderbotSmallForCausalLM"),
511
+ ("bloom", "BloomForCausalLM"),
512
+ ("camembert", "CamembertForCausalLM"),
513
+ ("code_llama", "LlamaForCausalLM"),
514
+ ("codegen", "CodeGenForCausalLM"),
515
+ ("cohere", "CohereForCausalLM"),
516
+ ("cohere2", "Cohere2ForCausalLM"),
517
+ ("cpmant", "CpmAntForCausalLM"),
518
+ ("ctrl", "CTRLLMHeadModel"),
519
+ ("data2vec-text", "Data2VecTextForCausalLM"),
520
+ ("dbrx", "DbrxForCausalLM"),
521
+ ("deepseek_v3", "DeepseekV3ForCausalLM"),
522
+ ("diffllama", "DiffLlamaForCausalLM"),
523
+ ("electra", "ElectraForCausalLM"),
524
+ ("emu3", "Emu3ForCausalLM"),
525
+ ("ernie", "ErnieForCausalLM"),
526
+ ("falcon", "FalconForCausalLM"),
527
+ ("falcon_mamba", "FalconMambaForCausalLM"),
528
+ ("fuyu", "FuyuForCausalLM"),
529
+ ("gemma", "GemmaForCausalLM"),
530
+ ("gemma2", "Gemma2ForCausalLM"),
531
+ ("gemma3", "Gemma3ForConditionalGeneration"),
532
+ ("gemma3_text", "Gemma3ForCausalLM"),
533
+ ("git", "GitForCausalLM"),
534
+ ("glm", "GlmForCausalLM"),
535
+ ("got_ocr2", "GotOcr2ForConditionalGeneration"),
536
+ ("gpt-sw3", "GPT2LMHeadModel"),
537
+ ("gpt2", "GPT2LMHeadModel"),
538
+ ("gpt_bigcode", "GPTBigCodeForCausalLM"),
539
+ ("gpt_neo", "GPTNeoForCausalLM"),
540
+ ("gpt_neox", "GPTNeoXForCausalLM"),
541
+ ("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"),
542
+ ("gptj", "GPTJForCausalLM"),
543
+ ("granite", "GraniteForCausalLM"),
544
+ ("granitemoe", "GraniteMoeForCausalLM"),
545
+ ("granitemoeshared", "GraniteMoeSharedForCausalLM"),
546
+ ("helium", "HeliumForCausalLM"),
547
+ ("jamba", "JambaForCausalLM"),
548
+ ("jetmoe", "JetMoeForCausalLM"),
549
+ ("llama", "LlamaForCausalLM"),
550
+ ("llama4", "Llama4ForCausalLM"),
551
+ ("llama4_text", "Llama4ForCausalLM"),
552
+ ("mamba", "MambaForCausalLM"),
553
+ ("mamba2", "Mamba2ForCausalLM"),
554
+ ("marian", "MarianForCausalLM"),
555
+ ("mbart", "MBartForCausalLM"),
556
+ ("mega", "MegaForCausalLM"),
557
+ ("megatron-bert", "MegatronBertForCausalLM"),
558
+ ("mistral", "MistralForCausalLM"),
559
+ ("mixtral", "MixtralForCausalLM"),
560
+ ("mllama", "MllamaForCausalLM"),
561
+ ("moshi", "MoshiForCausalLM"),
562
+ ("mpt", "MptForCausalLM"),
563
+ ("musicgen", "MusicgenForCausalLM"),
564
+ ("musicgen_melody", "MusicgenMelodyForCausalLM"),
565
+ ("mvp", "MvpForCausalLM"),
566
+ ("nemotron", "NemotronForCausalLM"),
567
+ ("olmo", "OlmoForCausalLM"),
568
+ ("olmo2", "Olmo2ForCausalLM"),
569
+ ("olmoe", "OlmoeForCausalLM"),
570
+ ("open-llama", "OpenLlamaForCausalLM"),
571
+ ("openai-gpt", "OpenAIGPTLMHeadModel"),
572
+ ("opt", "OPTForCausalLM"),
573
+ ("pegasus", "PegasusForCausalLM"),
574
+ ("persimmon", "PersimmonForCausalLM"),
575
+ ("phi", "PhiForCausalLM"),
576
+ ("phi3", "Phi3ForCausalLM"),
577
+ ("phi4_multimodal", "Phi4MultimodalForCausalLM"),
578
+ ("phimoe", "PhimoeForCausalLM"),
579
+ ("plbart", "PLBartForCausalLM"),
580
+ ("prophetnet", "ProphetNetForCausalLM"),
581
+ ("qdqbert", "QDQBertLMHeadModel"),
582
+ ("qwen2", "Qwen2ForCausalLM"),
583
+ ("qwen2_moe", "Qwen2MoeForCausalLM"),
584
+ ("qwen3", "Qwen3ForCausalLM"),
585
+ ("qwen3_moe", "Qwen3MoeForCausalLM"),
586
+ ("recurrent_gemma", "RecurrentGemmaForCausalLM"),
587
+ ("reformer", "ReformerModelWithLMHead"),
588
+ ("rembert", "RemBertForCausalLM"),
589
+ ("roberta", "RobertaForCausalLM"),
590
+ ("roberta-prelayernorm", "RobertaPreLayerNormForCausalLM"),
591
+ ("roc_bert", "RoCBertForCausalLM"),
592
+ ("roformer", "RoFormerForCausalLM"),
593
+ ("rwkv", "RwkvForCausalLM"),
594
+ ("speech_to_text_2", "Speech2Text2ForCausalLM"),
595
+ ("stablelm", "StableLmForCausalLM"),
596
+ ("starcoder2", "Starcoder2ForCausalLM"),
597
+ ("transfo-xl", "TransfoXLLMHeadModel"),
598
+ ("trocr", "TrOCRForCausalLM"),
599
+ ("whisper", "WhisperForCausalLM"),
600
+ ("xglm", "XGLMForCausalLM"),
601
+ ("xlm", "XLMWithLMHeadModel"),
602
+ ("xlm-prophetnet", "XLMProphetNetForCausalLM"),
603
+ ("xlm-roberta", "XLMRobertaForCausalLM"),
604
+ ("xlm-roberta-xl", "XLMRobertaXLForCausalLM"),
605
+ ("xlnet", "XLNetLMHeadModel"),
606
+ ("xmod", "XmodForCausalLM"),
607
+ ("zamba", "ZambaForCausalLM"),
608
+ ("zamba2", "Zamba2ForCausalLM"),
609
+ ]
610
+ )
611
+
612
+ MODEL_FOR_IMAGE_MAPPING_NAMES = OrderedDict(
613
+ [
614
+ # Model for Image mapping
615
+ ("beit", "BeitModel"),
616
+ ("bit", "BitModel"),
617
+ ("conditional_detr", "ConditionalDetrModel"),
618
+ ("convnext", "ConvNextModel"),
619
+ ("convnextv2", "ConvNextV2Model"),
620
+ ("dab-detr", "DabDetrModel"),
621
+ ("data2vec-vision", "Data2VecVisionModel"),
622
+ ("deformable_detr", "DeformableDetrModel"),
623
+ ("deit", "DeiTModel"),
624
+ ("depth_pro", "DepthProModel"),
625
+ ("deta", "DetaModel"),
626
+ ("detr", "DetrModel"),
627
+ ("dinat", "DinatModel"),
628
+ ("dinov2", "Dinov2Model"),
629
+ ("dinov2_with_registers", "Dinov2WithRegistersModel"),
630
+ ("dpt", "DPTModel"),
631
+ ("efficientformer", "EfficientFormerModel"),
632
+ ("efficientnet", "EfficientNetModel"),
633
+ ("focalnet", "FocalNetModel"),
634
+ ("glpn", "GLPNModel"),
635
+ ("hiera", "HieraModel"),
636
+ ("ijepa", "IJepaModel"),
637
+ ("imagegpt", "ImageGPTModel"),
638
+ ("levit", "LevitModel"),
639
+ ("llama4", "Llama4VisionModel"),
640
+ ("mllama", "MllamaVisionModel"),
641
+ ("mobilenet_v1", "MobileNetV1Model"),
642
+ ("mobilenet_v2", "MobileNetV2Model"),
643
+ ("mobilevit", "MobileViTModel"),
644
+ ("mobilevitv2", "MobileViTV2Model"),
645
+ ("nat", "NatModel"),
646
+ ("poolformer", "PoolFormerModel"),
647
+ ("pvt", "PvtModel"),
648
+ ("regnet", "RegNetModel"),
649
+ ("resnet", "ResNetModel"),
650
+ ("segformer", "SegformerModel"),
651
+ ("siglip_vision_model", "SiglipVisionModel"),
652
+ ("swiftformer", "SwiftFormerModel"),
653
+ ("swin", "SwinModel"),
654
+ ("swin2sr", "Swin2SRModel"),
655
+ ("swinv2", "Swinv2Model"),
656
+ ("table-transformer", "TableTransformerModel"),
657
+ ("timesformer", "TimesformerModel"),
658
+ ("timm_backbone", "TimmBackbone"),
659
+ ("timm_wrapper", "TimmWrapperModel"),
660
+ ("van", "VanModel"),
661
+ ("videomae", "VideoMAEModel"),
662
+ ("vit", "ViTModel"),
663
+ ("vit_hybrid", "ViTHybridModel"),
664
+ ("vit_mae", "ViTMAEModel"),
665
+ ("vit_msn", "ViTMSNModel"),
666
+ ("vitdet", "VitDetModel"),
667
+ ("vivit", "VivitModel"),
668
+ ("yolos", "YolosModel"),
669
+ ]
670
+ )
671
+
672
+ MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
673
+ [
674
+ ("deit", "DeiTForMaskedImageModeling"),
675
+ ("focalnet", "FocalNetForMaskedImageModeling"),
676
+ ("swin", "SwinForMaskedImageModeling"),
677
+ ("swinv2", "Swinv2ForMaskedImageModeling"),
678
+ ("vit", "ViTForMaskedImageModeling"),
679
+ ]
680
+ )
681
+
682
+
683
+ MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
684
+ # Model for Causal Image Modeling mapping
685
+ [
686
+ ("imagegpt", "ImageGPTForCausalImageModeling"),
687
+ ]
688
+ )
689
+
690
+ MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
691
+ [
692
+ # Model for Image Classification mapping
693
+ ("beit", "BeitForImageClassification"),
694
+ ("bit", "BitForImageClassification"),
695
+ ("clip", "CLIPForImageClassification"),
696
+ ("convnext", "ConvNextForImageClassification"),
697
+ ("convnextv2", "ConvNextV2ForImageClassification"),
698
+ ("cvt", "CvtForImageClassification"),
699
+ ("data2vec-vision", "Data2VecVisionForImageClassification"),
700
+ (
701
+ "deit",
702
+ ("DeiTForImageClassification", "DeiTForImageClassificationWithTeacher"),
703
+ ),
704
+ ("dinat", "DinatForImageClassification"),
705
+ ("dinov2", "Dinov2ForImageClassification"),
706
+ ("dinov2_with_registers", "Dinov2WithRegistersForImageClassification"),
707
+ (
708
+ "efficientformer",
709
+ (
710
+ "EfficientFormerForImageClassification",
711
+ "EfficientFormerForImageClassificationWithTeacher",
712
+ ),
713
+ ),
714
+ ("efficientnet", "EfficientNetForImageClassification"),
715
+ ("focalnet", "FocalNetForImageClassification"),
716
+ ("hiera", "HieraForImageClassification"),
717
+ ("ijepa", "IJepaForImageClassification"),
718
+ ("imagegpt", "ImageGPTForImageClassification"),
719
+ (
720
+ "levit",
721
+ ("LevitForImageClassification", "LevitForImageClassificationWithTeacher"),
722
+ ),
723
+ ("mobilenet_v1", "MobileNetV1ForImageClassification"),
724
+ ("mobilenet_v2", "MobileNetV2ForImageClassification"),
725
+ ("mobilevit", "MobileViTForImageClassification"),
726
+ ("mobilevitv2", "MobileViTV2ForImageClassification"),
727
+ ("nat", "NatForImageClassification"),
728
+ (
729
+ "perceiver",
730
+ (
731
+ "PerceiverForImageClassificationLearned",
732
+ "PerceiverForImageClassificationFourier",
733
+ "PerceiverForImageClassificationConvProcessing",
734
+ ),
735
+ ),
736
+ ("poolformer", "PoolFormerForImageClassification"),
737
+ ("pvt", "PvtForImageClassification"),
738
+ ("pvt_v2", "PvtV2ForImageClassification"),
739
+ ("regnet", "RegNetForImageClassification"),
740
+ ("resnet", "ResNetForImageClassification"),
741
+ ("segformer", "SegformerForImageClassification"),
742
+ ("shieldgemma2", "ShieldGemma2ForImageClassification"),
743
+ ("siglip", "SiglipForImageClassification"),
744
+ ("siglip2", "Siglip2ForImageClassification"),
745
+ ("swiftformer", "SwiftFormerForImageClassification"),
746
+ ("swin", "SwinForImageClassification"),
747
+ ("swinv2", "Swinv2ForImageClassification"),
748
+ ("textnet", "TextNetForImageClassification"),
749
+ ("timm_wrapper", "TimmWrapperForImageClassification"),
750
+ ("van", "VanForImageClassification"),
751
+ ("vit", "ViTForImageClassification"),
752
+ ("vit_hybrid", "ViTHybridForImageClassification"),
753
+ ("vit_msn", "ViTMSNForImageClassification"),
754
+ ]
755
+ )
756
+
757
+ MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = OrderedDict(
758
+ [
759
+ # Do not add new models here, this class will be deprecated in the future.
760
+ # Model for Image Segmentation mapping
761
+ ("detr", "DetrForSegmentation"),
762
+ ]
763
+ )
764
+
765
+ MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = OrderedDict(
766
+ [
767
+ # Model for Semantic Segmentation mapping
768
+ ("beit", "BeitForSemanticSegmentation"),
769
+ ("data2vec-vision", "Data2VecVisionForSemanticSegmentation"),
770
+ ("dpt", "DPTForSemanticSegmentation"),
771
+ ("mobilenet_v2", "MobileNetV2ForSemanticSegmentation"),
772
+ ("mobilevit", "MobileViTForSemanticSegmentation"),
773
+ ("mobilevitv2", "MobileViTV2ForSemanticSegmentation"),
774
+ ("segformer", "SegformerForSemanticSegmentation"),
775
+ ("upernet", "UperNetForSemanticSegmentation"),
776
+ ]
777
+ )
778
+
779
+ MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES = OrderedDict(
780
+ [
781
+ # Model for Instance Segmentation mapping
782
+ # MaskFormerForInstanceSegmentation can be removed from this mapping in v5
783
+ ("maskformer", "MaskFormerForInstanceSegmentation"),
784
+ ]
785
+ )
786
+
787
+ MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = OrderedDict(
788
+ [
789
+ # Model for Universal Segmentation mapping
790
+ ("detr", "DetrForSegmentation"),
791
+ ("mask2former", "Mask2FormerForUniversalSegmentation"),
792
+ ("maskformer", "MaskFormerForInstanceSegmentation"),
793
+ ("oneformer", "OneFormerForUniversalSegmentation"),
794
+ ]
795
+ )
796
+
797
+ MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
798
+ [
799
+ ("timesformer", "TimesformerForVideoClassification"),
800
+ ("videomae", "VideoMAEForVideoClassification"),
801
+ ("vivit", "VivitForVideoClassification"),
802
+ ]
803
+ )
804
+
805
+ MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
806
+ [
807
+ ("blip", "BlipForConditionalGeneration"),
808
+ ("blip-2", "Blip2ForConditionalGeneration"),
809
+ ("chameleon", "ChameleonForConditionalGeneration"),
810
+ ("git", "GitForCausalLM"),
811
+ ("idefics2", "Idefics2ForConditionalGeneration"),
812
+ ("idefics3", "Idefics3ForConditionalGeneration"),
813
+ ("instructblip", "InstructBlipForConditionalGeneration"),
814
+ ("instructblipvideo", "InstructBlipVideoForConditionalGeneration"),
815
+ ("kosmos-2", "Kosmos2ForConditionalGeneration"),
816
+ ("llava", "LlavaForConditionalGeneration"),
817
+ ("llava_next", "LlavaNextForConditionalGeneration"),
818
+ ("llava_next_video", "LlavaNextVideoForConditionalGeneration"),
819
+ ("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
820
+ ("mistral3", "Mistral3ForConditionalGeneration"),
821
+ ("mllama", "MllamaForConditionalGeneration"),
822
+ ("paligemma", "PaliGemmaForConditionalGeneration"),
823
+ ("pix2struct", "Pix2StructForConditionalGeneration"),
824
+ ("qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"),
825
+ ("qwen2_vl", "Qwen2VLForConditionalGeneration"),
826
+ ("video_llava", "VideoLlavaForConditionalGeneration"),
827
+ ("vipllava", "VipLlavaForConditionalGeneration"),
828
+ ("vision-encoder-decoder", "VisionEncoderDecoderModel"),
829
+ ]
830
+ )
831
+
832
+ MODEL_FOR_RETRIEVAL_MAPPING_NAMES = OrderedDict(
833
+ [
834
+ ("colpali", "ColPaliForRetrieval"),
835
+ ]
836
+ )
837
+
838
+ MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = OrderedDict(
839
+ [
840
+ ("aria", "AriaForConditionalGeneration"),
841
+ ("aya_vision", "AyaVisionForConditionalGeneration"),
842
+ ("blip", "BlipForConditionalGeneration"),
843
+ ("blip-2", "Blip2ForConditionalGeneration"),
844
+ ("chameleon", "ChameleonForConditionalGeneration"),
845
+ ("emu3", "Emu3ForConditionalGeneration"),
846
+ ("fuyu", "FuyuForCausalLM"),
847
+ ("gemma3", "Gemma3ForConditionalGeneration"),
848
+ ("git", "GitForCausalLM"),
849
+ ("got_ocr2", "GotOcr2ForConditionalGeneration"),
850
+ ("idefics", "IdeficsForVisionText2Text"),
851
+ ("idefics2", "Idefics2ForConditionalGeneration"),
852
+ ("idefics3", "Idefics3ForConditionalGeneration"),
853
+ ("instructblip", "InstructBlipForConditionalGeneration"),
854
+ ("kosmos-2", "Kosmos2ForConditionalGeneration"),
855
+ ("llama4", "Llama4ForConditionalGeneration"),
856
+ ("llava", "LlavaForConditionalGeneration"),
857
+ ("llava_next", "LlavaNextForConditionalGeneration"),
858
+ ("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
859
+ ("mistral3", "Mistral3ForConditionalGeneration"),
860
+ ("mllama", "MllamaForConditionalGeneration"),
861
+ ("paligemma", "PaliGemmaForConditionalGeneration"),
862
+ ("pix2struct", "Pix2StructForConditionalGeneration"),
863
+ ("pixtral", "LlavaForConditionalGeneration"),
864
+ ("qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"),
865
+ ("qwen2_vl", "Qwen2VLForConditionalGeneration"),
866
+ ("shieldgemma2", "Gemma3ForConditionalGeneration"),
867
+ ("smolvlm", "SmolVLMForConditionalGeneration"),
868
+ ("udop", "UdopForConditionalGeneration"),
869
+ ("vipllava", "VipLlavaForConditionalGeneration"),
870
+ ("vision-encoder-decoder", "VisionEncoderDecoderModel"),
871
+ ]
872
+ )
873
+
874
+ MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
875
+ [
876
+ # Model for Masked LM mapping
877
+ ("albert", "AlbertForMaskedLM"),
878
+ ("bart", "BartForConditionalGeneration"),
879
+ ("bert", "BertForMaskedLM"),
880
+ ("big_bird", "BigBirdForMaskedLM"),
881
+ ("camembert", "CamembertForMaskedLM"),
882
+ ("convbert", "ConvBertForMaskedLM"),
883
+ ("data2vec-text", "Data2VecTextForMaskedLM"),
884
+ ("deberta", "DebertaForMaskedLM"),
885
+ ("deberta-v2", "DebertaV2ForMaskedLM"),
886
+ ("distilbert", "DistilBertForMaskedLM"),
887
+ ("electra", "ElectraForMaskedLM"),
888
+ ("ernie", "ErnieForMaskedLM"),
889
+ ("esm", "EsmForMaskedLM"),
890
+ ("flaubert", "FlaubertWithLMHeadModel"),
891
+ ("fnet", "FNetForMaskedLM"),
892
+ ("funnel", "FunnelForMaskedLM"),
893
+ ("ibert", "IBertForMaskedLM"),
894
+ ("layoutlm", "LayoutLMForMaskedLM"),
895
+ ("longformer", "LongformerForMaskedLM"),
896
+ ("luke", "LukeForMaskedLM"),
897
+ ("mbart", "MBartForConditionalGeneration"),
898
+ ("mega", "MegaForMaskedLM"),
899
+ ("megatron-bert", "MegatronBertForMaskedLM"),
900
+ ("mobilebert", "MobileBertForMaskedLM"),
901
+ ("modernbert", "ModernBertForMaskedLM"),
902
+ ("mpnet", "MPNetForMaskedLM"),
903
+ ("mra", "MraForMaskedLM"),
904
+ ("mvp", "MvpForConditionalGeneration"),
905
+ ("nezha", "NezhaForMaskedLM"),
906
+ ("nystromformer", "NystromformerForMaskedLM"),
907
+ ("perceiver", "PerceiverForMaskedLM"),
908
+ ("qdqbert", "QDQBertForMaskedLM"),
909
+ ("reformer", "ReformerForMaskedLM"),
910
+ ("rembert", "RemBertForMaskedLM"),
911
+ ("roberta", "RobertaForMaskedLM"),
912
+ ("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
913
+ ("roc_bert", "RoCBertForMaskedLM"),
914
+ ("roformer", "RoFormerForMaskedLM"),
915
+ ("squeezebert", "SqueezeBertForMaskedLM"),
916
+ ("tapas", "TapasForMaskedLM"),
917
+ ("wav2vec2", "Wav2Vec2ForMaskedLM"),
918
+ ("xlm", "XLMWithLMHeadModel"),
919
+ ("xlm-roberta", "XLMRobertaForMaskedLM"),
920
+ ("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
921
+ ("xmod", "XmodForMaskedLM"),
922
+ ("yoso", "YosoForMaskedLM"),
923
+ ]
924
+ )
925
+
926
+ MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict(
927
+ [
928
+ # Model for Object Detection mapping
929
+ ("conditional_detr", "ConditionalDetrForObjectDetection"),
930
+ ("dab-detr", "DabDetrForObjectDetection"),
931
+ ("deformable_detr", "DeformableDetrForObjectDetection"),
932
+ ("deta", "DetaForObjectDetection"),
933
+ ("detr", "DetrForObjectDetection"),
934
+ ("rt_detr", "RTDetrForObjectDetection"),
935
+ ("rt_detr_v2", "RTDetrV2ForObjectDetection"),
936
+ ("table-transformer", "TableTransformerForObjectDetection"),
937
+ ("yolos", "YolosForObjectDetection"),
938
+ ]
939
+ )
940
+
941
+ MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict(
942
+ [
943
+ # Model for Zero Shot Object Detection mapping
944
+ ("grounding-dino", "GroundingDinoForObjectDetection"),
945
+ ("omdet-turbo", "OmDetTurboForObjectDetection"),
946
+ ("owlv2", "Owlv2ForObjectDetection"),
947
+ ("owlvit", "OwlViTForObjectDetection"),
948
+ ]
949
+ )
950
+
951
+ MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = OrderedDict(
952
+ [
953
+ # Model for depth estimation mapping
954
+ ("depth_anything", "DepthAnythingForDepthEstimation"),
955
+ ("depth_pro", "DepthProForDepthEstimation"),
956
+ ("dpt", "DPTForDepthEstimation"),
957
+ ("glpn", "GLPNForDepthEstimation"),
958
+ ("prompt_depth_anything", "PromptDepthAnythingForDepthEstimation"),
959
+ ("zoedepth", "ZoeDepthForDepthEstimation"),
960
+ ]
961
+ )
962
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
963
+ [
964
+ # Model for Seq2Seq Causal LM mapping
965
+ ("bart", "BartForConditionalGeneration"),
966
+ ("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"),
967
+ ("blenderbot", "BlenderbotForConditionalGeneration"),
968
+ ("blenderbot-small", "BlenderbotSmallForConditionalGeneration"),
969
+ ("encoder-decoder", "EncoderDecoderModel"),
970
+ ("fsmt", "FSMTForConditionalGeneration"),
971
+ ("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
972
+ ("led", "LEDForConditionalGeneration"),
973
+ ("longt5", "LongT5ForConditionalGeneration"),
974
+ ("m2m_100", "M2M100ForConditionalGeneration"),
975
+ ("marian", "MarianMTModel"),
976
+ ("mbart", "MBartForConditionalGeneration"),
977
+ ("mt5", "MT5ForConditionalGeneration"),
978
+ ("mvp", "MvpForConditionalGeneration"),
979
+ ("nllb-moe", "NllbMoeForConditionalGeneration"),
980
+ ("pegasus", "PegasusForConditionalGeneration"),
981
+ ("pegasus_x", "PegasusXForConditionalGeneration"),
982
+ ("plbart", "PLBartForConditionalGeneration"),
983
+ ("prophetnet", "ProphetNetForConditionalGeneration"),
984
+ ("qwen2_audio", "Qwen2AudioForConditionalGeneration"),
985
+ ("seamless_m4t", "SeamlessM4TForTextToText"),
986
+ ("seamless_m4t_v2", "SeamlessM4Tv2ForTextToText"),
987
+ ("switch_transformers", "SwitchTransformersForConditionalGeneration"),
988
+ ("t5", "T5ForConditionalGeneration"),
989
+ ("umt5", "UMT5ForConditionalGeneration"),
990
+ ("xlm-prophetnet", "XLMProphetNetForConditionalGeneration"),
991
+ ]
992
+ )
993
+
994
+ MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
995
+ [
996
+ ("moonshine", "MoonshineForConditionalGeneration"),
997
+ ("pop2piano", "Pop2PianoForConditionalGeneration"),
998
+ ("seamless_m4t", "SeamlessM4TForSpeechToText"),
999
+ ("seamless_m4t_v2", "SeamlessM4Tv2ForSpeechToText"),
1000
+ ("speech-encoder-decoder", "SpeechEncoderDecoderModel"),
1001
+ ("speech_to_text", "Speech2TextForConditionalGeneration"),
1002
+ ("speecht5", "SpeechT5ForSpeechToText"),
1003
+ ("whisper", "WhisperForConditionalGeneration"),
1004
+ ]
1005
+ )
1006
+
1007
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
1008
+ [
1009
+ # Model for Sequence Classification mapping
1010
+ ("albert", "AlbertForSequenceClassification"),
1011
+ ("bart", "BartForSequenceClassification"),
1012
+ ("bert", "BertForSequenceClassification"),
1013
+ ("big_bird", "BigBirdForSequenceClassification"),
1014
+ ("bigbird_pegasus", "BigBirdPegasusForSequenceClassification"),
1015
+ ("biogpt", "BioGptForSequenceClassification"),
1016
+ ("bloom", "BloomForSequenceClassification"),
1017
+ ("camembert", "CamembertForSequenceClassification"),
1018
+ ("canine", "CanineForSequenceClassification"),
1019
+ ("code_llama", "LlamaForSequenceClassification"),
1020
+ ("convbert", "ConvBertForSequenceClassification"),
1021
+ ("ctrl", "CTRLForSequenceClassification"),
1022
+ ("data2vec-text", "Data2VecTextForSequenceClassification"),
1023
+ ("deberta", "DebertaForSequenceClassification"),
1024
+ ("deberta-v2", "DebertaV2ForSequenceClassification"),
1025
+ ("diffllama", "DiffLlamaForSequenceClassification"),
1026
+ ("distilbert", "DistilBertForSequenceClassification"),
1027
+ ("electra", "ElectraForSequenceClassification"),
1028
+ ("ernie", "ErnieForSequenceClassification"),
1029
+ ("ernie_m", "ErnieMForSequenceClassification"),
1030
+ ("esm", "EsmForSequenceClassification"),
1031
+ ("falcon", "FalconForSequenceClassification"),
1032
+ ("flaubert", "FlaubertForSequenceClassification"),
1033
+ ("fnet", "FNetForSequenceClassification"),
1034
+ ("funnel", "FunnelForSequenceClassification"),
1035
+ ("gemma", "GemmaForSequenceClassification"),
1036
+ ("gemma2", "Gemma2ForSequenceClassification"),
1037
+ ("glm", "GlmForSequenceClassification"),
1038
+ ("gpt-sw3", "GPT2ForSequenceClassification"),
1039
+ ("gpt2", "GPT2ForSequenceClassification"),
1040
+ ("gpt_bigcode", "GPTBigCodeForSequenceClassification"),
1041
+ ("gpt_neo", "GPTNeoForSequenceClassification"),
1042
+ ("gpt_neox", "GPTNeoXForSequenceClassification"),
1043
+ ("gptj", "GPTJForSequenceClassification"),
1044
+ ("helium", "HeliumForSequenceClassification"),
1045
+ ("ibert", "IBertForSequenceClassification"),
1046
+ ("jamba", "JambaForSequenceClassification"),
1047
+ ("jetmoe", "JetMoeForSequenceClassification"),
1048
+ ("layoutlm", "LayoutLMForSequenceClassification"),
1049
+ ("layoutlmv2", "LayoutLMv2ForSequenceClassification"),
1050
+ ("layoutlmv3", "LayoutLMv3ForSequenceClassification"),
1051
+ ("led", "LEDForSequenceClassification"),
1052
+ ("lilt", "LiltForSequenceClassification"),
1053
+ ("llama", "LlamaForSequenceClassification"),
1054
+ ("longformer", "LongformerForSequenceClassification"),
1055
+ ("luke", "LukeForSequenceClassification"),
1056
+ ("markuplm", "MarkupLMForSequenceClassification"),
1057
+ ("mbart", "MBartForSequenceClassification"),
1058
+ ("mega", "MegaForSequenceClassification"),
1059
+ ("megatron-bert", "MegatronBertForSequenceClassification"),
1060
+ ("mistral", "MistralForSequenceClassification"),
1061
+ ("mixtral", "MixtralForSequenceClassification"),
1062
+ ("mobilebert", "MobileBertForSequenceClassification"),
1063
+ ("modernbert", "ModernBertForSequenceClassification"),
1064
+ ("mpnet", "MPNetForSequenceClassification"),
1065
+ ("mpt", "MptForSequenceClassification"),
1066
+ ("mra", "MraForSequenceClassification"),
1067
+ ("mt5", "MT5ForSequenceClassification"),
1068
+ ("mvp", "MvpForSequenceClassification"),
1069
+ ("nemotron", "NemotronForSequenceClassification"),
1070
+ ("nezha", "NezhaForSequenceClassification"),
1071
+ ("nystromformer", "NystromformerForSequenceClassification"),
1072
+ ("open-llama", "OpenLlamaForSequenceClassification"),
1073
+ ("openai-gpt", "OpenAIGPTForSequenceClassification"),
1074
+ ("opt", "OPTForSequenceClassification"),
1075
+ ("perceiver", "PerceiverForSequenceClassification"),
1076
+ ("persimmon", "PersimmonForSequenceClassification"),
1077
+ ("phi", "PhiForSequenceClassification"),
1078
+ ("phi3", "Phi3ForSequenceClassification"),
1079
+ ("phimoe", "PhimoeForSequenceClassification"),
1080
+ ("plbart", "PLBartForSequenceClassification"),
1081
+ ("qdqbert", "QDQBertForSequenceClassification"),
1082
+ ("qwen2", "Qwen2ForSequenceClassification"),
1083
+ ("qwen2_moe", "Qwen2MoeForSequenceClassification"),
1084
+ ("qwen3", "Qwen3ForSequenceClassification"),
1085
+ ("qwen3_moe", "Qwen3MoeForSequenceClassification"),
1086
+ ("reformer", "ReformerForSequenceClassification"),
1087
+ ("rembert", "RemBertForSequenceClassification"),
1088
+ ("roberta", "RobertaForSequenceClassification"),
1089
+ ("roberta-prelayernorm", "RobertaPreLayerNormForSequenceClassification"),
1090
+ ("roc_bert", "RoCBertForSequenceClassification"),
1091
+ ("roformer", "RoFormerForSequenceClassification"),
1092
+ ("squeezebert", "SqueezeBertForSequenceClassification"),
1093
+ ("stablelm", "StableLmForSequenceClassification"),
1094
+ ("starcoder2", "Starcoder2ForSequenceClassification"),
1095
+ ("t5", "T5ForSequenceClassification"),
1096
+ ("tapas", "TapasForSequenceClassification"),
1097
+ ("transfo-xl", "TransfoXLForSequenceClassification"),
1098
+ ("umt5", "UMT5ForSequenceClassification"),
1099
+ ("xlm", "XLMForSequenceClassification"),
1100
+ ("xlm-roberta", "XLMRobertaForSequenceClassification"),
1101
+ ("xlm-roberta-xl", "XLMRobertaXLForSequenceClassification"),
1102
+ ("xlnet", "XLNetForSequenceClassification"),
1103
+ ("xmod", "XmodForSequenceClassification"),
1104
+ ("yoso", "YosoForSequenceClassification"),
1105
+ ("zamba", "ZambaForSequenceClassification"),
1106
+ ("zamba2", "Zamba2ForSequenceClassification"),
1107
+ ]
1108
+ )
1109
+
1110
+ MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
1111
+ [
1112
+ # Model for Question Answering mapping
1113
+ ("albert", "AlbertForQuestionAnswering"),
1114
+ ("bart", "BartForQuestionAnswering"),
1115
+ ("bert", "BertForQuestionAnswering"),
1116
+ ("big_bird", "BigBirdForQuestionAnswering"),
1117
+ ("bigbird_pegasus", "BigBirdPegasusForQuestionAnswering"),
1118
+ ("bloom", "BloomForQuestionAnswering"),
1119
+ ("camembert", "CamembertForQuestionAnswering"),
1120
+ ("canine", "CanineForQuestionAnswering"),
1121
+ ("convbert", "ConvBertForQuestionAnswering"),
1122
+ ("data2vec-text", "Data2VecTextForQuestionAnswering"),
1123
+ ("deberta", "DebertaForQuestionAnswering"),
1124
+ ("deberta-v2", "DebertaV2ForQuestionAnswering"),
1125
+ ("diffllama", "DiffLlamaForQuestionAnswering"),
1126
+ ("distilbert", "DistilBertForQuestionAnswering"),
1127
+ ("electra", "ElectraForQuestionAnswering"),
1128
+ ("ernie", "ErnieForQuestionAnswering"),
1129
+ ("ernie_m", "ErnieMForQuestionAnswering"),
1130
+ ("falcon", "FalconForQuestionAnswering"),
1131
+ ("flaubert", "FlaubertForQuestionAnsweringSimple"),
1132
+ ("fnet", "FNetForQuestionAnswering"),
1133
+ ("funnel", "FunnelForQuestionAnswering"),
1134
+ ("gpt2", "GPT2ForQuestionAnswering"),
1135
+ ("gpt_neo", "GPTNeoForQuestionAnswering"),
1136
+ ("gpt_neox", "GPTNeoXForQuestionAnswering"),
1137
+ ("gptj", "GPTJForQuestionAnswering"),
1138
+ ("ibert", "IBertForQuestionAnswering"),
1139
+ ("layoutlmv2", "LayoutLMv2ForQuestionAnswering"),
1140
+ ("layoutlmv3", "LayoutLMv3ForQuestionAnswering"),
1141
+ ("led", "LEDForQuestionAnswering"),
1142
+ ("lilt", "LiltForQuestionAnswering"),
1143
+ ("llama", "LlamaForQuestionAnswering"),
1144
+ ("longformer", "LongformerForQuestionAnswering"),
1145
+ ("luke", "LukeForQuestionAnswering"),
1146
+ ("lxmert", "LxmertForQuestionAnswering"),
1147
+ ("markuplm", "MarkupLMForQuestionAnswering"),
1148
+ ("mbart", "MBartForQuestionAnswering"),
1149
+ ("mega", "MegaForQuestionAnswering"),
1150
+ ("megatron-bert", "MegatronBertForQuestionAnswering"),
1151
+ ("mistral", "MistralForQuestionAnswering"),
1152
+ ("mixtral", "MixtralForQuestionAnswering"),
1153
+ ("mobilebert", "MobileBertForQuestionAnswering"),
1154
+ ("modernbert", "ModernBertForQuestionAnswering"),
1155
+ ("mpnet", "MPNetForQuestionAnswering"),
1156
+ ("mpt", "MptForQuestionAnswering"),
1157
+ ("mra", "MraForQuestionAnswering"),
1158
+ ("mt5", "MT5ForQuestionAnswering"),
1159
+ ("mvp", "MvpForQuestionAnswering"),
1160
+ ("nemotron", "NemotronForQuestionAnswering"),
1161
+ ("nezha", "NezhaForQuestionAnswering"),
1162
+ ("nystromformer", "NystromformerForQuestionAnswering"),
1163
+ ("opt", "OPTForQuestionAnswering"),
1164
+ ("qdqbert", "QDQBertForQuestionAnswering"),
1165
+ ("qwen2", "Qwen2ForQuestionAnswering"),
1166
+ ("qwen2_moe", "Qwen2MoeForQuestionAnswering"),
1167
+ ("qwen3", "Qwen3ForQuestionAnswering"),
1168
+ ("qwen3_moe", "Qwen3MoeForQuestionAnswering"),
1169
+ ("reformer", "ReformerForQuestionAnswering"),
1170
+ ("rembert", "RemBertForQuestionAnswering"),
1171
+ ("roberta", "RobertaForQuestionAnswering"),
1172
+ ("roberta-prelayernorm", "RobertaPreLayerNormForQuestionAnswering"),
1173
+ ("roc_bert", "RoCBertForQuestionAnswering"),
1174
+ ("roformer", "RoFormerForQuestionAnswering"),
1175
+ ("splinter", "SplinterForQuestionAnswering"),
1176
+ ("squeezebert", "SqueezeBertForQuestionAnswering"),
1177
+ ("t5", "T5ForQuestionAnswering"),
1178
+ ("umt5", "UMT5ForQuestionAnswering"),
1179
+ ("xlm", "XLMForQuestionAnsweringSimple"),
1180
+ ("xlm-roberta", "XLMRobertaForQuestionAnswering"),
1181
+ ("xlm-roberta-xl", "XLMRobertaXLForQuestionAnswering"),
1182
+ ("xlnet", "XLNetForQuestionAnsweringSimple"),
1183
+ ("xmod", "XmodForQuestionAnswering"),
1184
+ ("yoso", "YosoForQuestionAnswering"),
1185
+ ]
1186
+ )
1187
+
1188
+ MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
1189
+ [
1190
+ # Model for Table Question Answering mapping
1191
+ ("tapas", "TapasForQuestionAnswering"),
1192
+ ]
1193
+ )
1194
+
1195
+ MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
1196
+ [
1197
+ ("blip", "BlipForQuestionAnswering"),
1198
+ ("blip-2", "Blip2ForConditionalGeneration"),
1199
+ ("vilt", "ViltForQuestionAnswering"),
1200
+ ]
1201
+ )
1202
+
1203
+ MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
1204
+ [
1205
+ ("layoutlm", "LayoutLMForQuestionAnswering"),
1206
+ ("layoutlmv2", "LayoutLMv2ForQuestionAnswering"),
1207
+ ("layoutlmv3", "LayoutLMv3ForQuestionAnswering"),
1208
+ ]
1209
+ )
1210
+
1211
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
1212
+ [
1213
+ # Model for Token Classification mapping
1214
+ ("albert", "AlbertForTokenClassification"),
1215
+ ("bert", "BertForTokenClassification"),
1216
+ ("big_bird", "BigBirdForTokenClassification"),
1217
+ ("biogpt", "BioGptForTokenClassification"),
1218
+ ("bloom", "BloomForTokenClassification"),
1219
+ ("bros", "BrosForTokenClassification"),
1220
+ ("camembert", "CamembertForTokenClassification"),
1221
+ ("canine", "CanineForTokenClassification"),
1222
+ ("convbert", "ConvBertForTokenClassification"),
1223
+ ("data2vec-text", "Data2VecTextForTokenClassification"),
1224
+ ("deberta", "DebertaForTokenClassification"),
1225
+ ("deberta-v2", "DebertaV2ForTokenClassification"),
1226
+ ("diffllama", "DiffLlamaForTokenClassification"),
1227
+ ("distilbert", "DistilBertForTokenClassification"),
1228
+ ("electra", "ElectraForTokenClassification"),
1229
+ ("ernie", "ErnieForTokenClassification"),
1230
+ ("ernie_m", "ErnieMForTokenClassification"),
1231
+ ("esm", "EsmForTokenClassification"),
1232
+ ("falcon", "FalconForTokenClassification"),
1233
+ ("flaubert", "FlaubertForTokenClassification"),
1234
+ ("fnet", "FNetForTokenClassification"),
1235
+ ("funnel", "FunnelForTokenClassification"),
1236
+ ("gemma", "GemmaForTokenClassification"),
1237
+ ("gemma2", "Gemma2ForTokenClassification"),
1238
+ ("glm", "GlmForTokenClassification"),
1239
+ ("gpt-sw3", "GPT2ForTokenClassification"),
1240
+ ("gpt2", "GPT2ForTokenClassification"),
1241
+ ("gpt_bigcode", "GPTBigCodeForTokenClassification"),
1242
+ ("gpt_neo", "GPTNeoForTokenClassification"),
1243
+ ("gpt_neox", "GPTNeoXForTokenClassification"),
1244
+ ("helium", "HeliumForTokenClassification"),
1245
+ ("ibert", "IBertForTokenClassification"),
1246
+ ("layoutlm", "LayoutLMForTokenClassification"),
1247
+ ("layoutlmv2", "LayoutLMv2ForTokenClassification"),
1248
+ ("layoutlmv3", "LayoutLMv3ForTokenClassification"),
1249
+ ("lilt", "LiltForTokenClassification"),
1250
+ ("llama", "LlamaForTokenClassification"),
1251
+ ("longformer", "LongformerForTokenClassification"),
1252
+ ("luke", "LukeForTokenClassification"),
1253
+ ("markuplm", "MarkupLMForTokenClassification"),
1254
+ ("mega", "MegaForTokenClassification"),
1255
+ ("megatron-bert", "MegatronBertForTokenClassification"),
1256
+ ("mistral", "MistralForTokenClassification"),
1257
+ ("mixtral", "MixtralForTokenClassification"),
1258
+ ("mobilebert", "MobileBertForTokenClassification"),
1259
+ ("modernbert", "ModernBertForTokenClassification"),
1260
+ ("mpnet", "MPNetForTokenClassification"),
1261
+ ("mpt", "MptForTokenClassification"),
1262
+ ("mra", "MraForTokenClassification"),
1263
+ ("mt5", "MT5ForTokenClassification"),
1264
+ ("nemotron", "NemotronForTokenClassification"),
1265
+ ("nezha", "NezhaForTokenClassification"),
1266
+ ("nystromformer", "NystromformerForTokenClassification"),
1267
+ ("persimmon", "PersimmonForTokenClassification"),
1268
+ ("phi", "PhiForTokenClassification"),
1269
+ ("phi3", "Phi3ForTokenClassification"),
1270
+ ("qdqbert", "QDQBertForTokenClassification"),
1271
+ ("qwen2", "Qwen2ForTokenClassification"),
1272
+ ("qwen2_moe", "Qwen2MoeForTokenClassification"),
1273
+ ("qwen3", "Qwen3ForTokenClassification"),
1274
+ ("qwen3_moe", "Qwen3MoeForTokenClassification"),
1275
+ ("rembert", "RemBertForTokenClassification"),
1276
+ ("roberta", "RobertaForTokenClassification"),
1277
+ ("roberta-prelayernorm", "RobertaPreLayerNormForTokenClassification"),
1278
+ ("roc_bert", "RoCBertForTokenClassification"),
1279
+ ("roformer", "RoFormerForTokenClassification"),
1280
+ ("squeezebert", "SqueezeBertForTokenClassification"),
1281
+ ("stablelm", "StableLmForTokenClassification"),
1282
+ ("starcoder2", "Starcoder2ForTokenClassification"),
1283
+ ("t5", "T5ForTokenClassification"),
1284
+ ("umt5", "UMT5ForTokenClassification"),
1285
+ ("xlm", "XLMForTokenClassification"),
1286
+ ("xlm-roberta", "XLMRobertaForTokenClassification"),
1287
+ ("xlm-roberta-xl", "XLMRobertaXLForTokenClassification"),
1288
+ ("xlnet", "XLNetForTokenClassification"),
1289
+ ("xmod", "XmodForTokenClassification"),
1290
+ ("yoso", "YosoForTokenClassification"),
1291
+ ]
1292
+ )
1293
+
1294
+ MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
1295
+ [
1296
+ # Model for Multiple Choice mapping
1297
+ ("albert", "AlbertForMultipleChoice"),
1298
+ ("bert", "BertForMultipleChoice"),
1299
+ ("big_bird", "BigBirdForMultipleChoice"),
1300
+ ("camembert", "CamembertForMultipleChoice"),
1301
+ ("canine", "CanineForMultipleChoice"),
1302
+ ("convbert", "ConvBertForMultipleChoice"),
1303
+ ("data2vec-text", "Data2VecTextForMultipleChoice"),
1304
+ ("deberta-v2", "DebertaV2ForMultipleChoice"),
1305
+ ("distilbert", "DistilBertForMultipleChoice"),
1306
+ ("electra", "ElectraForMultipleChoice"),
1307
+ ("ernie", "ErnieForMultipleChoice"),
1308
+ ("ernie_m", "ErnieMForMultipleChoice"),
1309
+ ("flaubert", "FlaubertForMultipleChoice"),
1310
+ ("fnet", "FNetForMultipleChoice"),
1311
+ ("funnel", "FunnelForMultipleChoice"),
1312
+ ("ibert", "IBertForMultipleChoice"),
1313
+ ("longformer", "LongformerForMultipleChoice"),
1314
+ ("luke", "LukeForMultipleChoice"),
1315
+ ("mega", "MegaForMultipleChoice"),
1316
+ ("megatron-bert", "MegatronBertForMultipleChoice"),
1317
+ ("mobilebert", "MobileBertForMultipleChoice"),
1318
+ ("mpnet", "MPNetForMultipleChoice"),
1319
+ ("mra", "MraForMultipleChoice"),
1320
+ ("nezha", "NezhaForMultipleChoice"),
1321
+ ("nystromformer", "NystromformerForMultipleChoice"),
1322
+ ("qdqbert", "QDQBertForMultipleChoice"),
1323
+ ("rembert", "RemBertForMultipleChoice"),
1324
+ ("roberta", "RobertaForMultipleChoice"),
1325
+ ("roberta-prelayernorm", "RobertaPreLayerNormForMultipleChoice"),
1326
+ ("roc_bert", "RoCBertForMultipleChoice"),
1327
+ ("roformer", "RoFormerForMultipleChoice"),
1328
+ ("squeezebert", "SqueezeBertForMultipleChoice"),
1329
+ ("xlm", "XLMForMultipleChoice"),
1330
+ ("xlm-roberta", "XLMRobertaForMultipleChoice"),
1331
+ ("xlm-roberta-xl", "XLMRobertaXLForMultipleChoice"),
1332
+ ("xlnet", "XLNetForMultipleChoice"),
1333
+ ("xmod", "XmodForMultipleChoice"),
1334
+ ("yoso", "YosoForMultipleChoice"),
1335
+ ]
1336
+ )
1337
+
1338
+ MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
1339
+ [
1340
+ ("bert", "BertForNextSentencePrediction"),
1341
+ ("ernie", "ErnieForNextSentencePrediction"),
1342
+ ("fnet", "FNetForNextSentencePrediction"),
1343
+ ("megatron-bert", "MegatronBertForNextSentencePrediction"),
1344
+ ("mobilebert", "MobileBertForNextSentencePrediction"),
1345
+ ("nezha", "NezhaForNextSentencePrediction"),
1346
+ ("qdqbert", "QDQBertForNextSentencePrediction"),
1347
+ ]
1348
+ )
1349
+
1350
+ MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
1351
+ [
1352
+ # Model for Audio Classification mapping
1353
+ ("audio-spectrogram-transformer", "ASTForAudioClassification"),
1354
+ ("data2vec-audio", "Data2VecAudioForSequenceClassification"),
1355
+ ("hubert", "HubertForSequenceClassification"),
1356
+ ("sew", "SEWForSequenceClassification"),
1357
+ ("sew-d", "SEWDForSequenceClassification"),
1358
+ ("unispeech", "UniSpeechForSequenceClassification"),
1359
+ ("unispeech-sat", "UniSpeechSatForSequenceClassification"),
1360
+ ("wav2vec2", "Wav2Vec2ForSequenceClassification"),
1361
+ ("wav2vec2-bert", "Wav2Vec2BertForSequenceClassification"),
1362
+ ("wav2vec2-conformer", "Wav2Vec2ConformerForSequenceClassification"),
1363
+ ("wavlm", "WavLMForSequenceClassification"),
1364
+ ("whisper", "WhisperForAudioClassification"),
1365
+ ]
1366
+ )
1367
+
1368
+ MODEL_FOR_CTC_MAPPING_NAMES = OrderedDict(
1369
+ [
1370
+ # Model for Connectionist temporal classification (CTC) mapping
1371
+ ("data2vec-audio", "Data2VecAudioForCTC"),
1372
+ ("hubert", "HubertForCTC"),
1373
+ ("mctct", "MCTCTForCTC"),
1374
+ ("sew", "SEWForCTC"),
1375
+ ("sew-d", "SEWDForCTC"),
1376
+ ("unispeech", "UniSpeechForCTC"),
1377
+ ("unispeech-sat", "UniSpeechSatForCTC"),
1378
+ ("wav2vec2", "Wav2Vec2ForCTC"),
1379
+ ("wav2vec2-bert", "Wav2Vec2BertForCTC"),
1380
+ ("wav2vec2-conformer", "Wav2Vec2ConformerForCTC"),
1381
+ ("wavlm", "WavLMForCTC"),
1382
+ ]
1383
+ )
1384
+
1385
+ MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
1386
+ [
1387
+ # Model for Audio Classification mapping
1388
+ ("data2vec-audio", "Data2VecAudioForAudioFrameClassification"),
1389
+ ("unispeech-sat", "UniSpeechSatForAudioFrameClassification"),
1390
+ ("wav2vec2", "Wav2Vec2ForAudioFrameClassification"),
1391
+ ("wav2vec2-bert", "Wav2Vec2BertForAudioFrameClassification"),
1392
+ ("wav2vec2-conformer", "Wav2Vec2ConformerForAudioFrameClassification"),
1393
+ ("wavlm", "WavLMForAudioFrameClassification"),
1394
+ ]
1395
+ )
1396
+
1397
+ MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = OrderedDict(
1398
+ [
1399
+ # Model for Audio Classification mapping
1400
+ ("data2vec-audio", "Data2VecAudioForXVector"),
1401
+ ("unispeech-sat", "UniSpeechSatForXVector"),
1402
+ ("wav2vec2", "Wav2Vec2ForXVector"),
1403
+ ("wav2vec2-bert", "Wav2Vec2BertForXVector"),
1404
+ ("wav2vec2-conformer", "Wav2Vec2ConformerForXVector"),
1405
+ ("wavlm", "WavLMForXVector"),
1406
+ ]
1407
+ )
1408
+
1409
+ MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = OrderedDict(
1410
+ [
1411
+ # Model for Text-To-Spectrogram mapping
1412
+ ("fastspeech2_conformer", "FastSpeech2ConformerModel"),
1413
+ ("speecht5", "SpeechT5ForTextToSpeech"),
1414
+ ]
1415
+ )
1416
+
1417
+ MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = OrderedDict(
1418
+ [
1419
+ # Model for Text-To-Waveform mapping
1420
+ ("bark", "BarkModel"),
1421
+ ("fastspeech2_conformer", "FastSpeech2ConformerWithHifiGan"),
1422
+ ("musicgen", "MusicgenForConditionalGeneration"),
1423
+ ("musicgen_melody", "MusicgenMelodyForConditionalGeneration"),
1424
+ ("seamless_m4t", "SeamlessM4TForTextToSpeech"),
1425
+ ("seamless_m4t_v2", "SeamlessM4Tv2ForTextToSpeech"),
1426
+ ("vits", "VitsModel"),
1427
+ ]
1428
+ )
1429
+
1430
+ MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
1431
+ [
1432
+ # Model for Zero Shot Image Classification mapping
1433
+ ("align", "AlignModel"),
1434
+ ("altclip", "AltCLIPModel"),
1435
+ ("blip", "BlipModel"),
1436
+ ("blip-2", "Blip2ForImageTextRetrieval"),
1437
+ ("chinese_clip", "ChineseCLIPModel"),
1438
+ ("clip", "CLIPModel"),
1439
+ ("clipseg", "CLIPSegModel"),
1440
+ ("siglip", "SiglipModel"),
1441
+ ("siglip2", "Siglip2Model"),
1442
+ ]
1443
+ )
1444
+
1445
+ MODEL_FOR_BACKBONE_MAPPING_NAMES = OrderedDict(
1446
+ [
1447
+ # Backbone mapping
1448
+ ("beit", "BeitBackbone"),
1449
+ ("bit", "BitBackbone"),
1450
+ ("convnext", "ConvNextBackbone"),
1451
+ ("convnextv2", "ConvNextV2Backbone"),
1452
+ ("dinat", "DinatBackbone"),
1453
+ ("dinov2", "Dinov2Backbone"),
1454
+ ("dinov2_with_registers", "Dinov2WithRegistersBackbone"),
1455
+ ("focalnet", "FocalNetBackbone"),
1456
+ ("hiera", "HieraBackbone"),
1457
+ ("maskformer-swin", "MaskFormerSwinBackbone"),
1458
+ ("nat", "NatBackbone"),
1459
+ ("pvt_v2", "PvtV2Backbone"),
1460
+ ("resnet", "ResNetBackbone"),
1461
+ ("rt_detr_resnet", "RTDetrResNetBackbone"),
1462
+ ("swin", "SwinBackbone"),
1463
+ ("swinv2", "Swinv2Backbone"),
1464
+ ("textnet", "TextNetBackbone"),
1465
+ ("timm_backbone", "TimmBackbone"),
1466
+ ("vitdet", "VitDetBackbone"),
1467
+ ("vitpose_backbone", "VitPoseBackbone"),
1468
+ ]
1469
+ )
1470
+
1471
+ MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = OrderedDict(
1472
+ [
1473
+ ("sam", "SamModel"),
1474
+ ]
1475
+ )
1476
+
1477
+
1478
+ MODEL_FOR_KEYPOINT_DETECTION_MAPPING_NAMES = OrderedDict(
1479
+ [
1480
+ ("superpoint", "SuperPointForKeypointDetection"),
1481
+ ]
1482
+ )
1483
+
1484
+
1485
+ MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES = OrderedDict(
1486
+ [
1487
+ ("albert", "AlbertModel"),
1488
+ ("bert", "BertModel"),
1489
+ ("big_bird", "BigBirdModel"),
1490
+ ("clip_text_model", "CLIPTextModel"),
1491
+ ("data2vec-text", "Data2VecTextModel"),
1492
+ ("deberta", "DebertaModel"),
1493
+ ("deberta-v2", "DebertaV2Model"),
1494
+ ("distilbert", "DistilBertModel"),
1495
+ ("electra", "ElectraModel"),
1496
+ ("emu3", "Emu3TextModel"),
1497
+ ("flaubert", "FlaubertModel"),
1498
+ ("ibert", "IBertModel"),
1499
+ ("llama4", "Llama4TextModel"),
1500
+ ("longformer", "LongformerModel"),
1501
+ ("mllama", "MllamaTextModel"),
1502
+ ("mobilebert", "MobileBertModel"),
1503
+ ("mt5", "MT5EncoderModel"),
1504
+ ("nystromformer", "NystromformerModel"),
1505
+ ("reformer", "ReformerModel"),
1506
+ ("rembert", "RemBertModel"),
1507
+ ("roberta", "RobertaModel"),
1508
+ ("roberta-prelayernorm", "RobertaPreLayerNormModel"),
1509
+ ("roc_bert", "RoCBertModel"),
1510
+ ("roformer", "RoFormerModel"),
1511
+ ("squeezebert", "SqueezeBertModel"),
1512
+ ("t5", "T5EncoderModel"),
1513
+ ("umt5", "UMT5EncoderModel"),
1514
+ ("xlm", "XLMModel"),
1515
+ ("xlm-roberta", "XLMRobertaModel"),
1516
+ ("xlm-roberta-xl", "XLMRobertaXLModel"),
1517
+ ]
1518
+ )
1519
+
1520
+ MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
1521
+ [
1522
+ ("patchtsmixer", "PatchTSMixerForTimeSeriesClassification"),
1523
+ ("patchtst", "PatchTSTForClassification"),
1524
+ ]
1525
+ )
1526
+
1527
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING_NAMES = OrderedDict(
1528
+ [
1529
+ ("patchtsmixer", "PatchTSMixerForRegression"),
1530
+ ("patchtst", "PatchTSTForRegression"),
1531
+ ]
1532
+ )
1533
+
1534
+ MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = OrderedDict(
1535
+ [
1536
+ ("swin2sr", "Swin2SRForImageSuperResolution"),
1537
+ ]
1538
+ )
1539
+
1540
+ MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_MAPPING_NAMES)
1541
+ MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_PRETRAINING_MAPPING_NAMES)
1542
+ MODEL_WITH_LM_HEAD_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_WITH_LM_HEAD_MAPPING_NAMES)
1543
+ MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
1544
+ MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
1545
+ CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES
1546
+ )
1547
+ MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1548
+ CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
1549
+ )
1550
+ MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1551
+ CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
1552
+ )
1553
+ MODEL_FOR_IMAGE_SEGMENTATION_MAPPING = _LazyAutoMapping(
1554
+ CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES
1555
+ )
1556
+ MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = _LazyAutoMapping(
1557
+ CONFIG_MAPPING_NAMES, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES
1558
+ )
1559
+ MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING = _LazyAutoMapping(
1560
+ CONFIG_MAPPING_NAMES, MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES
1561
+ )
1562
+ MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING = _LazyAutoMapping(
1563
+ CONFIG_MAPPING_NAMES, MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES
1564
+ )
1565
+ MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1566
+ CONFIG_MAPPING_NAMES, MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
1567
+ )
1568
+ MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
1569
+ MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING = _LazyAutoMapping(
1570
+ CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
1571
+ )
1572
+ MODEL_FOR_RETRIEVAL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_RETRIEVAL_MAPPING_NAMES)
1573
+ MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
1574
+ CONFIG_MAPPING_NAMES, MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES
1575
+ )
1576
+ MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
1577
+ CONFIG_MAPPING_NAMES, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
1578
+ )
1579
+ MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES)
1580
+ MODEL_FOR_IMAGE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_MAPPING_NAMES)
1581
+ MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
1582
+ CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES
1583
+ )
1584
+ MODEL_FOR_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES)
1585
+ MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(
1586
+ CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES
1587
+ )
1588
+ MODEL_FOR_DEPTH_ESTIMATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
1589
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
1590
+ CONFIG_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
1591
+ )
1592
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1593
+ CONFIG_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
1594
+ )
1595
+ MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
1596
+ CONFIG_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
1597
+ )
1598
+ MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
1599
+ CONFIG_MAPPING_NAMES, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES
1600
+ )
1601
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1602
+ CONFIG_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
1603
+ )
1604
+ MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES)
1605
+ MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
1606
+ CONFIG_MAPPING_NAMES, MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
1607
+ )
1608
+ MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1609
+ CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
1610
+ )
1611
+ MODEL_FOR_CTC_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES)
1612
+ MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES)
1613
+ MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1614
+ CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES
1615
+ )
1616
+ MODEL_FOR_AUDIO_XVECTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES)
1617
+
1618
+ MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING = _LazyAutoMapping(
1619
+ CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES
1620
+ )
1621
+
1622
+ MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES)
1623
+
1624
+ MODEL_FOR_BACKBONE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_BACKBONE_MAPPING_NAMES)
1625
+
1626
+ MODEL_FOR_MASK_GENERATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
1627
+
1628
+ MODEL_FOR_KEYPOINT_DETECTION_MAPPING = _LazyAutoMapping(
1629
+ CONFIG_MAPPING_NAMES, MODEL_FOR_KEYPOINT_DETECTION_MAPPING_NAMES
1630
+ )
1631
+
1632
+ MODEL_FOR_TEXT_ENCODING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES)
1633
+
1634
+ MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING = _LazyAutoMapping(
1635
+ CONFIG_MAPPING_NAMES, MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING_NAMES
1636
+ )
1637
+
1638
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING = _LazyAutoMapping(
1639
+ CONFIG_MAPPING_NAMES, MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING_NAMES
1640
+ )
1641
+
1642
+ MODEL_FOR_IMAGE_TO_IMAGE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES)
1643
+
1644
+
1645
+ class AutoModelForMaskGeneration(_BaseAutoModelClass):
1646
+ _model_mapping = MODEL_FOR_MASK_GENERATION_MAPPING
1647
+
1648
+
1649
+ class AutoModelForKeypointDetection(_BaseAutoModelClass):
1650
+ _model_mapping = MODEL_FOR_KEYPOINT_DETECTION_MAPPING
1651
+
1652
+
1653
+ class AutoModelForTextEncoding(_BaseAutoModelClass):
1654
+ _model_mapping = MODEL_FOR_TEXT_ENCODING_MAPPING
1655
+
1656
+
1657
+ class AutoModelForImageToImage(_BaseAutoModelClass):
1658
+ _model_mapping = MODEL_FOR_IMAGE_TO_IMAGE_MAPPING
1659
+
1660
+
1661
+ class AutoModel(_BaseAutoModelClass):
1662
+ _model_mapping = MODEL_MAPPING
1663
+
1664
+
1665
+ AutoModel = auto_class_update(AutoModel)
1666
+
1667
+
1668
+ class AutoModelForPreTraining(_BaseAutoModelClass):
1669
+ _model_mapping = MODEL_FOR_PRETRAINING_MAPPING
1670
+
1671
+
1672
+ AutoModelForPreTraining = auto_class_update(AutoModelForPreTraining, head_doc="pretraining")
1673
+
1674
+
1675
+ # Private on purpose, the public class will add the deprecation warnings.
1676
+ class _AutoModelWithLMHead(_BaseAutoModelClass):
1677
+ _model_mapping = MODEL_WITH_LM_HEAD_MAPPING
1678
+
1679
+
1680
+ _AutoModelWithLMHead = auto_class_update(_AutoModelWithLMHead, head_doc="language modeling")
1681
+
1682
+
1683
+ class AutoModelForCausalLM(_BaseAutoModelClass):
1684
+ _model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING
1685
+
1686
+
1687
+ AutoModelForCausalLM = auto_class_update(AutoModelForCausalLM, head_doc="causal language modeling")
1688
+
1689
+
1690
+ class AutoModelForMaskedLM(_BaseAutoModelClass):
1691
+ _model_mapping = MODEL_FOR_MASKED_LM_MAPPING
1692
+
1693
+
1694
+ AutoModelForMaskedLM = auto_class_update(AutoModelForMaskedLM, head_doc="masked language modeling")
1695
+
1696
+
1697
+ class AutoModelForSeq2SeqLM(_BaseAutoModelClass):
1698
+ _model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
1699
+
1700
+
1701
+ AutoModelForSeq2SeqLM = auto_class_update(
1702
+ AutoModelForSeq2SeqLM,
1703
+ head_doc="sequence-to-sequence language modeling",
1704
+ checkpoint_for_example="google-t5/t5-base",
1705
+ )
1706
+
1707
+
1708
+ class AutoModelForSequenceClassification(_BaseAutoModelClass):
1709
+ _model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
1710
+
1711
+
1712
+ AutoModelForSequenceClassification = auto_class_update(
1713
+ AutoModelForSequenceClassification, head_doc="sequence classification"
1714
+ )
1715
+
1716
+
1717
+ class AutoModelForQuestionAnswering(_BaseAutoModelClass):
1718
+ _model_mapping = MODEL_FOR_QUESTION_ANSWERING_MAPPING
1719
+
1720
+
1721
+ AutoModelForQuestionAnswering = auto_class_update(AutoModelForQuestionAnswering, head_doc="question answering")
1722
+
1723
+
1724
+ class AutoModelForTableQuestionAnswering(_BaseAutoModelClass):
1725
+ _model_mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING
1726
+
1727
+
1728
+ AutoModelForTableQuestionAnswering = auto_class_update(
1729
+ AutoModelForTableQuestionAnswering,
1730
+ head_doc="table question answering",
1731
+ checkpoint_for_example="google/tapas-base-finetuned-wtq",
1732
+ )
1733
+
1734
+
1735
+ class AutoModelForVisualQuestionAnswering(_BaseAutoModelClass):
1736
+ _model_mapping = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING
1737
+
1738
+
1739
+ AutoModelForVisualQuestionAnswering = auto_class_update(
1740
+ AutoModelForVisualQuestionAnswering,
1741
+ head_doc="visual question answering",
1742
+ checkpoint_for_example="dandelin/vilt-b32-finetuned-vqa",
1743
+ )
1744
+
1745
+
1746
+ class AutoModelForDocumentQuestionAnswering(_BaseAutoModelClass):
1747
+ _model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
1748
+
1749
+
1750
+ AutoModelForDocumentQuestionAnswering = auto_class_update(
1751
+ AutoModelForDocumentQuestionAnswering,
1752
+ head_doc="document question answering",
1753
+ checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3',
1754
+ )
1755
+
1756
+
1757
+ class AutoModelForTokenClassification(_BaseAutoModelClass):
1758
+ _model_mapping = MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
1759
+
1760
+
1761
+ AutoModelForTokenClassification = auto_class_update(AutoModelForTokenClassification, head_doc="token classification")
1762
+
1763
+
1764
+ class AutoModelForMultipleChoice(_BaseAutoModelClass):
1765
+ _model_mapping = MODEL_FOR_MULTIPLE_CHOICE_MAPPING
1766
+
1767
+
1768
+ AutoModelForMultipleChoice = auto_class_update(AutoModelForMultipleChoice, head_doc="multiple choice")
1769
+
1770
+
1771
+ class AutoModelForNextSentencePrediction(_BaseAutoModelClass):
1772
+ _model_mapping = MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
1773
+
1774
+
1775
+ AutoModelForNextSentencePrediction = auto_class_update(
1776
+ AutoModelForNextSentencePrediction, head_doc="next sentence prediction"
1777
+ )
1778
+
1779
+
1780
+ class AutoModelForImageClassification(_BaseAutoModelClass):
1781
+ _model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
1782
+
1783
+
1784
+ AutoModelForImageClassification = auto_class_update(AutoModelForImageClassification, head_doc="image classification")
1785
+
1786
+
1787
+ class AutoModelForZeroShotImageClassification(_BaseAutoModelClass):
1788
+ _model_mapping = MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
1789
+
1790
+
1791
+ AutoModelForZeroShotImageClassification = auto_class_update(
1792
+ AutoModelForZeroShotImageClassification, head_doc="zero-shot image classification"
1793
+ )
1794
+
1795
+
1796
+ class AutoModelForImageSegmentation(_BaseAutoModelClass):
1797
+ _model_mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING
1798
+
1799
+
1800
+ AutoModelForImageSegmentation = auto_class_update(AutoModelForImageSegmentation, head_doc="image segmentation")
1801
+
1802
+
1803
+ class AutoModelForSemanticSegmentation(_BaseAutoModelClass):
1804
+ _model_mapping = MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
1805
+
1806
+
1807
+ AutoModelForSemanticSegmentation = auto_class_update(
1808
+ AutoModelForSemanticSegmentation, head_doc="semantic segmentation"
1809
+ )
1810
+
1811
+
1812
+ class AutoModelForUniversalSegmentation(_BaseAutoModelClass):
1813
+ _model_mapping = MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING
1814
+
1815
+
1816
+ AutoModelForUniversalSegmentation = auto_class_update(
1817
+ AutoModelForUniversalSegmentation, head_doc="universal image segmentation"
1818
+ )
1819
+
1820
+
1821
+ class AutoModelForInstanceSegmentation(_BaseAutoModelClass):
1822
+ _model_mapping = MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING
1823
+
1824
+
1825
+ AutoModelForInstanceSegmentation = auto_class_update(
1826
+ AutoModelForInstanceSegmentation, head_doc="instance segmentation"
1827
+ )
1828
+
1829
+
1830
+ class AutoModelForObjectDetection(_BaseAutoModelClass):
1831
+ _model_mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING
1832
+
1833
+
1834
+ AutoModelForObjectDetection = auto_class_update(AutoModelForObjectDetection, head_doc="object detection")
1835
+
1836
+
1837
+ class AutoModelForZeroShotObjectDetection(_BaseAutoModelClass):
1838
+ _model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
1839
+
1840
+
1841
+ AutoModelForZeroShotObjectDetection = auto_class_update(
1842
+ AutoModelForZeroShotObjectDetection, head_doc="zero-shot object detection"
1843
+ )
1844
+
1845
+
1846
+ class AutoModelForDepthEstimation(_BaseAutoModelClass):
1847
+ _model_mapping = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
1848
+
1849
+
1850
+ AutoModelForDepthEstimation = auto_class_update(AutoModelForDepthEstimation, head_doc="depth estimation")
1851
+
1852
+
1853
+ class AutoModelForVideoClassification(_BaseAutoModelClass):
1854
+ _model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
1855
+
1856
+
1857
+ AutoModelForVideoClassification = auto_class_update(AutoModelForVideoClassification, head_doc="video classification")
1858
+
1859
+
1860
+ class AutoModelForVision2Seq(_BaseAutoModelClass):
1861
+ _model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING
1862
+
1863
+
1864
+ AutoModelForVision2Seq = auto_class_update(AutoModelForVision2Seq, head_doc="vision-to-text modeling")
1865
+
1866
+
1867
+ class AutoModelForImageTextToText(_BaseAutoModelClass):
1868
+ _model_mapping = MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING
1869
+
1870
+
1871
+ AutoModelForImageTextToText = auto_class_update(AutoModelForImageTextToText, head_doc="image-text-to-text modeling")
1872
+
1873
+
1874
+ class AutoModelForAudioClassification(_BaseAutoModelClass):
1875
+ _model_mapping = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
1876
+
1877
+
1878
+ AutoModelForAudioClassification = auto_class_update(AutoModelForAudioClassification, head_doc="audio classification")
1879
+
1880
+
1881
+ class AutoModelForCTC(_BaseAutoModelClass):
1882
+ _model_mapping = MODEL_FOR_CTC_MAPPING
1883
+
1884
+
1885
+ AutoModelForCTC = auto_class_update(AutoModelForCTC, head_doc="connectionist temporal classification")
1886
+
1887
+
1888
+ class AutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
1889
+ _model_mapping = MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
1890
+
1891
+
1892
+ AutoModelForSpeechSeq2Seq = auto_class_update(
1893
+ AutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
1894
+ )
1895
+
1896
+
1897
+ class AutoModelForAudioFrameClassification(_BaseAutoModelClass):
1898
+ _model_mapping = MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING
1899
+
1900
+
1901
+ AutoModelForAudioFrameClassification = auto_class_update(
1902
+ AutoModelForAudioFrameClassification, head_doc="audio frame (token) classification"
1903
+ )
1904
+
1905
+
1906
+ class AutoModelForAudioXVector(_BaseAutoModelClass):
1907
+ _model_mapping = MODEL_FOR_AUDIO_XVECTOR_MAPPING
1908
+
1909
+
1910
+ class AutoModelForTextToSpectrogram(_BaseAutoModelClass):
1911
+ _model_mapping = MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING
1912
+
1913
+
1914
+ class AutoModelForTextToWaveform(_BaseAutoModelClass):
1915
+ _model_mapping = MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING
1916
+
1917
+
1918
+ class AutoBackbone(_BaseAutoBackboneClass):
1919
+ _model_mapping = MODEL_FOR_BACKBONE_MAPPING
1920
+
1921
+
1922
+ AutoModelForAudioXVector = auto_class_update(AutoModelForAudioXVector, head_doc="audio retrieval via x-vector")
1923
+
1924
+
1925
+ class AutoModelForMaskedImageModeling(_BaseAutoModelClass):
1926
+ _model_mapping = MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING
1927
+
1928
+
1929
+ AutoModelForMaskedImageModeling = auto_class_update(AutoModelForMaskedImageModeling, head_doc="masked image modeling")
1930
+
1931
+
1932
+ class AutoModelWithLMHead(_AutoModelWithLMHead):
1933
+ @classmethod
1934
+ def from_config(cls, config):
1935
+ warnings.warn(
1936
+ "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
1937
+ "`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and "
1938
+ "`AutoModelForSeq2SeqLM` for encoder-decoder models.",
1939
+ FutureWarning,
1940
+ )
1941
+ return super().from_config(config)
1942
+
1943
+ @classmethod
1944
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
1945
+ warnings.warn(
1946
+ "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
1947
+ "`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and "
1948
+ "`AutoModelForSeq2SeqLM` for encoder-decoder models.",
1949
+ FutureWarning,
1950
+ )
1951
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
lib/python3.12/site-packages/transformers/models/auto/modeling_flax_auto.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google Flax Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Auto Model class."""
16
+
17
+ from collections import OrderedDict
18
+
19
+ from ...utils import logging
20
+ from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
21
+ from .configuration_auto import CONFIG_MAPPING_NAMES
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ FLAX_MODEL_MAPPING_NAMES = OrderedDict(
28
+ [
29
+ # Base model mapping
30
+ ("albert", "FlaxAlbertModel"),
31
+ ("bart", "FlaxBartModel"),
32
+ ("beit", "FlaxBeitModel"),
33
+ ("bert", "FlaxBertModel"),
34
+ ("big_bird", "FlaxBigBirdModel"),
35
+ ("blenderbot", "FlaxBlenderbotModel"),
36
+ ("blenderbot-small", "FlaxBlenderbotSmallModel"),
37
+ ("bloom", "FlaxBloomModel"),
38
+ ("clip", "FlaxCLIPModel"),
39
+ ("dinov2", "FlaxDinov2Model"),
40
+ ("distilbert", "FlaxDistilBertModel"),
41
+ ("electra", "FlaxElectraModel"),
42
+ ("gemma", "FlaxGemmaModel"),
43
+ ("gpt-sw3", "FlaxGPT2Model"),
44
+ ("gpt2", "FlaxGPT2Model"),
45
+ ("gpt_neo", "FlaxGPTNeoModel"),
46
+ ("gptj", "FlaxGPTJModel"),
47
+ ("llama", "FlaxLlamaModel"),
48
+ ("longt5", "FlaxLongT5Model"),
49
+ ("marian", "FlaxMarianModel"),
50
+ ("mbart", "FlaxMBartModel"),
51
+ ("mistral", "FlaxMistralModel"),
52
+ ("mt5", "FlaxMT5Model"),
53
+ ("opt", "FlaxOPTModel"),
54
+ ("pegasus", "FlaxPegasusModel"),
55
+ ("regnet", "FlaxRegNetModel"),
56
+ ("resnet", "FlaxResNetModel"),
57
+ ("roberta", "FlaxRobertaModel"),
58
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"),
59
+ ("roformer", "FlaxRoFormerModel"),
60
+ ("t5", "FlaxT5Model"),
61
+ ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"),
62
+ ("vit", "FlaxViTModel"),
63
+ ("wav2vec2", "FlaxWav2Vec2Model"),
64
+ ("whisper", "FlaxWhisperModel"),
65
+ ("xglm", "FlaxXGLMModel"),
66
+ ("xlm-roberta", "FlaxXLMRobertaModel"),
67
+ ]
68
+ )
69
+
70
+ FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
71
+ [
72
+ # Model for pre-training mapping
73
+ ("albert", "FlaxAlbertForPreTraining"),
74
+ ("bart", "FlaxBartForConditionalGeneration"),
75
+ ("bert", "FlaxBertForPreTraining"),
76
+ ("big_bird", "FlaxBigBirdForPreTraining"),
77
+ ("electra", "FlaxElectraForPreTraining"),
78
+ ("longt5", "FlaxLongT5ForConditionalGeneration"),
79
+ ("mbart", "FlaxMBartForConditionalGeneration"),
80
+ ("mt5", "FlaxMT5ForConditionalGeneration"),
81
+ ("roberta", "FlaxRobertaForMaskedLM"),
82
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
83
+ ("roformer", "FlaxRoFormerForMaskedLM"),
84
+ ("t5", "FlaxT5ForConditionalGeneration"),
85
+ ("wav2vec2", "FlaxWav2Vec2ForPreTraining"),
86
+ ("whisper", "FlaxWhisperForConditionalGeneration"),
87
+ ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
88
+ ]
89
+ )
90
+
91
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
92
+ [
93
+ # Model for Masked LM mapping
94
+ ("albert", "FlaxAlbertForMaskedLM"),
95
+ ("bart", "FlaxBartForConditionalGeneration"),
96
+ ("bert", "FlaxBertForMaskedLM"),
97
+ ("big_bird", "FlaxBigBirdForMaskedLM"),
98
+ ("distilbert", "FlaxDistilBertForMaskedLM"),
99
+ ("electra", "FlaxElectraForMaskedLM"),
100
+ ("mbart", "FlaxMBartForConditionalGeneration"),
101
+ ("roberta", "FlaxRobertaForMaskedLM"),
102
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
103
+ ("roformer", "FlaxRoFormerForMaskedLM"),
104
+ ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
105
+ ]
106
+ )
107
+
108
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
109
+ [
110
+ # Model for Seq2Seq Causal LM mapping
111
+ ("bart", "FlaxBartForConditionalGeneration"),
112
+ ("blenderbot", "FlaxBlenderbotForConditionalGeneration"),
113
+ ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"),
114
+ ("encoder-decoder", "FlaxEncoderDecoderModel"),
115
+ ("longt5", "FlaxLongT5ForConditionalGeneration"),
116
+ ("marian", "FlaxMarianMTModel"),
117
+ ("mbart", "FlaxMBartForConditionalGeneration"),
118
+ ("mt5", "FlaxMT5ForConditionalGeneration"),
119
+ ("pegasus", "FlaxPegasusForConditionalGeneration"),
120
+ ("t5", "FlaxT5ForConditionalGeneration"),
121
+ ]
122
+ )
123
+
124
+ FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
125
+ [
126
+ # Model for Image-classification
127
+ ("beit", "FlaxBeitForImageClassification"),
128
+ ("dinov2", "FlaxDinov2ForImageClassification"),
129
+ ("regnet", "FlaxRegNetForImageClassification"),
130
+ ("resnet", "FlaxResNetForImageClassification"),
131
+ ("vit", "FlaxViTForImageClassification"),
132
+ ]
133
+ )
134
+
135
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
136
+ [
137
+ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"),
138
+ ]
139
+ )
140
+
141
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
142
+ [
143
+ # Model for Causal LM mapping
144
+ ("bart", "FlaxBartForCausalLM"),
145
+ ("bert", "FlaxBertForCausalLM"),
146
+ ("big_bird", "FlaxBigBirdForCausalLM"),
147
+ ("bloom", "FlaxBloomForCausalLM"),
148
+ ("electra", "FlaxElectraForCausalLM"),
149
+ ("gemma", "FlaxGemmaForCausalLM"),
150
+ ("gpt-sw3", "FlaxGPT2LMHeadModel"),
151
+ ("gpt2", "FlaxGPT2LMHeadModel"),
152
+ ("gpt_neo", "FlaxGPTNeoForCausalLM"),
153
+ ("gptj", "FlaxGPTJForCausalLM"),
154
+ ("llama", "FlaxLlamaForCausalLM"),
155
+ ("mistral", "FlaxMistralForCausalLM"),
156
+ ("opt", "FlaxOPTForCausalLM"),
157
+ ("roberta", "FlaxRobertaForCausalLM"),
158
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"),
159
+ ("xglm", "FlaxXGLMForCausalLM"),
160
+ ("xlm-roberta", "FlaxXLMRobertaForCausalLM"),
161
+ ]
162
+ )
163
+
164
+ FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
165
+ [
166
+ # Model for Sequence Classification mapping
167
+ ("albert", "FlaxAlbertForSequenceClassification"),
168
+ ("bart", "FlaxBartForSequenceClassification"),
169
+ ("bert", "FlaxBertForSequenceClassification"),
170
+ ("big_bird", "FlaxBigBirdForSequenceClassification"),
171
+ ("distilbert", "FlaxDistilBertForSequenceClassification"),
172
+ ("electra", "FlaxElectraForSequenceClassification"),
173
+ ("mbart", "FlaxMBartForSequenceClassification"),
174
+ ("roberta", "FlaxRobertaForSequenceClassification"),
175
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"),
176
+ ("roformer", "FlaxRoFormerForSequenceClassification"),
177
+ ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"),
178
+ ]
179
+ )
180
+
181
+ FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
182
+ [
183
+ # Model for Question Answering mapping
184
+ ("albert", "FlaxAlbertForQuestionAnswering"),
185
+ ("bart", "FlaxBartForQuestionAnswering"),
186
+ ("bert", "FlaxBertForQuestionAnswering"),
187
+ ("big_bird", "FlaxBigBirdForQuestionAnswering"),
188
+ ("distilbert", "FlaxDistilBertForQuestionAnswering"),
189
+ ("electra", "FlaxElectraForQuestionAnswering"),
190
+ ("mbart", "FlaxMBartForQuestionAnswering"),
191
+ ("roberta", "FlaxRobertaForQuestionAnswering"),
192
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"),
193
+ ("roformer", "FlaxRoFormerForQuestionAnswering"),
194
+ ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"),
195
+ ]
196
+ )
197
+
198
+ FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
199
+ [
200
+ # Model for Token Classification mapping
201
+ ("albert", "FlaxAlbertForTokenClassification"),
202
+ ("bert", "FlaxBertForTokenClassification"),
203
+ ("big_bird", "FlaxBigBirdForTokenClassification"),
204
+ ("distilbert", "FlaxDistilBertForTokenClassification"),
205
+ ("electra", "FlaxElectraForTokenClassification"),
206
+ ("roberta", "FlaxRobertaForTokenClassification"),
207
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"),
208
+ ("roformer", "FlaxRoFormerForTokenClassification"),
209
+ ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"),
210
+ ]
211
+ )
212
+
213
+ FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
214
+ [
215
+ # Model for Multiple Choice mapping
216
+ ("albert", "FlaxAlbertForMultipleChoice"),
217
+ ("bert", "FlaxBertForMultipleChoice"),
218
+ ("big_bird", "FlaxBigBirdForMultipleChoice"),
219
+ ("distilbert", "FlaxDistilBertForMultipleChoice"),
220
+ ("electra", "FlaxElectraForMultipleChoice"),
221
+ ("roberta", "FlaxRobertaForMultipleChoice"),
222
+ ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"),
223
+ ("roformer", "FlaxRoFormerForMultipleChoice"),
224
+ ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"),
225
+ ]
226
+ )
227
+
228
+ FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
229
+ [
230
+ ("bert", "FlaxBertForNextSentencePrediction"),
231
+ ]
232
+ )
233
+
234
+ FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
235
+ [
236
+ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"),
237
+ ("whisper", "FlaxWhisperForConditionalGeneration"),
238
+ ]
239
+ )
240
+
241
+ FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
242
+ [
243
+ ("whisper", "FlaxWhisperForAudioClassification"),
244
+ ]
245
+ )
246
+
247
+ FLAX_MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
248
+ FLAX_MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
249
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
250
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
251
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
252
+ )
253
+ FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
254
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
255
+ )
256
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
257
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
258
+ FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
259
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
260
+ )
261
+ FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
262
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
263
+ )
264
+ FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
265
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
266
+ )
267
+ FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(
268
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
269
+ )
270
+ FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
271
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
272
+ )
273
+ FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(
274
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
275
+ )
276
+ FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
277
+ CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
278
+ )
279
+
280
+
281
+ class FlaxAutoModel(_BaseAutoModelClass):
282
+ _model_mapping = FLAX_MODEL_MAPPING
283
+
284
+
285
+ FlaxAutoModel = auto_class_update(FlaxAutoModel)
286
+
287
+
288
+ class FlaxAutoModelForPreTraining(_BaseAutoModelClass):
289
+ _model_mapping = FLAX_MODEL_FOR_PRETRAINING_MAPPING
290
+
291
+
292
+ FlaxAutoModelForPreTraining = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining")
293
+
294
+
295
+ class FlaxAutoModelForCausalLM(_BaseAutoModelClass):
296
+ _model_mapping = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
297
+
298
+
299
+ FlaxAutoModelForCausalLM = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling")
300
+
301
+
302
+ class FlaxAutoModelForMaskedLM(_BaseAutoModelClass):
303
+ _model_mapping = FLAX_MODEL_FOR_MASKED_LM_MAPPING
304
+
305
+
306
+ FlaxAutoModelForMaskedLM = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling")
307
+
308
+
309
+ class FlaxAutoModelForSeq2SeqLM(_BaseAutoModelClass):
310
+ _model_mapping = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
311
+
312
+
313
+ FlaxAutoModelForSeq2SeqLM = auto_class_update(
314
+ FlaxAutoModelForSeq2SeqLM,
315
+ head_doc="sequence-to-sequence language modeling",
316
+ checkpoint_for_example="google-t5/t5-base",
317
+ )
318
+
319
+
320
+ class FlaxAutoModelForSequenceClassification(_BaseAutoModelClass):
321
+ _model_mapping = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
322
+
323
+
324
+ FlaxAutoModelForSequenceClassification = auto_class_update(
325
+ FlaxAutoModelForSequenceClassification, head_doc="sequence classification"
326
+ )
327
+
328
+
329
+ class FlaxAutoModelForQuestionAnswering(_BaseAutoModelClass):
330
+ _model_mapping = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
331
+
332
+
333
+ FlaxAutoModelForQuestionAnswering = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering")
334
+
335
+
336
+ class FlaxAutoModelForTokenClassification(_BaseAutoModelClass):
337
+ _model_mapping = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
338
+
339
+
340
+ FlaxAutoModelForTokenClassification = auto_class_update(
341
+ FlaxAutoModelForTokenClassification, head_doc="token classification"
342
+ )
343
+
344
+
345
+ class FlaxAutoModelForMultipleChoice(_BaseAutoModelClass):
346
+ _model_mapping = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
347
+
348
+
349
+ FlaxAutoModelForMultipleChoice = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice")
350
+
351
+
352
+ class FlaxAutoModelForNextSentencePrediction(_BaseAutoModelClass):
353
+ _model_mapping = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
354
+
355
+
356
+ FlaxAutoModelForNextSentencePrediction = auto_class_update(
357
+ FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
358
+ )
359
+
360
+
361
+ class FlaxAutoModelForImageClassification(_BaseAutoModelClass):
362
+ _model_mapping = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
363
+
364
+
365
+ FlaxAutoModelForImageClassification = auto_class_update(
366
+ FlaxAutoModelForImageClassification, head_doc="image classification"
367
+ )
368
+
369
+
370
+ class FlaxAutoModelForVision2Seq(_BaseAutoModelClass):
371
+ _model_mapping = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
372
+
373
+
374
+ FlaxAutoModelForVision2Seq = auto_class_update(FlaxAutoModelForVision2Seq, head_doc="vision-to-text modeling")
375
+
376
+
377
+ class FlaxAutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
378
+ _model_mapping = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
379
+
380
+
381
+ FlaxAutoModelForSpeechSeq2Seq = auto_class_update(
382
+ FlaxAutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
383
+ )
lib/python3.12/site-packages/transformers/models/auto/modeling_tf_auto.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Auto Model class."""
16
+
17
+ import warnings
18
+ from collections import OrderedDict
19
+
20
+ from ...utils import logging
21
+ from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
22
+ from .configuration_auto import CONFIG_MAPPING_NAMES
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ TF_MODEL_MAPPING_NAMES = OrderedDict(
29
+ [
30
+ # Base model mapping
31
+ ("albert", "TFAlbertModel"),
32
+ ("bart", "TFBartModel"),
33
+ ("bert", "TFBertModel"),
34
+ ("blenderbot", "TFBlenderbotModel"),
35
+ ("blenderbot-small", "TFBlenderbotSmallModel"),
36
+ ("blip", "TFBlipModel"),
37
+ ("camembert", "TFCamembertModel"),
38
+ ("clip", "TFCLIPModel"),
39
+ ("convbert", "TFConvBertModel"),
40
+ ("convnext", "TFConvNextModel"),
41
+ ("convnextv2", "TFConvNextV2Model"),
42
+ ("ctrl", "TFCTRLModel"),
43
+ ("cvt", "TFCvtModel"),
44
+ ("data2vec-vision", "TFData2VecVisionModel"),
45
+ ("deberta", "TFDebertaModel"),
46
+ ("deberta-v2", "TFDebertaV2Model"),
47
+ ("deit", "TFDeiTModel"),
48
+ ("distilbert", "TFDistilBertModel"),
49
+ ("dpr", "TFDPRQuestionEncoder"),
50
+ ("efficientformer", "TFEfficientFormerModel"),
51
+ ("electra", "TFElectraModel"),
52
+ ("esm", "TFEsmModel"),
53
+ ("flaubert", "TFFlaubertModel"),
54
+ ("funnel", ("TFFunnelModel", "TFFunnelBaseModel")),
55
+ ("gpt-sw3", "TFGPT2Model"),
56
+ ("gpt2", "TFGPT2Model"),
57
+ ("gptj", "TFGPTJModel"),
58
+ ("groupvit", "TFGroupViTModel"),
59
+ ("hubert", "TFHubertModel"),
60
+ ("idefics", "TFIdeficsModel"),
61
+ ("layoutlm", "TFLayoutLMModel"),
62
+ ("layoutlmv3", "TFLayoutLMv3Model"),
63
+ ("led", "TFLEDModel"),
64
+ ("longformer", "TFLongformerModel"),
65
+ ("lxmert", "TFLxmertModel"),
66
+ ("marian", "TFMarianModel"),
67
+ ("mbart", "TFMBartModel"),
68
+ ("mistral", "TFMistralModel"),
69
+ ("mobilebert", "TFMobileBertModel"),
70
+ ("mobilevit", "TFMobileViTModel"),
71
+ ("mpnet", "TFMPNetModel"),
72
+ ("mt5", "TFMT5Model"),
73
+ ("openai-gpt", "TFOpenAIGPTModel"),
74
+ ("opt", "TFOPTModel"),
75
+ ("pegasus", "TFPegasusModel"),
76
+ ("regnet", "TFRegNetModel"),
77
+ ("rembert", "TFRemBertModel"),
78
+ ("resnet", "TFResNetModel"),
79
+ ("roberta", "TFRobertaModel"),
80
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormModel"),
81
+ ("roformer", "TFRoFormerModel"),
82
+ ("sam", "TFSamModel"),
83
+ ("sam_vision_model", "TFSamVisionModel"),
84
+ ("segformer", "TFSegformerModel"),
85
+ ("speech_to_text", "TFSpeech2TextModel"),
86
+ ("swiftformer", "TFSwiftFormerModel"),
87
+ ("swin", "TFSwinModel"),
88
+ ("t5", "TFT5Model"),
89
+ ("tapas", "TFTapasModel"),
90
+ ("transfo-xl", "TFTransfoXLModel"),
91
+ ("vision-text-dual-encoder", "TFVisionTextDualEncoderModel"),
92
+ ("vit", "TFViTModel"),
93
+ ("vit_mae", "TFViTMAEModel"),
94
+ ("wav2vec2", "TFWav2Vec2Model"),
95
+ ("whisper", "TFWhisperModel"),
96
+ ("xglm", "TFXGLMModel"),
97
+ ("xlm", "TFXLMModel"),
98
+ ("xlm-roberta", "TFXLMRobertaModel"),
99
+ ("xlnet", "TFXLNetModel"),
100
+ ]
101
+ )
102
+
103
+ TF_MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
104
+ [
105
+ # Model for pre-training mapping
106
+ ("albert", "TFAlbertForPreTraining"),
107
+ ("bart", "TFBartForConditionalGeneration"),
108
+ ("bert", "TFBertForPreTraining"),
109
+ ("camembert", "TFCamembertForMaskedLM"),
110
+ ("ctrl", "TFCTRLLMHeadModel"),
111
+ ("distilbert", "TFDistilBertForMaskedLM"),
112
+ ("electra", "TFElectraForPreTraining"),
113
+ ("flaubert", "TFFlaubertWithLMHeadModel"),
114
+ ("funnel", "TFFunnelForPreTraining"),
115
+ ("gpt-sw3", "TFGPT2LMHeadModel"),
116
+ ("gpt2", "TFGPT2LMHeadModel"),
117
+ ("idefics", "TFIdeficsForVisionText2Text"),
118
+ ("layoutlm", "TFLayoutLMForMaskedLM"),
119
+ ("lxmert", "TFLxmertForPreTraining"),
120
+ ("mobilebert", "TFMobileBertForPreTraining"),
121
+ ("mpnet", "TFMPNetForMaskedLM"),
122
+ ("openai-gpt", "TFOpenAIGPTLMHeadModel"),
123
+ ("roberta", "TFRobertaForMaskedLM"),
124
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForMaskedLM"),
125
+ ("t5", "TFT5ForConditionalGeneration"),
126
+ ("tapas", "TFTapasForMaskedLM"),
127
+ ("transfo-xl", "TFTransfoXLLMHeadModel"),
128
+ ("vit_mae", "TFViTMAEForPreTraining"),
129
+ ("xlm", "TFXLMWithLMHeadModel"),
130
+ ("xlm-roberta", "TFXLMRobertaForMaskedLM"),
131
+ ("xlnet", "TFXLNetLMHeadModel"),
132
+ ]
133
+ )
134
+
135
+ TF_MODEL_WITH_LM_HEAD_MAPPING_NAMES = OrderedDict(
136
+ [
137
+ # Model with LM heads mapping
138
+ ("albert", "TFAlbertForMaskedLM"),
139
+ ("bart", "TFBartForConditionalGeneration"),
140
+ ("bert", "TFBertForMaskedLM"),
141
+ ("camembert", "TFCamembertForMaskedLM"),
142
+ ("convbert", "TFConvBertForMaskedLM"),
143
+ ("ctrl", "TFCTRLLMHeadModel"),
144
+ ("distilbert", "TFDistilBertForMaskedLM"),
145
+ ("electra", "TFElectraForMaskedLM"),
146
+ ("esm", "TFEsmForMaskedLM"),
147
+ ("flaubert", "TFFlaubertWithLMHeadModel"),
148
+ ("funnel", "TFFunnelForMaskedLM"),
149
+ ("gpt-sw3", "TFGPT2LMHeadModel"),
150
+ ("gpt2", "TFGPT2LMHeadModel"),
151
+ ("gptj", "TFGPTJForCausalLM"),
152
+ ("layoutlm", "TFLayoutLMForMaskedLM"),
153
+ ("led", "TFLEDForConditionalGeneration"),
154
+ ("longformer", "TFLongformerForMaskedLM"),
155
+ ("marian", "TFMarianMTModel"),
156
+ ("mobilebert", "TFMobileBertForMaskedLM"),
157
+ ("mpnet", "TFMPNetForMaskedLM"),
158
+ ("openai-gpt", "TFOpenAIGPTLMHeadModel"),
159
+ ("rembert", "TFRemBertForMaskedLM"),
160
+ ("roberta", "TFRobertaForMaskedLM"),
161
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForMaskedLM"),
162
+ ("roformer", "TFRoFormerForMaskedLM"),
163
+ ("speech_to_text", "TFSpeech2TextForConditionalGeneration"),
164
+ ("t5", "TFT5ForConditionalGeneration"),
165
+ ("tapas", "TFTapasForMaskedLM"),
166
+ ("transfo-xl", "TFTransfoXLLMHeadModel"),
167
+ ("whisper", "TFWhisperForConditionalGeneration"),
168
+ ("xlm", "TFXLMWithLMHeadModel"),
169
+ ("xlm-roberta", "TFXLMRobertaForMaskedLM"),
170
+ ("xlnet", "TFXLNetLMHeadModel"),
171
+ ]
172
+ )
173
+
174
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
175
+ [
176
+ # Model for Causal LM mapping
177
+ ("bert", "TFBertLMHeadModel"),
178
+ ("camembert", "TFCamembertForCausalLM"),
179
+ ("ctrl", "TFCTRLLMHeadModel"),
180
+ ("gpt-sw3", "TFGPT2LMHeadModel"),
181
+ ("gpt2", "TFGPT2LMHeadModel"),
182
+ ("gptj", "TFGPTJForCausalLM"),
183
+ ("mistral", "TFMistralForCausalLM"),
184
+ ("openai-gpt", "TFOpenAIGPTLMHeadModel"),
185
+ ("opt", "TFOPTForCausalLM"),
186
+ ("rembert", "TFRemBertForCausalLM"),
187
+ ("roberta", "TFRobertaForCausalLM"),
188
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForCausalLM"),
189
+ ("roformer", "TFRoFormerForCausalLM"),
190
+ ("transfo-xl", "TFTransfoXLLMHeadModel"),
191
+ ("xglm", "TFXGLMForCausalLM"),
192
+ ("xlm", "TFXLMWithLMHeadModel"),
193
+ ("xlm-roberta", "TFXLMRobertaForCausalLM"),
194
+ ("xlnet", "TFXLNetLMHeadModel"),
195
+ ]
196
+ )
197
+
198
+ TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
199
+ [
200
+ ("deit", "TFDeiTForMaskedImageModeling"),
201
+ ("swin", "TFSwinForMaskedImageModeling"),
202
+ ]
203
+ )
204
+
205
+ TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
206
+ [
207
+ # Model for Image-classsification
208
+ ("convnext", "TFConvNextForImageClassification"),
209
+ ("convnextv2", "TFConvNextV2ForImageClassification"),
210
+ ("cvt", "TFCvtForImageClassification"),
211
+ ("data2vec-vision", "TFData2VecVisionForImageClassification"),
212
+ ("deit", ("TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher")),
213
+ (
214
+ "efficientformer",
215
+ ("TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher"),
216
+ ),
217
+ ("mobilevit", "TFMobileViTForImageClassification"),
218
+ ("regnet", "TFRegNetForImageClassification"),
219
+ ("resnet", "TFResNetForImageClassification"),
220
+ ("segformer", "TFSegformerForImageClassification"),
221
+ ("swiftformer", "TFSwiftFormerForImageClassification"),
222
+ ("swin", "TFSwinForImageClassification"),
223
+ ("vit", "TFViTForImageClassification"),
224
+ ]
225
+ )
226
+
227
+
228
+ TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
229
+ [
230
+ # Model for Zero Shot Image Classification mapping
231
+ ("blip", "TFBlipModel"),
232
+ ("clip", "TFCLIPModel"),
233
+ ]
234
+ )
235
+
236
+
237
+ TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = OrderedDict(
238
+ [
239
+ # Model for Semantic Segmentation mapping
240
+ ("data2vec-vision", "TFData2VecVisionForSemanticSegmentation"),
241
+ ("mobilevit", "TFMobileViTForSemanticSegmentation"),
242
+ ("segformer", "TFSegformerForSemanticSegmentation"),
243
+ ]
244
+ )
245
+
246
+ TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
247
+ [
248
+ ("blip", "TFBlipForConditionalGeneration"),
249
+ ("vision-encoder-decoder", "TFVisionEncoderDecoderModel"),
250
+ ]
251
+ )
252
+
253
+ TF_MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
254
+ [
255
+ # Model for Masked LM mapping
256
+ ("albert", "TFAlbertForMaskedLM"),
257
+ ("bert", "TFBertForMaskedLM"),
258
+ ("camembert", "TFCamembertForMaskedLM"),
259
+ ("convbert", "TFConvBertForMaskedLM"),
260
+ ("deberta", "TFDebertaForMaskedLM"),
261
+ ("deberta-v2", "TFDebertaV2ForMaskedLM"),
262
+ ("distilbert", "TFDistilBertForMaskedLM"),
263
+ ("electra", "TFElectraForMaskedLM"),
264
+ ("esm", "TFEsmForMaskedLM"),
265
+ ("flaubert", "TFFlaubertWithLMHeadModel"),
266
+ ("funnel", "TFFunnelForMaskedLM"),
267
+ ("layoutlm", "TFLayoutLMForMaskedLM"),
268
+ ("longformer", "TFLongformerForMaskedLM"),
269
+ ("mobilebert", "TFMobileBertForMaskedLM"),
270
+ ("mpnet", "TFMPNetForMaskedLM"),
271
+ ("rembert", "TFRemBertForMaskedLM"),
272
+ ("roberta", "TFRobertaForMaskedLM"),
273
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForMaskedLM"),
274
+ ("roformer", "TFRoFormerForMaskedLM"),
275
+ ("tapas", "TFTapasForMaskedLM"),
276
+ ("xlm", "TFXLMWithLMHeadModel"),
277
+ ("xlm-roberta", "TFXLMRobertaForMaskedLM"),
278
+ ]
279
+ )
280
+
281
+ TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
282
+ [
283
+ # Model for Seq2Seq Causal LM mapping
284
+ ("bart", "TFBartForConditionalGeneration"),
285
+ ("blenderbot", "TFBlenderbotForConditionalGeneration"),
286
+ ("blenderbot-small", "TFBlenderbotSmallForConditionalGeneration"),
287
+ ("encoder-decoder", "TFEncoderDecoderModel"),
288
+ ("led", "TFLEDForConditionalGeneration"),
289
+ ("marian", "TFMarianMTModel"),
290
+ ("mbart", "TFMBartForConditionalGeneration"),
291
+ ("mt5", "TFMT5ForConditionalGeneration"),
292
+ ("pegasus", "TFPegasusForConditionalGeneration"),
293
+ ("t5", "TFT5ForConditionalGeneration"),
294
+ ]
295
+ )
296
+
297
+ TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
298
+ [
299
+ ("speech_to_text", "TFSpeech2TextForConditionalGeneration"),
300
+ ("whisper", "TFWhisperForConditionalGeneration"),
301
+ ]
302
+ )
303
+
304
+ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
305
+ [
306
+ # Model for Sequence Classification mapping
307
+ ("albert", "TFAlbertForSequenceClassification"),
308
+ ("bart", "TFBartForSequenceClassification"),
309
+ ("bert", "TFBertForSequenceClassification"),
310
+ ("camembert", "TFCamembertForSequenceClassification"),
311
+ ("convbert", "TFConvBertForSequenceClassification"),
312
+ ("ctrl", "TFCTRLForSequenceClassification"),
313
+ ("deberta", "TFDebertaForSequenceClassification"),
314
+ ("deberta-v2", "TFDebertaV2ForSequenceClassification"),
315
+ ("distilbert", "TFDistilBertForSequenceClassification"),
316
+ ("electra", "TFElectraForSequenceClassification"),
317
+ ("esm", "TFEsmForSequenceClassification"),
318
+ ("flaubert", "TFFlaubertForSequenceClassification"),
319
+ ("funnel", "TFFunnelForSequenceClassification"),
320
+ ("gpt-sw3", "TFGPT2ForSequenceClassification"),
321
+ ("gpt2", "TFGPT2ForSequenceClassification"),
322
+ ("gptj", "TFGPTJForSequenceClassification"),
323
+ ("layoutlm", "TFLayoutLMForSequenceClassification"),
324
+ ("layoutlmv3", "TFLayoutLMv3ForSequenceClassification"),
325
+ ("longformer", "TFLongformerForSequenceClassification"),
326
+ ("mistral", "TFMistralForSequenceClassification"),
327
+ ("mobilebert", "TFMobileBertForSequenceClassification"),
328
+ ("mpnet", "TFMPNetForSequenceClassification"),
329
+ ("openai-gpt", "TFOpenAIGPTForSequenceClassification"),
330
+ ("rembert", "TFRemBertForSequenceClassification"),
331
+ ("roberta", "TFRobertaForSequenceClassification"),
332
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForSequenceClassification"),
333
+ ("roformer", "TFRoFormerForSequenceClassification"),
334
+ ("tapas", "TFTapasForSequenceClassification"),
335
+ ("transfo-xl", "TFTransfoXLForSequenceClassification"),
336
+ ("xlm", "TFXLMForSequenceClassification"),
337
+ ("xlm-roberta", "TFXLMRobertaForSequenceClassification"),
338
+ ("xlnet", "TFXLNetForSequenceClassification"),
339
+ ]
340
+ )
341
+
342
+ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
343
+ [
344
+ # Model for Question Answering mapping
345
+ ("albert", "TFAlbertForQuestionAnswering"),
346
+ ("bert", "TFBertForQuestionAnswering"),
347
+ ("camembert", "TFCamembertForQuestionAnswering"),
348
+ ("convbert", "TFConvBertForQuestionAnswering"),
349
+ ("deberta", "TFDebertaForQuestionAnswering"),
350
+ ("deberta-v2", "TFDebertaV2ForQuestionAnswering"),
351
+ ("distilbert", "TFDistilBertForQuestionAnswering"),
352
+ ("electra", "TFElectraForQuestionAnswering"),
353
+ ("flaubert", "TFFlaubertForQuestionAnsweringSimple"),
354
+ ("funnel", "TFFunnelForQuestionAnswering"),
355
+ ("gptj", "TFGPTJForQuestionAnswering"),
356
+ ("layoutlmv3", "TFLayoutLMv3ForQuestionAnswering"),
357
+ ("longformer", "TFLongformerForQuestionAnswering"),
358
+ ("mobilebert", "TFMobileBertForQuestionAnswering"),
359
+ ("mpnet", "TFMPNetForQuestionAnswering"),
360
+ ("rembert", "TFRemBertForQuestionAnswering"),
361
+ ("roberta", "TFRobertaForQuestionAnswering"),
362
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForQuestionAnswering"),
363
+ ("roformer", "TFRoFormerForQuestionAnswering"),
364
+ ("xlm", "TFXLMForQuestionAnsweringSimple"),
365
+ ("xlm-roberta", "TFXLMRobertaForQuestionAnswering"),
366
+ ("xlnet", "TFXLNetForQuestionAnsweringSimple"),
367
+ ]
368
+ )
369
+ TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict([("wav2vec2", "TFWav2Vec2ForSequenceClassification")])
370
+
371
+ TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
372
+ [
373
+ ("layoutlm", "TFLayoutLMForQuestionAnswering"),
374
+ ("layoutlmv3", "TFLayoutLMv3ForQuestionAnswering"),
375
+ ]
376
+ )
377
+
378
+
379
+ TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
380
+ [
381
+ # Model for Table Question Answering mapping
382
+ ("tapas", "TFTapasForQuestionAnswering"),
383
+ ]
384
+ )
385
+
386
+ TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
387
+ [
388
+ # Model for Token Classification mapping
389
+ ("albert", "TFAlbertForTokenClassification"),
390
+ ("bert", "TFBertForTokenClassification"),
391
+ ("camembert", "TFCamembertForTokenClassification"),
392
+ ("convbert", "TFConvBertForTokenClassification"),
393
+ ("deberta", "TFDebertaForTokenClassification"),
394
+ ("deberta-v2", "TFDebertaV2ForTokenClassification"),
395
+ ("distilbert", "TFDistilBertForTokenClassification"),
396
+ ("electra", "TFElectraForTokenClassification"),
397
+ ("esm", "TFEsmForTokenClassification"),
398
+ ("flaubert", "TFFlaubertForTokenClassification"),
399
+ ("funnel", "TFFunnelForTokenClassification"),
400
+ ("layoutlm", "TFLayoutLMForTokenClassification"),
401
+ ("layoutlmv3", "TFLayoutLMv3ForTokenClassification"),
402
+ ("longformer", "TFLongformerForTokenClassification"),
403
+ ("mobilebert", "TFMobileBertForTokenClassification"),
404
+ ("mpnet", "TFMPNetForTokenClassification"),
405
+ ("rembert", "TFRemBertForTokenClassification"),
406
+ ("roberta", "TFRobertaForTokenClassification"),
407
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForTokenClassification"),
408
+ ("roformer", "TFRoFormerForTokenClassification"),
409
+ ("xlm", "TFXLMForTokenClassification"),
410
+ ("xlm-roberta", "TFXLMRobertaForTokenClassification"),
411
+ ("xlnet", "TFXLNetForTokenClassification"),
412
+ ]
413
+ )
414
+
415
+ TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
416
+ [
417
+ # Model for Multiple Choice mapping
418
+ ("albert", "TFAlbertForMultipleChoice"),
419
+ ("bert", "TFBertForMultipleChoice"),
420
+ ("camembert", "TFCamembertForMultipleChoice"),
421
+ ("convbert", "TFConvBertForMultipleChoice"),
422
+ ("deberta-v2", "TFDebertaV2ForMultipleChoice"),
423
+ ("distilbert", "TFDistilBertForMultipleChoice"),
424
+ ("electra", "TFElectraForMultipleChoice"),
425
+ ("flaubert", "TFFlaubertForMultipleChoice"),
426
+ ("funnel", "TFFunnelForMultipleChoice"),
427
+ ("longformer", "TFLongformerForMultipleChoice"),
428
+ ("mobilebert", "TFMobileBertForMultipleChoice"),
429
+ ("mpnet", "TFMPNetForMultipleChoice"),
430
+ ("rembert", "TFRemBertForMultipleChoice"),
431
+ ("roberta", "TFRobertaForMultipleChoice"),
432
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormForMultipleChoice"),
433
+ ("roformer", "TFRoFormerForMultipleChoice"),
434
+ ("xlm", "TFXLMForMultipleChoice"),
435
+ ("xlm-roberta", "TFXLMRobertaForMultipleChoice"),
436
+ ("xlnet", "TFXLNetForMultipleChoice"),
437
+ ]
438
+ )
439
+
440
+ TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
441
+ [
442
+ ("bert", "TFBertForNextSentencePrediction"),
443
+ ("mobilebert", "TFMobileBertForNextSentencePrediction"),
444
+ ]
445
+ )
446
+ TF_MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = OrderedDict(
447
+ [
448
+ ("sam", "TFSamModel"),
449
+ ]
450
+ )
451
+ TF_MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES = OrderedDict(
452
+ [
453
+ ("albert", "TFAlbertModel"),
454
+ ("bert", "TFBertModel"),
455
+ ("convbert", "TFConvBertModel"),
456
+ ("deberta", "TFDebertaModel"),
457
+ ("deberta-v2", "TFDebertaV2Model"),
458
+ ("distilbert", "TFDistilBertModel"),
459
+ ("electra", "TFElectraModel"),
460
+ ("flaubert", "TFFlaubertModel"),
461
+ ("longformer", "TFLongformerModel"),
462
+ ("mobilebert", "TFMobileBertModel"),
463
+ ("mt5", "TFMT5EncoderModel"),
464
+ ("rembert", "TFRemBertModel"),
465
+ ("roberta", "TFRobertaModel"),
466
+ ("roberta-prelayernorm", "TFRobertaPreLayerNormModel"),
467
+ ("roformer", "TFRoFormerModel"),
468
+ ("t5", "TFT5EncoderModel"),
469
+ ("xlm", "TFXLMModel"),
470
+ ("xlm-roberta", "TFXLMRobertaModel"),
471
+ ]
472
+ )
473
+
474
+ TF_MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_MAPPING_NAMES)
475
+ TF_MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
476
+ TF_MODEL_WITH_LM_HEAD_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_WITH_LM_HEAD_MAPPING_NAMES)
477
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
478
+ TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
479
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES
480
+ )
481
+ TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
482
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
483
+ )
484
+ TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
485
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
486
+ )
487
+ TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = _LazyAutoMapping(
488
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES
489
+ )
490
+ TF_MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
491
+ TF_MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
492
+ TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
493
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
494
+ )
495
+ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
496
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
497
+ )
498
+ TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(
499
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
500
+ )
501
+ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
502
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
503
+ )
504
+ TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
505
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
506
+ )
507
+ TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
508
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES
509
+ )
510
+ TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
511
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
512
+ )
513
+ TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(
514
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
515
+ )
516
+ TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
517
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
518
+ )
519
+ TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
520
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
521
+ )
522
+
523
+ TF_MODEL_FOR_MASK_GENERATION_MAPPING = _LazyAutoMapping(
524
+ CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MASK_GENERATION_MAPPING_NAMES
525
+ )
526
+
527
+ TF_MODEL_FOR_TEXT_ENCODING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES)
528
+
529
+
530
+ class TFAutoModelForMaskGeneration(_BaseAutoModelClass):
531
+ _model_mapping = TF_MODEL_FOR_MASK_GENERATION_MAPPING
532
+
533
+
534
+ class TFAutoModelForTextEncoding(_BaseAutoModelClass):
535
+ _model_mapping = TF_MODEL_FOR_TEXT_ENCODING_MAPPING
536
+
537
+
538
+ class TFAutoModel(_BaseAutoModelClass):
539
+ _model_mapping = TF_MODEL_MAPPING
540
+
541
+
542
+ TFAutoModel = auto_class_update(TFAutoModel)
543
+
544
+
545
+ class TFAutoModelForAudioClassification(_BaseAutoModelClass):
546
+ _model_mapping = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
547
+
548
+
549
+ TFAutoModelForAudioClassification = auto_class_update(
550
+ TFAutoModelForAudioClassification, head_doc="audio classification"
551
+ )
552
+
553
+
554
+ class TFAutoModelForPreTraining(_BaseAutoModelClass):
555
+ _model_mapping = TF_MODEL_FOR_PRETRAINING_MAPPING
556
+
557
+
558
+ TFAutoModelForPreTraining = auto_class_update(TFAutoModelForPreTraining, head_doc="pretraining")
559
+
560
+
561
+ # Private on purpose, the public class will add the deprecation warnings.
562
+ class _TFAutoModelWithLMHead(_BaseAutoModelClass):
563
+ _model_mapping = TF_MODEL_WITH_LM_HEAD_MAPPING
564
+
565
+
566
+ _TFAutoModelWithLMHead = auto_class_update(_TFAutoModelWithLMHead, head_doc="language modeling")
567
+
568
+
569
+ class TFAutoModelForCausalLM(_BaseAutoModelClass):
570
+ _model_mapping = TF_MODEL_FOR_CAUSAL_LM_MAPPING
571
+
572
+
573
+ TFAutoModelForCausalLM = auto_class_update(TFAutoModelForCausalLM, head_doc="causal language modeling")
574
+
575
+
576
+ class TFAutoModelForMaskedImageModeling(_BaseAutoModelClass):
577
+ _model_mapping = TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING
578
+
579
+
580
+ TFAutoModelForMaskedImageModeling = auto_class_update(
581
+ TFAutoModelForMaskedImageModeling, head_doc="masked image modeling"
582
+ )
583
+
584
+
585
+ class TFAutoModelForImageClassification(_BaseAutoModelClass):
586
+ _model_mapping = TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
587
+
588
+
589
+ TFAutoModelForImageClassification = auto_class_update(
590
+ TFAutoModelForImageClassification, head_doc="image classification"
591
+ )
592
+
593
+
594
+ class TFAutoModelForZeroShotImageClassification(_BaseAutoModelClass):
595
+ _model_mapping = TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
596
+
597
+
598
+ TFAutoModelForZeroShotImageClassification = auto_class_update(
599
+ TFAutoModelForZeroShotImageClassification, head_doc="zero-shot image classification"
600
+ )
601
+
602
+
603
+ class TFAutoModelForSemanticSegmentation(_BaseAutoModelClass):
604
+ _model_mapping = TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
605
+
606
+
607
+ TFAutoModelForSemanticSegmentation = auto_class_update(
608
+ TFAutoModelForSemanticSegmentation, head_doc="semantic segmentation"
609
+ )
610
+
611
+
612
+ class TFAutoModelForVision2Seq(_BaseAutoModelClass):
613
+ _model_mapping = TF_MODEL_FOR_VISION_2_SEQ_MAPPING
614
+
615
+
616
+ TFAutoModelForVision2Seq = auto_class_update(TFAutoModelForVision2Seq, head_doc="vision-to-text modeling")
617
+
618
+
619
+ class TFAutoModelForMaskedLM(_BaseAutoModelClass):
620
+ _model_mapping = TF_MODEL_FOR_MASKED_LM_MAPPING
621
+
622
+
623
+ TFAutoModelForMaskedLM = auto_class_update(TFAutoModelForMaskedLM, head_doc="masked language modeling")
624
+
625
+
626
+ class TFAutoModelForSeq2SeqLM(_BaseAutoModelClass):
627
+ _model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
628
+
629
+
630
+ TFAutoModelForSeq2SeqLM = auto_class_update(
631
+ TFAutoModelForSeq2SeqLM,
632
+ head_doc="sequence-to-sequence language modeling",
633
+ checkpoint_for_example="google-t5/t5-base",
634
+ )
635
+
636
+
637
+ class TFAutoModelForSequenceClassification(_BaseAutoModelClass):
638
+ _model_mapping = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
639
+
640
+
641
+ TFAutoModelForSequenceClassification = auto_class_update(
642
+ TFAutoModelForSequenceClassification, head_doc="sequence classification"
643
+ )
644
+
645
+
646
+ class TFAutoModelForQuestionAnswering(_BaseAutoModelClass):
647
+ _model_mapping = TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING
648
+
649
+
650
+ TFAutoModelForQuestionAnswering = auto_class_update(TFAutoModelForQuestionAnswering, head_doc="question answering")
651
+
652
+
653
+ class TFAutoModelForDocumentQuestionAnswering(_BaseAutoModelClass):
654
+ _model_mapping = TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
655
+
656
+
657
+ TFAutoModelForDocumentQuestionAnswering = auto_class_update(
658
+ TFAutoModelForDocumentQuestionAnswering,
659
+ head_doc="document question answering",
660
+ checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3',
661
+ )
662
+
663
+
664
+ class TFAutoModelForTableQuestionAnswering(_BaseAutoModelClass):
665
+ _model_mapping = TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING
666
+
667
+
668
+ TFAutoModelForTableQuestionAnswering = auto_class_update(
669
+ TFAutoModelForTableQuestionAnswering,
670
+ head_doc="table question answering",
671
+ checkpoint_for_example="google/tapas-base-finetuned-wtq",
672
+ )
673
+
674
+
675
+ class TFAutoModelForTokenClassification(_BaseAutoModelClass):
676
+ _model_mapping = TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
677
+
678
+
679
+ TFAutoModelForTokenClassification = auto_class_update(
680
+ TFAutoModelForTokenClassification, head_doc="token classification"
681
+ )
682
+
683
+
684
+ class TFAutoModelForMultipleChoice(_BaseAutoModelClass):
685
+ _model_mapping = TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
686
+
687
+
688
+ TFAutoModelForMultipleChoice = auto_class_update(TFAutoModelForMultipleChoice, head_doc="multiple choice")
689
+
690
+
691
+ class TFAutoModelForNextSentencePrediction(_BaseAutoModelClass):
692
+ _model_mapping = TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
693
+
694
+
695
+ TFAutoModelForNextSentencePrediction = auto_class_update(
696
+ TFAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
697
+ )
698
+
699
+
700
+ class TFAutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
701
+ _model_mapping = TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
702
+
703
+
704
+ TFAutoModelForSpeechSeq2Seq = auto_class_update(
705
+ TFAutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
706
+ )
707
+
708
+
709
+ class TFAutoModelWithLMHead(_TFAutoModelWithLMHead):
710
+ @classmethod
711
+ def from_config(cls, config):
712
+ warnings.warn(
713
+ "The class `TFAutoModelWithLMHead` is deprecated and will be removed in a future version. Please use"
714
+ " `TFAutoModelForCausalLM` for causal language models, `TFAutoModelForMaskedLM` for masked language models"
715
+ " and `TFAutoModelForSeq2SeqLM` for encoder-decoder models.",
716
+ FutureWarning,
717
+ )
718
+ return super().from_config(config)
719
+
720
+ @classmethod
721
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
722
+ warnings.warn(
723
+ "The class `TFAutoModelWithLMHead` is deprecated and will be removed in a future version. Please use"
724
+ " `TFAutoModelForCausalLM` for causal language models, `TFAutoModelForMaskedLM` for masked language models"
725
+ " and `TFAutoModelForSeq2SeqLM` for encoder-decoder models.",
726
+ FutureWarning,
727
+ )
728
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
lib/python3.12/site-packages/transformers/models/auto/processing_auto.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """AutoProcessor class."""
16
+
17
+ import importlib
18
+ import inspect
19
+ import json
20
+ import os
21
+ import warnings
22
+ from collections import OrderedDict
23
+
24
+ # Build the list of all feature extractors
25
+ from ...configuration_utils import PretrainedConfig
26
+ from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
27
+ from ...feature_extraction_utils import FeatureExtractionMixin
28
+ from ...image_processing_utils import ImageProcessingMixin
29
+ from ...processing_utils import ProcessorMixin
30
+ from ...tokenization_utils import TOKENIZER_CONFIG_FILE
31
+ from ...utils import FEATURE_EXTRACTOR_NAME, PROCESSOR_NAME, cached_file, logging
32
+ from .auto_factory import _LazyAutoMapping
33
+ from .configuration_auto import (
34
+ CONFIG_MAPPING_NAMES,
35
+ AutoConfig,
36
+ model_type_to_module_name,
37
+ replace_list_option_in_docstrings,
38
+ )
39
+ from .feature_extraction_auto import AutoFeatureExtractor
40
+ from .image_processing_auto import AutoImageProcessor
41
+ from .tokenization_auto import AutoTokenizer
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ PROCESSOR_MAPPING_NAMES = OrderedDict(
47
+ [
48
+ ("align", "AlignProcessor"),
49
+ ("altclip", "AltCLIPProcessor"),
50
+ ("aria", "AriaProcessor"),
51
+ ("aya_vision", "AyaVisionProcessor"),
52
+ ("bark", "BarkProcessor"),
53
+ ("blip", "BlipProcessor"),
54
+ ("blip-2", "Blip2Processor"),
55
+ ("bridgetower", "BridgeTowerProcessor"),
56
+ ("chameleon", "ChameleonProcessor"),
57
+ ("chinese_clip", "ChineseCLIPProcessor"),
58
+ ("clap", "ClapProcessor"),
59
+ ("clip", "CLIPProcessor"),
60
+ ("clipseg", "CLIPSegProcessor"),
61
+ ("clvp", "ClvpProcessor"),
62
+ ("colpali", "ColPaliProcessor"),
63
+ ("emu3", "Emu3Processor"),
64
+ ("flava", "FlavaProcessor"),
65
+ ("fuyu", "FuyuProcessor"),
66
+ ("gemma3", "Gemma3Processor"),
67
+ ("git", "GitProcessor"),
68
+ ("got_ocr2", "GotOcr2Processor"),
69
+ ("grounding-dino", "GroundingDinoProcessor"),
70
+ ("groupvit", "CLIPProcessor"),
71
+ ("hubert", "Wav2Vec2Processor"),
72
+ ("idefics", "IdeficsProcessor"),
73
+ ("idefics2", "Idefics2Processor"),
74
+ ("idefics3", "Idefics3Processor"),
75
+ ("instructblip", "InstructBlipProcessor"),
76
+ ("instructblipvideo", "InstructBlipVideoProcessor"),
77
+ ("kosmos-2", "Kosmos2Processor"),
78
+ ("layoutlmv2", "LayoutLMv2Processor"),
79
+ ("layoutlmv3", "LayoutLMv3Processor"),
80
+ ("llama4", "Llama4Processor"),
81
+ ("llava", "LlavaProcessor"),
82
+ ("llava_next", "LlavaNextProcessor"),
83
+ ("llava_next_video", "LlavaNextVideoProcessor"),
84
+ ("llava_onevision", "LlavaOnevisionProcessor"),
85
+ ("markuplm", "MarkupLMProcessor"),
86
+ ("mctct", "MCTCTProcessor"),
87
+ ("mgp-str", "MgpstrProcessor"),
88
+ ("mistral3", "PixtralProcessor"),
89
+ ("mllama", "MllamaProcessor"),
90
+ ("moonshine", "Wav2Vec2Processor"),
91
+ ("oneformer", "OneFormerProcessor"),
92
+ ("owlv2", "Owlv2Processor"),
93
+ ("owlvit", "OwlViTProcessor"),
94
+ ("paligemma", "PaliGemmaProcessor"),
95
+ ("phi4_multimodal", "Phi4MultimodalProcessor"),
96
+ ("pix2struct", "Pix2StructProcessor"),
97
+ ("pixtral", "PixtralProcessor"),
98
+ ("pop2piano", "Pop2PianoProcessor"),
99
+ ("qwen2_5_vl", "Qwen2_5_VLProcessor"),
100
+ ("qwen2_audio", "Qwen2AudioProcessor"),
101
+ ("qwen2_vl", "Qwen2VLProcessor"),
102
+ ("sam", "SamProcessor"),
103
+ ("seamless_m4t", "SeamlessM4TProcessor"),
104
+ ("sew", "Wav2Vec2Processor"),
105
+ ("sew-d", "Wav2Vec2Processor"),
106
+ ("shieldgemma2", "ShieldGemma2Processor"),
107
+ ("siglip", "SiglipProcessor"),
108
+ ("siglip2", "Siglip2Processor"),
109
+ ("speech_to_text", "Speech2TextProcessor"),
110
+ ("speech_to_text_2", "Speech2Text2Processor"),
111
+ ("speecht5", "SpeechT5Processor"),
112
+ ("trocr", "TrOCRProcessor"),
113
+ ("tvlt", "TvltProcessor"),
114
+ ("tvp", "TvpProcessor"),
115
+ ("udop", "UdopProcessor"),
116
+ ("unispeech", "Wav2Vec2Processor"),
117
+ ("unispeech-sat", "Wav2Vec2Processor"),
118
+ ("video_llava", "VideoLlavaProcessor"),
119
+ ("vilt", "ViltProcessor"),
120
+ ("vipllava", "LlavaProcessor"),
121
+ ("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"),
122
+ ("wav2vec2", "Wav2Vec2Processor"),
123
+ ("wav2vec2-bert", "Wav2Vec2Processor"),
124
+ ("wav2vec2-conformer", "Wav2Vec2Processor"),
125
+ ("wavlm", "Wav2Vec2Processor"),
126
+ ("whisper", "WhisperProcessor"),
127
+ ("xclip", "XCLIPProcessor"),
128
+ ]
129
+ )
130
+
131
+ PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)
132
+
133
+
134
+ def processor_class_from_name(class_name: str):
135
+ for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
136
+ if class_name in processors:
137
+ module_name = model_type_to_module_name(module_name)
138
+
139
+ module = importlib.import_module(f".{module_name}", "transformers.models")
140
+ try:
141
+ return getattr(module, class_name)
142
+ except AttributeError:
143
+ continue
144
+
145
+ for processor in PROCESSOR_MAPPING._extra_content.values():
146
+ if getattr(processor, "__name__", None) == class_name:
147
+ return processor
148
+
149
+ # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
150
+ # init and we return the proper dummy to get an appropriate error message.
151
+ main_module = importlib.import_module("transformers")
152
+ if hasattr(main_module, class_name):
153
+ return getattr(main_module, class_name)
154
+
155
+ return None
156
+
157
+
158
+ class AutoProcessor:
159
+ r"""
160
+ This is a generic processor class that will be instantiated as one of the processor classes of the library when
161
+ created with the [`AutoProcessor.from_pretrained`] class method.
162
+
163
+ This class cannot be instantiated directly using `__init__()` (throws an error).
164
+ """
165
+
166
+ def __init__(self):
167
+ raise EnvironmentError(
168
+ "AutoProcessor is designed to be instantiated "
169
+ "using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."
170
+ )
171
+
172
+ @classmethod
173
+ @replace_list_option_in_docstrings(PROCESSOR_MAPPING_NAMES)
174
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
175
+ r"""
176
+ Instantiate one of the processor classes of the library from a pretrained model vocabulary.
177
+
178
+ The processor class to instantiate is selected based on the `model_type` property of the config object (either
179
+ passed as an argument or loaded from `pretrained_model_name_or_path` if possible):
180
+
181
+ List options
182
+
183
+ Params:
184
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
185
+ This can be either:
186
+
187
+ - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
188
+ huggingface.co.
189
+ - a path to a *directory* containing a processor files saved using the `save_pretrained()` method,
190
+ e.g., `./my_model_directory/`.
191
+ cache_dir (`str` or `os.PathLike`, *optional*):
192
+ Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
193
+ standard cache should not be used.
194
+ force_download (`bool`, *optional*, defaults to `False`):
195
+ Whether or not to force to (re-)download the feature extractor files and override the cached versions
196
+ if they exist.
197
+ resume_download:
198
+ Deprecated and ignored. All downloads are now resumed by default when possible.
199
+ Will be removed in v5 of Transformers.
200
+ proxies (`Dict[str, str]`, *optional*):
201
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
202
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
203
+ token (`str` or *bool*, *optional*):
204
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
205
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
206
+ revision (`str`, *optional*, defaults to `"main"`):
207
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
208
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
209
+ identifier allowed by git.
210
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
211
+ If `False`, then this function returns just the final feature extractor object. If `True`, then this
212
+ functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
213
+ consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
214
+ `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
215
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
216
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
217
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
218
+ execute code present on the Hub on your local machine.
219
+ kwargs (`Dict[str, Any]`, *optional*):
220
+ The values in kwargs of any keys which are feature extractor attributes will be used to override the
221
+ loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
222
+ controlled by the `return_unused_kwargs` keyword parameter.
223
+
224
+ <Tip>
225
+
226
+ Passing `token=True` is required when you want to use a private model.
227
+
228
+ </Tip>
229
+
230
+ Examples:
231
+
232
+ ```python
233
+ >>> from transformers import AutoProcessor
234
+
235
+ >>> # Download processor from huggingface.co and cache.
236
+ >>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
237
+
238
+ >>> # If processor files are in a directory (e.g. processor was saved using *save_pretrained('./test/saved_model/')*)
239
+ >>> # processor = AutoProcessor.from_pretrained("./test/saved_model/")
240
+ ```"""
241
+ use_auth_token = kwargs.pop("use_auth_token", None)
242
+ if use_auth_token is not None:
243
+ warnings.warn(
244
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
245
+ FutureWarning,
246
+ )
247
+ if kwargs.get("token", None) is not None:
248
+ raise ValueError(
249
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
250
+ )
251
+ kwargs["token"] = use_auth_token
252
+
253
+ config = kwargs.pop("config", None)
254
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
255
+ kwargs["_from_auto"] = True
256
+
257
+ processor_class = None
258
+ processor_auto_map = None
259
+
260
+ # First, let's see if we have a processor or preprocessor config.
261
+ # Filter the kwargs for `cached_file`.
262
+ cached_file_kwargs = {
263
+ key: kwargs[key] for key in inspect.signature(cached_file).parameters.keys() if key in kwargs
264
+ }
265
+ # We don't want to raise
266
+ cached_file_kwargs.update(
267
+ {
268
+ "_raise_exceptions_for_gated_repo": False,
269
+ "_raise_exceptions_for_missing_entries": False,
270
+ "_raise_exceptions_for_connection_errors": False,
271
+ }
272
+ )
273
+
274
+ # Let's start by checking whether the processor class is saved in a processor config
275
+ processor_config_file = cached_file(pretrained_model_name_or_path, PROCESSOR_NAME, **cached_file_kwargs)
276
+ if processor_config_file is not None:
277
+ config_dict, _ = ProcessorMixin.get_processor_dict(pretrained_model_name_or_path, **kwargs)
278
+ processor_class = config_dict.get("processor_class", None)
279
+ if "AutoProcessor" in config_dict.get("auto_map", {}):
280
+ processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
281
+
282
+ if processor_class is None:
283
+ # If not found, let's check whether the processor class is saved in an image processor config
284
+ preprocessor_config_file = cached_file(
285
+ pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, **cached_file_kwargs
286
+ )
287
+ if preprocessor_config_file is not None:
288
+ config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
289
+ processor_class = config_dict.get("processor_class", None)
290
+ if "AutoProcessor" in config_dict.get("auto_map", {}):
291
+ processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
292
+
293
+ # If not found, let's check whether the processor class is saved in a feature extractor config
294
+ if preprocessor_config_file is not None and processor_class is None:
295
+ config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(
296
+ pretrained_model_name_or_path, **kwargs
297
+ )
298
+ processor_class = config_dict.get("processor_class", None)
299
+ if "AutoProcessor" in config_dict.get("auto_map", {}):
300
+ processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
301
+
302
+ if processor_class is None:
303
+ # Next, let's check whether the processor class is saved in a tokenizer
304
+ tokenizer_config_file = cached_file(
305
+ pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **cached_file_kwargs
306
+ )
307
+ if tokenizer_config_file is not None:
308
+ with open(tokenizer_config_file, encoding="utf-8") as reader:
309
+ config_dict = json.load(reader)
310
+
311
+ processor_class = config_dict.get("processor_class", None)
312
+ if "AutoProcessor" in config_dict.get("auto_map", {}):
313
+ processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
314
+
315
+ if processor_class is None:
316
+ # Otherwise, load config, if it can be loaded.
317
+ if not isinstance(config, PretrainedConfig):
318
+ config = AutoConfig.from_pretrained(
319
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
320
+ )
321
+
322
+ # And check if the config contains the processor class.
323
+ processor_class = getattr(config, "processor_class", None)
324
+ if hasattr(config, "auto_map") and "AutoProcessor" in config.auto_map:
325
+ processor_auto_map = config.auto_map["AutoProcessor"]
326
+
327
+ if processor_class is not None:
328
+ processor_class = processor_class_from_name(processor_class)
329
+
330
+ has_remote_code = processor_auto_map is not None
331
+ has_local_code = processor_class is not None or type(config) in PROCESSOR_MAPPING
332
+ trust_remote_code = resolve_trust_remote_code(
333
+ trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
334
+ )
335
+
336
+ if has_remote_code and trust_remote_code:
337
+ processor_class = get_class_from_dynamic_module(
338
+ processor_auto_map, pretrained_model_name_or_path, **kwargs
339
+ )
340
+ _ = kwargs.pop("code_revision", None)
341
+ if os.path.isdir(pretrained_model_name_or_path):
342
+ processor_class.register_for_auto_class()
343
+ return processor_class.from_pretrained(
344
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
345
+ )
346
+ elif processor_class is not None:
347
+ return processor_class.from_pretrained(
348
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
349
+ )
350
+ # Last try: we use the PROCESSOR_MAPPING.
351
+ elif type(config) in PROCESSOR_MAPPING:
352
+ return PROCESSOR_MAPPING[type(config)].from_pretrained(pretrained_model_name_or_path, **kwargs)
353
+
354
+ # At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
355
+ # tokenizer.
356
+ try:
357
+ return AutoTokenizer.from_pretrained(
358
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
359
+ )
360
+ except Exception:
361
+ try:
362
+ return AutoImageProcessor.from_pretrained(
363
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
364
+ )
365
+ except Exception:
366
+ pass
367
+
368
+ try:
369
+ return AutoFeatureExtractor.from_pretrained(
370
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
371
+ )
372
+ except Exception:
373
+ pass
374
+
375
+ raise ValueError(
376
+ f"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a "
377
+ "tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains "
378
+ "the files of at least one of those processing classes."
379
+ )
380
+
381
+ @staticmethod
382
+ def register(config_class, processor_class, exist_ok=False):
383
+ """
384
+ Register a new processor for this class.
385
+
386
+ Args:
387
+ config_class ([`PretrainedConfig`]):
388
+ The configuration corresponding to the model to register.
389
+ processor_class ([`ProcessorMixin`]): The processor to register.
390
+ """
391
+ PROCESSOR_MAPPING.register(config_class, processor_class, exist_ok=exist_ok)
lib/python3.12/site-packages/transformers/models/auto/tokenization_auto.py ADDED
@@ -0,0 +1,1084 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Auto Tokenizer class."""
16
+
17
+ import importlib
18
+ import json
19
+ import os
20
+ import warnings
21
+ from collections import OrderedDict
22
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
23
+
24
+ from ...configuration_utils import PretrainedConfig
25
+ from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
26
+ from ...modeling_gguf_pytorch_utils import load_gguf_checkpoint
27
+ from ...tokenization_utils import PreTrainedTokenizer
28
+ from ...tokenization_utils_base import TOKENIZER_CONFIG_FILE
29
+ from ...utils import (
30
+ cached_file,
31
+ extract_commit_hash,
32
+ is_g2p_en_available,
33
+ is_sentencepiece_available,
34
+ is_tokenizers_available,
35
+ logging,
36
+ )
37
+ from ..encoder_decoder import EncoderDecoderConfig
38
+ from .auto_factory import _LazyAutoMapping
39
+ from .configuration_auto import (
40
+ CONFIG_MAPPING_NAMES,
41
+ AutoConfig,
42
+ config_class_to_model_type,
43
+ model_type_to_module_name,
44
+ replace_list_option_in_docstrings,
45
+ )
46
+
47
+
48
+ if is_tokenizers_available():
49
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
50
+ else:
51
+ PreTrainedTokenizerFast = None
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ if TYPE_CHECKING:
57
+ # This significantly improves completion suggestion performance when
58
+ # the transformers package is used with Microsoft's Pylance language server.
59
+ TOKENIZER_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict()
60
+ else:
61
+ TOKENIZER_MAPPING_NAMES = OrderedDict(
62
+ [
63
+ (
64
+ "albert",
65
+ (
66
+ "AlbertTokenizer" if is_sentencepiece_available() else None,
67
+ "AlbertTokenizerFast" if is_tokenizers_available() else None,
68
+ ),
69
+ ),
70
+ ("align", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
71
+ ("aria", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
72
+ ("aya_vision", (None, "CohereTokenizerFast" if is_tokenizers_available() else None)),
73
+ ("bark", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
74
+ ("bart", ("BartTokenizer", "BartTokenizerFast")),
75
+ (
76
+ "barthez",
77
+ (
78
+ "BarthezTokenizer" if is_sentencepiece_available() else None,
79
+ "BarthezTokenizerFast" if is_tokenizers_available() else None,
80
+ ),
81
+ ),
82
+ ("bartpho", ("BartphoTokenizer", None)),
83
+ ("bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
84
+ ("bert-generation", ("BertGenerationTokenizer" if is_sentencepiece_available() else None, None)),
85
+ ("bert-japanese", ("BertJapaneseTokenizer", None)),
86
+ ("bertweet", ("BertweetTokenizer", None)),
87
+ (
88
+ "big_bird",
89
+ (
90
+ "BigBirdTokenizer" if is_sentencepiece_available() else None,
91
+ "BigBirdTokenizerFast" if is_tokenizers_available() else None,
92
+ ),
93
+ ),
94
+ ("bigbird_pegasus", ("PegasusTokenizer", "PegasusTokenizerFast" if is_tokenizers_available() else None)),
95
+ ("biogpt", ("BioGptTokenizer", None)),
96
+ ("blenderbot", ("BlenderbotTokenizer", "BlenderbotTokenizerFast")),
97
+ ("blenderbot-small", ("BlenderbotSmallTokenizer", None)),
98
+ ("blip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
99
+ ("blip-2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
100
+ ("bloom", (None, "BloomTokenizerFast" if is_tokenizers_available() else None)),
101
+ ("bridgetower", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
102
+ ("bros", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
103
+ ("byt5", ("ByT5Tokenizer", None)),
104
+ (
105
+ "camembert",
106
+ (
107
+ "CamembertTokenizer" if is_sentencepiece_available() else None,
108
+ "CamembertTokenizerFast" if is_tokenizers_available() else None,
109
+ ),
110
+ ),
111
+ ("canine", ("CanineTokenizer", None)),
112
+ (
113
+ "chameleon",
114
+ (
115
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
116
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
117
+ ),
118
+ ),
119
+ ("chinese_clip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
120
+ (
121
+ "clap",
122
+ (
123
+ "RobertaTokenizer",
124
+ "RobertaTokenizerFast" if is_tokenizers_available() else None,
125
+ ),
126
+ ),
127
+ (
128
+ "clip",
129
+ (
130
+ "CLIPTokenizer",
131
+ "CLIPTokenizerFast" if is_tokenizers_available() else None,
132
+ ),
133
+ ),
134
+ (
135
+ "clipseg",
136
+ (
137
+ "CLIPTokenizer",
138
+ "CLIPTokenizerFast" if is_tokenizers_available() else None,
139
+ ),
140
+ ),
141
+ ("clvp", ("ClvpTokenizer", None)),
142
+ (
143
+ "code_llama",
144
+ (
145
+ "CodeLlamaTokenizer" if is_sentencepiece_available() else None,
146
+ "CodeLlamaTokenizerFast" if is_tokenizers_available() else None,
147
+ ),
148
+ ),
149
+ ("codegen", ("CodeGenTokenizer", "CodeGenTokenizerFast" if is_tokenizers_available() else None)),
150
+ ("cohere", (None, "CohereTokenizerFast" if is_tokenizers_available() else None)),
151
+ ("cohere2", (None, "CohereTokenizerFast" if is_tokenizers_available() else None)),
152
+ ("colpali", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
153
+ ("convbert", ("ConvBertTokenizer", "ConvBertTokenizerFast" if is_tokenizers_available() else None)),
154
+ (
155
+ "cpm",
156
+ (
157
+ "CpmTokenizer" if is_sentencepiece_available() else None,
158
+ "CpmTokenizerFast" if is_tokenizers_available() else None,
159
+ ),
160
+ ),
161
+ ("cpmant", ("CpmAntTokenizer", None)),
162
+ ("ctrl", ("CTRLTokenizer", None)),
163
+ ("data2vec-audio", ("Wav2Vec2CTCTokenizer", None)),
164
+ ("data2vec-text", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
165
+ ("dbrx", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
166
+ ("deberta", ("DebertaTokenizer", "DebertaTokenizerFast" if is_tokenizers_available() else None)),
167
+ (
168
+ "deberta-v2",
169
+ (
170
+ "DebertaV2Tokenizer" if is_sentencepiece_available() else None,
171
+ "DebertaV2TokenizerFast" if is_tokenizers_available() else None,
172
+ ),
173
+ ),
174
+ (
175
+ "deepseek_v3",
176
+ (
177
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
178
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
179
+ ),
180
+ ),
181
+ (
182
+ "diffllama",
183
+ (
184
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
185
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
186
+ ),
187
+ ),
188
+ ("distilbert", ("DistilBertTokenizer", "DistilBertTokenizerFast" if is_tokenizers_available() else None)),
189
+ (
190
+ "dpr",
191
+ (
192
+ "DPRQuestionEncoderTokenizer",
193
+ "DPRQuestionEncoderTokenizerFast" if is_tokenizers_available() else None,
194
+ ),
195
+ ),
196
+ ("electra", ("ElectraTokenizer", "ElectraTokenizerFast" if is_tokenizers_available() else None)),
197
+ ("emu3", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
198
+ ("ernie", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
199
+ ("ernie_m", ("ErnieMTokenizer" if is_sentencepiece_available() else None, None)),
200
+ ("esm", ("EsmTokenizer", None)),
201
+ ("falcon", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
202
+ ("falcon_mamba", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
203
+ (
204
+ "fastspeech2_conformer",
205
+ ("FastSpeech2ConformerTokenizer" if is_g2p_en_available() else None, None),
206
+ ),
207
+ ("flaubert", ("FlaubertTokenizer", None)),
208
+ ("fnet", ("FNetTokenizer", "FNetTokenizerFast" if is_tokenizers_available() else None)),
209
+ ("fsmt", ("FSMTTokenizer", None)),
210
+ ("funnel", ("FunnelTokenizer", "FunnelTokenizerFast" if is_tokenizers_available() else None)),
211
+ (
212
+ "gemma",
213
+ (
214
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
215
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
216
+ ),
217
+ ),
218
+ (
219
+ "gemma2",
220
+ (
221
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
222
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
223
+ ),
224
+ ),
225
+ (
226
+ "gemma3",
227
+ (
228
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
229
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
230
+ ),
231
+ ),
232
+ (
233
+ "gemma3_text",
234
+ (
235
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
236
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
237
+ ),
238
+ ),
239
+ ("git", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
240
+ ("glm", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
241
+ ("gpt-sw3", ("GPTSw3Tokenizer" if is_sentencepiece_available() else None, None)),
242
+ ("gpt2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
243
+ ("gpt_bigcode", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
244
+ ("gpt_neo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
245
+ ("gpt_neox", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
246
+ ("gpt_neox_japanese", ("GPTNeoXJapaneseTokenizer", None)),
247
+ ("gptj", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
248
+ ("gptsan-japanese", ("GPTSanJapaneseTokenizer", None)),
249
+ ("grounding-dino", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
250
+ ("groupvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
251
+ ("helium", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
252
+ ("herbert", ("HerbertTokenizer", "HerbertTokenizerFast" if is_tokenizers_available() else None)),
253
+ ("hubert", ("Wav2Vec2CTCTokenizer", None)),
254
+ ("ibert", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
255
+ ("idefics", (None, "LlamaTokenizerFast" if is_tokenizers_available() else None)),
256
+ ("idefics2", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
257
+ ("idefics3", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
258
+ ("instructblip", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
259
+ ("instructblipvideo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
260
+ (
261
+ "jamba",
262
+ (
263
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
264
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
265
+ ),
266
+ ),
267
+ (
268
+ "jetmoe",
269
+ (
270
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
271
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
272
+ ),
273
+ ),
274
+ ("jukebox", ("JukeboxTokenizer", None)),
275
+ (
276
+ "kosmos-2",
277
+ (
278
+ "XLMRobertaTokenizer" if is_sentencepiece_available() else None,
279
+ "XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
280
+ ),
281
+ ),
282
+ ("layoutlm", ("LayoutLMTokenizer", "LayoutLMTokenizerFast" if is_tokenizers_available() else None)),
283
+ ("layoutlmv2", ("LayoutLMv2Tokenizer", "LayoutLMv2TokenizerFast" if is_tokenizers_available() else None)),
284
+ ("layoutlmv3", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)),
285
+ ("layoutxlm", ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast" if is_tokenizers_available() else None)),
286
+ ("led", ("LEDTokenizer", "LEDTokenizerFast" if is_tokenizers_available() else None)),
287
+ ("lilt", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)),
288
+ (
289
+ "llama",
290
+ (
291
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
292
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
293
+ ),
294
+ ),
295
+ (
296
+ "llama4",
297
+ (
298
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
299
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
300
+ ),
301
+ ),
302
+ (
303
+ "llama4_text",
304
+ (
305
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
306
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
307
+ ),
308
+ ),
309
+ ("llava", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
310
+ ("llava_next", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
311
+ ("llava_next_video", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
312
+ ("llava_onevision", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
313
+ ("longformer", ("LongformerTokenizer", "LongformerTokenizerFast" if is_tokenizers_available() else None)),
314
+ (
315
+ "longt5",
316
+ (
317
+ "T5Tokenizer" if is_sentencepiece_available() else None,
318
+ "T5TokenizerFast" if is_tokenizers_available() else None,
319
+ ),
320
+ ),
321
+ ("luke", ("LukeTokenizer", None)),
322
+ ("lxmert", ("LxmertTokenizer", "LxmertTokenizerFast" if is_tokenizers_available() else None)),
323
+ ("m2m_100", ("M2M100Tokenizer" if is_sentencepiece_available() else None, None)),
324
+ ("mamba", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
325
+ ("mamba2", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
326
+ ("marian", ("MarianTokenizer" if is_sentencepiece_available() else None, None)),
327
+ (
328
+ "mbart",
329
+ (
330
+ "MBartTokenizer" if is_sentencepiece_available() else None,
331
+ "MBartTokenizerFast" if is_tokenizers_available() else None,
332
+ ),
333
+ ),
334
+ (
335
+ "mbart50",
336
+ (
337
+ "MBart50Tokenizer" if is_sentencepiece_available() else None,
338
+ "MBart50TokenizerFast" if is_tokenizers_available() else None,
339
+ ),
340
+ ),
341
+ ("mega", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
342
+ ("megatron-bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
343
+ ("mgp-str", ("MgpstrTokenizer", None)),
344
+ (
345
+ "mistral",
346
+ (
347
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
348
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
349
+ ),
350
+ ),
351
+ (
352
+ "mixtral",
353
+ (
354
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
355
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
356
+ ),
357
+ ),
358
+ ("mllama", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
359
+ ("mluke", ("MLukeTokenizer" if is_sentencepiece_available() else None, None)),
360
+ ("mobilebert", ("MobileBertTokenizer", "MobileBertTokenizerFast" if is_tokenizers_available() else None)),
361
+ ("modernbert", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
362
+ ("moonshine", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
363
+ ("moshi", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
364
+ ("mpnet", ("MPNetTokenizer", "MPNetTokenizerFast" if is_tokenizers_available() else None)),
365
+ ("mpt", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
366
+ ("mra", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
367
+ (
368
+ "mt5",
369
+ (
370
+ "MT5Tokenizer" if is_sentencepiece_available() else None,
371
+ "MT5TokenizerFast" if is_tokenizers_available() else None,
372
+ ),
373
+ ),
374
+ ("musicgen", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
375
+ ("musicgen_melody", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
376
+ ("mvp", ("MvpTokenizer", "MvpTokenizerFast" if is_tokenizers_available() else None)),
377
+ ("myt5", ("MyT5Tokenizer", None)),
378
+ ("nemotron", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
379
+ ("nezha", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
380
+ (
381
+ "nllb",
382
+ (
383
+ "NllbTokenizer" if is_sentencepiece_available() else None,
384
+ "NllbTokenizerFast" if is_tokenizers_available() else None,
385
+ ),
386
+ ),
387
+ (
388
+ "nllb-moe",
389
+ (
390
+ "NllbTokenizer" if is_sentencepiece_available() else None,
391
+ "NllbTokenizerFast" if is_tokenizers_available() else None,
392
+ ),
393
+ ),
394
+ (
395
+ "nystromformer",
396
+ (
397
+ "AlbertTokenizer" if is_sentencepiece_available() else None,
398
+ "AlbertTokenizerFast" if is_tokenizers_available() else None,
399
+ ),
400
+ ),
401
+ ("olmo", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
402
+ ("olmo2", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
403
+ ("olmoe", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
404
+ (
405
+ "omdet-turbo",
406
+ ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None),
407
+ ),
408
+ ("oneformer", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
409
+ (
410
+ "openai-gpt",
411
+ ("OpenAIGPTTokenizer", "OpenAIGPTTokenizerFast" if is_tokenizers_available() else None),
412
+ ),
413
+ ("opt", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
414
+ ("owlv2", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
415
+ ("owlvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
416
+ ("paligemma", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
417
+ (
418
+ "pegasus",
419
+ (
420
+ "PegasusTokenizer" if is_sentencepiece_available() else None,
421
+ "PegasusTokenizerFast" if is_tokenizers_available() else None,
422
+ ),
423
+ ),
424
+ (
425
+ "pegasus_x",
426
+ (
427
+ "PegasusTokenizer" if is_sentencepiece_available() else None,
428
+ "PegasusTokenizerFast" if is_tokenizers_available() else None,
429
+ ),
430
+ ),
431
+ (
432
+ "perceiver",
433
+ (
434
+ "PerceiverTokenizer",
435
+ None,
436
+ ),
437
+ ),
438
+ (
439
+ "persimmon",
440
+ (
441
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
442
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
443
+ ),
444
+ ),
445
+ ("phi", ("CodeGenTokenizer", "CodeGenTokenizerFast" if is_tokenizers_available() else None)),
446
+ ("phi3", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
447
+ ("phimoe", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
448
+ ("phobert", ("PhobertTokenizer", None)),
449
+ ("pix2struct", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
450
+ ("pixtral", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
451
+ ("plbart", ("PLBartTokenizer" if is_sentencepiece_available() else None, None)),
452
+ ("prophetnet", ("ProphetNetTokenizer", None)),
453
+ ("qdqbert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
454
+ (
455
+ "qwen2",
456
+ (
457
+ "Qwen2Tokenizer",
458
+ "Qwen2TokenizerFast" if is_tokenizers_available() else None,
459
+ ),
460
+ ),
461
+ ("qwen2_5_vl", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)),
462
+ ("qwen2_audio", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)),
463
+ (
464
+ "qwen2_moe",
465
+ (
466
+ "Qwen2Tokenizer",
467
+ "Qwen2TokenizerFast" if is_tokenizers_available() else None,
468
+ ),
469
+ ),
470
+ ("qwen2_vl", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)),
471
+ (
472
+ "qwen3",
473
+ (
474
+ "Qwen2Tokenizer",
475
+ "Qwen2TokenizerFast" if is_tokenizers_available() else None,
476
+ ),
477
+ ),
478
+ (
479
+ "qwen3_moe",
480
+ (
481
+ "Qwen2Tokenizer",
482
+ "Qwen2TokenizerFast" if is_tokenizers_available() else None,
483
+ ),
484
+ ),
485
+ ("rag", ("RagTokenizer", None)),
486
+ ("realm", ("RealmTokenizer", "RealmTokenizerFast" if is_tokenizers_available() else None)),
487
+ (
488
+ "recurrent_gemma",
489
+ (
490
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
491
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
492
+ ),
493
+ ),
494
+ (
495
+ "reformer",
496
+ (
497
+ "ReformerTokenizer" if is_sentencepiece_available() else None,
498
+ "ReformerTokenizerFast" if is_tokenizers_available() else None,
499
+ ),
500
+ ),
501
+ (
502
+ "rembert",
503
+ (
504
+ "RemBertTokenizer" if is_sentencepiece_available() else None,
505
+ "RemBertTokenizerFast" if is_tokenizers_available() else None,
506
+ ),
507
+ ),
508
+ ("retribert", ("RetriBertTokenizer", "RetriBertTokenizerFast" if is_tokenizers_available() else None)),
509
+ ("roberta", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
510
+ (
511
+ "roberta-prelayernorm",
512
+ ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None),
513
+ ),
514
+ ("roc_bert", ("RoCBertTokenizer", None)),
515
+ ("roformer", ("RoFormerTokenizer", "RoFormerTokenizerFast" if is_tokenizers_available() else None)),
516
+ ("rwkv", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
517
+ (
518
+ "seamless_m4t",
519
+ (
520
+ "SeamlessM4TTokenizer" if is_sentencepiece_available() else None,
521
+ "SeamlessM4TTokenizerFast" if is_tokenizers_available() else None,
522
+ ),
523
+ ),
524
+ (
525
+ "seamless_m4t_v2",
526
+ (
527
+ "SeamlessM4TTokenizer" if is_sentencepiece_available() else None,
528
+ "SeamlessM4TTokenizerFast" if is_tokenizers_available() else None,
529
+ ),
530
+ ),
531
+ (
532
+ "shieldgemma2",
533
+ (
534
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
535
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
536
+ ),
537
+ ),
538
+ ("siglip", ("SiglipTokenizer" if is_sentencepiece_available() else None, None)),
539
+ (
540
+ "siglip2",
541
+ (
542
+ "GemmaTokenizer" if is_sentencepiece_available() else None,
543
+ "GemmaTokenizerFast" if is_tokenizers_available() else None,
544
+ ),
545
+ ),
546
+ ("speech_to_text", ("Speech2TextTokenizer" if is_sentencepiece_available() else None, None)),
547
+ ("speech_to_text_2", ("Speech2Text2Tokenizer", None)),
548
+ ("speecht5", ("SpeechT5Tokenizer" if is_sentencepiece_available() else None, None)),
549
+ ("splinter", ("SplinterTokenizer", "SplinterTokenizerFast")),
550
+ (
551
+ "squeezebert",
552
+ ("SqueezeBertTokenizer", "SqueezeBertTokenizerFast" if is_tokenizers_available() else None),
553
+ ),
554
+ ("stablelm", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
555
+ ("starcoder2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
556
+ (
557
+ "switch_transformers",
558
+ (
559
+ "T5Tokenizer" if is_sentencepiece_available() else None,
560
+ "T5TokenizerFast" if is_tokenizers_available() else None,
561
+ ),
562
+ ),
563
+ (
564
+ "t5",
565
+ (
566
+ "T5Tokenizer" if is_sentencepiece_available() else None,
567
+ "T5TokenizerFast" if is_tokenizers_available() else None,
568
+ ),
569
+ ),
570
+ ("tapas", ("TapasTokenizer", None)),
571
+ ("tapex", ("TapexTokenizer", None)),
572
+ ("transfo-xl", ("TransfoXLTokenizer", None)),
573
+ ("tvp", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
574
+ (
575
+ "udop",
576
+ (
577
+ "UdopTokenizer" if is_sentencepiece_available() else None,
578
+ "UdopTokenizerFast" if is_tokenizers_available() else None,
579
+ ),
580
+ ),
581
+ (
582
+ "umt5",
583
+ (
584
+ "T5Tokenizer" if is_sentencepiece_available() else None,
585
+ "T5TokenizerFast" if is_tokenizers_available() else None,
586
+ ),
587
+ ),
588
+ ("video_llava", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
589
+ ("vilt", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
590
+ ("vipllava", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
591
+ ("visual_bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
592
+ ("vits", ("VitsTokenizer", None)),
593
+ ("wav2vec2", ("Wav2Vec2CTCTokenizer", None)),
594
+ ("wav2vec2-bert", ("Wav2Vec2CTCTokenizer", None)),
595
+ ("wav2vec2-conformer", ("Wav2Vec2CTCTokenizer", None)),
596
+ ("wav2vec2_phoneme", ("Wav2Vec2PhonemeCTCTokenizer", None)),
597
+ ("whisper", ("WhisperTokenizer", "WhisperTokenizerFast" if is_tokenizers_available() else None)),
598
+ ("xclip", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
599
+ (
600
+ "xglm",
601
+ (
602
+ "XGLMTokenizer" if is_sentencepiece_available() else None,
603
+ "XGLMTokenizerFast" if is_tokenizers_available() else None,
604
+ ),
605
+ ),
606
+ ("xlm", ("XLMTokenizer", None)),
607
+ ("xlm-prophetnet", ("XLMProphetNetTokenizer" if is_sentencepiece_available() else None, None)),
608
+ (
609
+ "xlm-roberta",
610
+ (
611
+ "XLMRobertaTokenizer" if is_sentencepiece_available() else None,
612
+ "XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
613
+ ),
614
+ ),
615
+ (
616
+ "xlm-roberta-xl",
617
+ (
618
+ "XLMRobertaTokenizer" if is_sentencepiece_available() else None,
619
+ "XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
620
+ ),
621
+ ),
622
+ (
623
+ "xlnet",
624
+ (
625
+ "XLNetTokenizer" if is_sentencepiece_available() else None,
626
+ "XLNetTokenizerFast" if is_tokenizers_available() else None,
627
+ ),
628
+ ),
629
+ (
630
+ "xmod",
631
+ (
632
+ "XLMRobertaTokenizer" if is_sentencepiece_available() else None,
633
+ "XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
634
+ ),
635
+ ),
636
+ (
637
+ "yoso",
638
+ (
639
+ "AlbertTokenizer" if is_sentencepiece_available() else None,
640
+ "AlbertTokenizerFast" if is_tokenizers_available() else None,
641
+ ),
642
+ ),
643
+ (
644
+ "zamba",
645
+ (
646
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
647
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
648
+ ),
649
+ ),
650
+ (
651
+ "zamba2",
652
+ (
653
+ "LlamaTokenizer" if is_sentencepiece_available() else None,
654
+ "LlamaTokenizerFast" if is_tokenizers_available() else None,
655
+ ),
656
+ ),
657
+ ]
658
+ )
659
+
660
+ TOKENIZER_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TOKENIZER_MAPPING_NAMES)
661
+
662
+ CONFIG_TO_TYPE = {v: k for k, v in CONFIG_MAPPING_NAMES.items()}
663
+
664
+
665
+ def tokenizer_class_from_name(class_name: str):
666
+ if class_name == "PreTrainedTokenizerFast":
667
+ return PreTrainedTokenizerFast
668
+
669
+ for module_name, tokenizers in TOKENIZER_MAPPING_NAMES.items():
670
+ if class_name in tokenizers:
671
+ module_name = model_type_to_module_name(module_name)
672
+
673
+ module = importlib.import_module(f".{module_name}", "transformers.models")
674
+ try:
675
+ return getattr(module, class_name)
676
+ except AttributeError:
677
+ continue
678
+
679
+ for config, tokenizers in TOKENIZER_MAPPING._extra_content.items():
680
+ for tokenizer in tokenizers:
681
+ if getattr(tokenizer, "__name__", None) == class_name:
682
+ return tokenizer
683
+
684
+ # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
685
+ # init and we return the proper dummy to get an appropriate error message.
686
+ main_module = importlib.import_module("transformers")
687
+ if hasattr(main_module, class_name):
688
+ return getattr(main_module, class_name)
689
+
690
+ return None
691
+
692
+
693
+ def get_tokenizer_config(
694
+ pretrained_model_name_or_path: Union[str, os.PathLike],
695
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
696
+ force_download: bool = False,
697
+ resume_download: Optional[bool] = None,
698
+ proxies: Optional[Dict[str, str]] = None,
699
+ token: Optional[Union[bool, str]] = None,
700
+ revision: Optional[str] = None,
701
+ local_files_only: bool = False,
702
+ subfolder: str = "",
703
+ **kwargs,
704
+ ):
705
+ """
706
+ Loads the tokenizer configuration from a pretrained model tokenizer configuration.
707
+
708
+ Args:
709
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
710
+ This can be either:
711
+
712
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
713
+ huggingface.co.
714
+ - a path to a *directory* containing a configuration file saved using the
715
+ [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
716
+
717
+ cache_dir (`str` or `os.PathLike`, *optional*):
718
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
719
+ cache should not be used.
720
+ force_download (`bool`, *optional*, defaults to `False`):
721
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
722
+ exist.
723
+ resume_download:
724
+ Deprecated and ignored. All downloads are now resumed by default when possible.
725
+ Will be removed in v5 of Transformers.
726
+ proxies (`Dict[str, str]`, *optional*):
727
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
728
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
729
+ token (`str` or *bool*, *optional*):
730
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
731
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
732
+ revision (`str`, *optional*, defaults to `"main"`):
733
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
734
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
735
+ identifier allowed by git.
736
+ local_files_only (`bool`, *optional*, defaults to `False`):
737
+ If `True`, will only try to load the tokenizer configuration from local files.
738
+ subfolder (`str`, *optional*, defaults to `""`):
739
+ In case the tokenizer config is located inside a subfolder of the model repo on huggingface.co, you can
740
+ specify the folder name here.
741
+
742
+ <Tip>
743
+
744
+ Passing `token=True` is required when you want to use a private model.
745
+
746
+ </Tip>
747
+
748
+ Returns:
749
+ `Dict`: The configuration of the tokenizer.
750
+
751
+ Examples:
752
+
753
+ ```python
754
+ # Download configuration from huggingface.co and cache.
755
+ tokenizer_config = get_tokenizer_config("google-bert/bert-base-uncased")
756
+ # This model does not have a tokenizer config so the result will be an empty dict.
757
+ tokenizer_config = get_tokenizer_config("FacebookAI/xlm-roberta-base")
758
+
759
+ # Save a pretrained tokenizer locally and you can reload its config
760
+ from transformers import AutoTokenizer
761
+
762
+ tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
763
+ tokenizer.save_pretrained("tokenizer-test")
764
+ tokenizer_config = get_tokenizer_config("tokenizer-test")
765
+ ```"""
766
+ use_auth_token = kwargs.pop("use_auth_token", None)
767
+ if use_auth_token is not None:
768
+ warnings.warn(
769
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
770
+ FutureWarning,
771
+ )
772
+ if token is not None:
773
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
774
+ token = use_auth_token
775
+
776
+ commit_hash = kwargs.get("_commit_hash", None)
777
+ resolved_config_file = cached_file(
778
+ pretrained_model_name_or_path,
779
+ TOKENIZER_CONFIG_FILE,
780
+ cache_dir=cache_dir,
781
+ force_download=force_download,
782
+ resume_download=resume_download,
783
+ proxies=proxies,
784
+ token=token,
785
+ revision=revision,
786
+ local_files_only=local_files_only,
787
+ subfolder=subfolder,
788
+ _raise_exceptions_for_gated_repo=False,
789
+ _raise_exceptions_for_missing_entries=False,
790
+ _raise_exceptions_for_connection_errors=False,
791
+ _commit_hash=commit_hash,
792
+ )
793
+ if resolved_config_file is None:
794
+ logger.info("Could not locate the tokenizer configuration file, will try to use the model config instead.")
795
+ return {}
796
+ commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
797
+
798
+ with open(resolved_config_file, encoding="utf-8") as reader:
799
+ result = json.load(reader)
800
+ result["_commit_hash"] = commit_hash
801
+ return result
802
+
803
+
804
+ class AutoTokenizer:
805
+ r"""
806
+ This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when
807
+ created with the [`AutoTokenizer.from_pretrained`] class method.
808
+
809
+ This class cannot be instantiated directly using `__init__()` (throws an error).
810
+ """
811
+
812
+ def __init__(self):
813
+ raise EnvironmentError(
814
+ "AutoTokenizer is designed to be instantiated "
815
+ "using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method."
816
+ )
817
+
818
+ @classmethod
819
+ @replace_list_option_in_docstrings(TOKENIZER_MAPPING_NAMES)
820
+ def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
821
+ r"""
822
+ Instantiate one of the tokenizer classes of the library from a pretrained model vocabulary.
823
+
824
+ The tokenizer class to instantiate is selected based on the `model_type` property of the config object (either
825
+ passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
826
+ falling back to using pattern matching on `pretrained_model_name_or_path`:
827
+
828
+ List options
829
+
830
+ Params:
831
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
832
+ Can be either:
833
+
834
+ - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
835
+ - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
836
+ using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
837
+ - A path or url to a single saved vocabulary file if and only if the tokenizer only requires a
838
+ single vocabulary file (like Bert or XLNet), e.g.: `./my_model_directory/vocab.txt`. (Not
839
+ applicable to all derived classes)
840
+ inputs (additional positional arguments, *optional*):
841
+ Will be passed along to the Tokenizer `__init__()` method.
842
+ config ([`PretrainedConfig`], *optional*)
843
+ The configuration object used to determine the tokenizer class to instantiate.
844
+ cache_dir (`str` or `os.PathLike`, *optional*):
845
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
846
+ standard cache should not be used.
847
+ force_download (`bool`, *optional*, defaults to `False`):
848
+ Whether or not to force the (re-)download the model weights and configuration files and override the
849
+ cached versions if they exist.
850
+ resume_download:
851
+ Deprecated and ignored. All downloads are now resumed by default when possible.
852
+ Will be removed in v5 of Transformers.
853
+ proxies (`Dict[str, str]`, *optional*):
854
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
855
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
856
+ revision (`str`, *optional*, defaults to `"main"`):
857
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
858
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
859
+ identifier allowed by git.
860
+ subfolder (`str`, *optional*):
861
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co (e.g. for
862
+ facebook/rag-token-base), specify it here.
863
+ use_fast (`bool`, *optional*, defaults to `True`):
864
+ Use a [fast Rust-based tokenizer](https://huggingface.co/docs/tokenizers/index) if it is supported for
865
+ a given model. If a fast tokenizer is not available for a given model, a normal Python-based tokenizer
866
+ is returned instead.
867
+ tokenizer_type (`str`, *optional*):
868
+ Tokenizer type to be loaded.
869
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
870
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
871
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
872
+ execute code present on the Hub on your local machine.
873
+ kwargs (additional keyword arguments, *optional*):
874
+ Will be passed to the Tokenizer `__init__()` method. Can be used to set special tokens like
875
+ `bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`,
876
+ `additional_special_tokens`. See parameters in the `__init__()` for more details.
877
+
878
+ Examples:
879
+
880
+ ```python
881
+ >>> from transformers import AutoTokenizer
882
+
883
+ >>> # Download vocabulary from huggingface.co and cache.
884
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
885
+
886
+ >>> # Download vocabulary from huggingface.co (user-uploaded) and cache.
887
+ >>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
888
+
889
+ >>> # If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*)
890
+ >>> # tokenizer = AutoTokenizer.from_pretrained("./test/bert_saved_model/")
891
+
892
+ >>> # Download vocabulary from huggingface.co and define model-specific arguments
893
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base", add_prefix_space=True)
894
+ ```"""
895
+ use_auth_token = kwargs.pop("use_auth_token", None)
896
+ if use_auth_token is not None:
897
+ warnings.warn(
898
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
899
+ FutureWarning,
900
+ )
901
+ if kwargs.get("token", None) is not None:
902
+ raise ValueError(
903
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
904
+ )
905
+ kwargs["token"] = use_auth_token
906
+
907
+ config = kwargs.pop("config", None)
908
+ kwargs["_from_auto"] = True
909
+
910
+ use_fast = kwargs.pop("use_fast", True)
911
+ tokenizer_type = kwargs.pop("tokenizer_type", None)
912
+ trust_remote_code = kwargs.pop("trust_remote_code", None)
913
+ gguf_file = kwargs.get("gguf_file", None)
914
+
915
+ # First, let's see whether the tokenizer_type is passed so that we can leverage it
916
+ if tokenizer_type is not None:
917
+ tokenizer_class = None
918
+ tokenizer_class_tuple = TOKENIZER_MAPPING_NAMES.get(tokenizer_type, None)
919
+
920
+ if tokenizer_class_tuple is None:
921
+ raise ValueError(
922
+ f"Passed `tokenizer_type` {tokenizer_type} does not exist. `tokenizer_type` should be one of "
923
+ f"{', '.join(c for c in TOKENIZER_MAPPING_NAMES.keys())}."
924
+ )
925
+
926
+ tokenizer_class_name, tokenizer_fast_class_name = tokenizer_class_tuple
927
+
928
+ if use_fast:
929
+ if tokenizer_fast_class_name is not None:
930
+ tokenizer_class = tokenizer_class_from_name(tokenizer_fast_class_name)
931
+ else:
932
+ logger.warning(
933
+ "`use_fast` is set to `True` but the tokenizer class does not have a fast version. "
934
+ " Falling back to the slow version."
935
+ )
936
+ if tokenizer_class is None:
937
+ tokenizer_class = tokenizer_class_from_name(tokenizer_class_name)
938
+
939
+ if tokenizer_class is None:
940
+ raise ValueError(f"Tokenizer class {tokenizer_class_name} is not currently imported.")
941
+
942
+ return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
943
+
944
+ # Next, let's try to use the tokenizer_config file to get the tokenizer class.
945
+ tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs)
946
+ if "_commit_hash" in tokenizer_config:
947
+ kwargs["_commit_hash"] = tokenizer_config["_commit_hash"]
948
+ config_tokenizer_class = tokenizer_config.get("tokenizer_class")
949
+ tokenizer_auto_map = None
950
+ if "auto_map" in tokenizer_config:
951
+ if isinstance(tokenizer_config["auto_map"], (tuple, list)):
952
+ # Legacy format for dynamic tokenizers
953
+ tokenizer_auto_map = tokenizer_config["auto_map"]
954
+ else:
955
+ tokenizer_auto_map = tokenizer_config["auto_map"].get("AutoTokenizer", None)
956
+
957
+ # If that did not work, let's try to use the config.
958
+ if config_tokenizer_class is None:
959
+ if not isinstance(config, PretrainedConfig):
960
+ if gguf_file:
961
+ gguf_path = cached_file(pretrained_model_name_or_path, gguf_file, **kwargs)
962
+ config_dict = load_gguf_checkpoint(gguf_path, return_tensors=False)["config"]
963
+ config = AutoConfig.for_model(**config_dict)
964
+ else:
965
+ config = AutoConfig.from_pretrained(
966
+ pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
967
+ )
968
+ config_tokenizer_class = config.tokenizer_class
969
+ if hasattr(config, "auto_map") and "AutoTokenizer" in config.auto_map:
970
+ tokenizer_auto_map = config.auto_map["AutoTokenizer"]
971
+
972
+ has_remote_code = tokenizer_auto_map is not None
973
+ has_local_code = type(config) in TOKENIZER_MAPPING or (
974
+ config_tokenizer_class is not None
975
+ and (
976
+ tokenizer_class_from_name(config_tokenizer_class) is not None
977
+ or tokenizer_class_from_name(config_tokenizer_class + "Fast") is not None
978
+ )
979
+ )
980
+ trust_remote_code = resolve_trust_remote_code(
981
+ trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
982
+ )
983
+
984
+ if has_remote_code and trust_remote_code:
985
+ if use_fast and tokenizer_auto_map[1] is not None:
986
+ class_ref = tokenizer_auto_map[1]
987
+ else:
988
+ class_ref = tokenizer_auto_map[0]
989
+ tokenizer_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
990
+ _ = kwargs.pop("code_revision", None)
991
+ if os.path.isdir(pretrained_model_name_or_path):
992
+ tokenizer_class.register_for_auto_class()
993
+ return tokenizer_class.from_pretrained(
994
+ pretrained_model_name_or_path, *inputs, trust_remote_code=trust_remote_code, **kwargs
995
+ )
996
+ elif config_tokenizer_class is not None:
997
+ tokenizer_class = None
998
+ if use_fast and not config_tokenizer_class.endswith("Fast"):
999
+ tokenizer_class_candidate = f"{config_tokenizer_class}Fast"
1000
+ tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
1001
+ if tokenizer_class is None:
1002
+ tokenizer_class_candidate = config_tokenizer_class
1003
+ tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
1004
+ if tokenizer_class is None:
1005
+ raise ValueError(
1006
+ f"Tokenizer class {tokenizer_class_candidate} does not exist or is not currently imported."
1007
+ )
1008
+ return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
1009
+
1010
+ # Otherwise we have to be creative.
1011
+ # if model is an encoder decoder, the encoder tokenizer class is used by default
1012
+ if isinstance(config, EncoderDecoderConfig):
1013
+ if type(config.decoder) is not type(config.encoder): # noqa: E721
1014
+ logger.warning(
1015
+ f"The encoder model config class: {config.encoder.__class__} is different from the decoder model "
1016
+ f"config class: {config.decoder.__class__}. It is not recommended to use the "
1017
+ "`AutoTokenizer.from_pretrained()` method in this case. Please use the encoder and decoder "
1018
+ "specific tokenizer classes."
1019
+ )
1020
+ config = config.encoder
1021
+
1022
+ model_type = config_class_to_model_type(type(config).__name__)
1023
+ if model_type is not None:
1024
+ tokenizer_class_py, tokenizer_class_fast = TOKENIZER_MAPPING[type(config)]
1025
+
1026
+ if tokenizer_class_fast and (use_fast or tokenizer_class_py is None):
1027
+ return tokenizer_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
1028
+ else:
1029
+ if tokenizer_class_py is not None:
1030
+ return tokenizer_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
1031
+ else:
1032
+ raise ValueError(
1033
+ "This tokenizer cannot be instantiated. Please make sure you have `sentencepiece` installed "
1034
+ "in order to use this tokenizer."
1035
+ )
1036
+
1037
+ raise ValueError(
1038
+ f"Unrecognized configuration class {config.__class__} to build an AutoTokenizer.\n"
1039
+ f"Model type should be one of {', '.join(c.__name__ for c in TOKENIZER_MAPPING.keys())}."
1040
+ )
1041
+
1042
+ @staticmethod
1043
+ def register(config_class, slow_tokenizer_class=None, fast_tokenizer_class=None, exist_ok=False):
1044
+ """
1045
+ Register a new tokenizer in this mapping.
1046
+
1047
+
1048
+ Args:
1049
+ config_class ([`PretrainedConfig`]):
1050
+ The configuration corresponding to the model to register.
1051
+ slow_tokenizer_class ([`PretrainedTokenizer`], *optional*):
1052
+ The slow tokenizer to register.
1053
+ fast_tokenizer_class ([`PretrainedTokenizerFast`], *optional*):
1054
+ The fast tokenizer to register.
1055
+ """
1056
+ if slow_tokenizer_class is None and fast_tokenizer_class is None:
1057
+ raise ValueError("You need to pass either a `slow_tokenizer_class` or a `fast_tokenizer_class")
1058
+ if slow_tokenizer_class is not None and issubclass(slow_tokenizer_class, PreTrainedTokenizerFast):
1059
+ raise ValueError("You passed a fast tokenizer in the `slow_tokenizer_class`.")
1060
+ if fast_tokenizer_class is not None and issubclass(fast_tokenizer_class, PreTrainedTokenizer):
1061
+ raise ValueError("You passed a slow tokenizer in the `fast_tokenizer_class`.")
1062
+
1063
+ if (
1064
+ slow_tokenizer_class is not None
1065
+ and fast_tokenizer_class is not None
1066
+ and issubclass(fast_tokenizer_class, PreTrainedTokenizerFast)
1067
+ and fast_tokenizer_class.slow_tokenizer_class != slow_tokenizer_class
1068
+ ):
1069
+ raise ValueError(
1070
+ "The fast tokenizer class you are passing has a `slow_tokenizer_class` attribute that is not "
1071
+ "consistent with the slow tokenizer class you passed (fast tokenizer has "
1072
+ f"{fast_tokenizer_class.slow_tokenizer_class} and you passed {slow_tokenizer_class}. Fix one of those "
1073
+ "so they match!"
1074
+ )
1075
+
1076
+ # Avoid resetting a set slow/fast tokenizer if we are passing just the other ones.
1077
+ if config_class in TOKENIZER_MAPPING._extra_content:
1078
+ existing_slow, existing_fast = TOKENIZER_MAPPING[config_class]
1079
+ if slow_tokenizer_class is None:
1080
+ slow_tokenizer_class = existing_slow
1081
+ if fast_tokenizer_class is None:
1082
+ fast_tokenizer_class = existing_fast
1083
+
1084
+ TOKENIZER_MAPPING.register(config_class, (slow_tokenizer_class, fast_tokenizer_class), exist_ok=exist_ok)
lib/python3.12/site-packages/transformers/models/bark/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_bark import *
22
+ from .modeling_bark import *
23
+ from .processing_bark import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/bark/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (691 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/bark/__pycache__/configuration_bark.cpython-312.pyc ADDED
Binary file (11.8 kB). View file
 
lib/python3.12/site-packages/transformers/models/bark/__pycache__/generation_configuration_bark.cpython-312.pyc ADDED
Binary file (14.4 kB). View file
 
lib/python3.12/site-packages/transformers/models/bark/__pycache__/modeling_bark.cpython-312.pyc ADDED
Binary file (81.6 kB). View file
 
lib/python3.12/site-packages/transformers/models/bark/__pycache__/processing_bark.cpython-312.pyc ADDED
Binary file (13.3 kB). View file
 
lib/python3.12/site-packages/transformers/models/bark/configuration_bark.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """BARK model configuration"""
16
+
17
+ from typing import Dict
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import add_start_docstrings, logging
21
+ from ..auto import CONFIG_MAPPING, AutoConfig
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ BARK_SUBMODELCONFIG_START_DOCSTRING = """
28
+ This is the configuration class to store the configuration of a [`{model}`]. It is used to instantiate the model
29
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the Bark [suno/bark](https://huggingface.co/suno/bark)
31
+ architecture.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ block_size (`int`, *optional*, defaults to 1024):
38
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
39
+ just in case (e.g., 512 or 1024 or 2048).
40
+ input_vocab_size (`int`, *optional*, defaults to 10_048):
41
+ Vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`{model}`]. Defaults to 10_048 but should be carefully thought with
43
+ regards to the chosen sub-model.
44
+ output_vocab_size (`int`, *optional*, defaults to 10_048):
45
+ Output vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented
46
+ by the: `output_ids` when passing forward a [`{model}`]. Defaults to 10_048 but should be carefully thought
47
+ with regards to the chosen sub-model.
48
+ num_layers (`int`, *optional*, defaults to 12):
49
+ Number of hidden layers in the given sub-model.
50
+ num_heads (`int`, *optional*, defaults to 12):
51
+ Number of attention heads for each attention layer in the Transformer architecture.
52
+ hidden_size (`int`, *optional*, defaults to 768):
53
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the architecture.
54
+ dropout (`float`, *optional*, defaults to 0.0):
55
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
56
+ bias (`bool`, *optional*, defaults to `True`):
57
+ Whether or not to use bias in the linear layers and layer norm layers.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ use_cache (`bool`, *optional*, defaults to `True`):
61
+ Whether or not the model should return the last key/values attentions (not used by all models).
62
+ """
63
+
64
+
65
+ class BarkSubModelConfig(PretrainedConfig):
66
+ keys_to_ignore_at_inference = ["past_key_values"]
67
+
68
+ attribute_map = {
69
+ "num_attention_heads": "num_heads",
70
+ "num_hidden_layers": "num_layers",
71
+ "vocab_size": "input_vocab_size",
72
+ "window_size": "block_size",
73
+ }
74
+
75
+ def __init__(
76
+ self,
77
+ block_size=1024,
78
+ input_vocab_size=10_048,
79
+ output_vocab_size=10_048,
80
+ num_layers=12,
81
+ num_heads=12,
82
+ hidden_size=768,
83
+ dropout=0.0,
84
+ bias=True, # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
85
+ initializer_range=0.02,
86
+ use_cache=True,
87
+ **kwargs,
88
+ ):
89
+ self.block_size = block_size
90
+ self.input_vocab_size = input_vocab_size
91
+ self.output_vocab_size = output_vocab_size
92
+ self.num_layers = num_layers
93
+ self.num_heads = num_heads
94
+ self.hidden_size = hidden_size
95
+ self.dropout = dropout
96
+ self.bias = bias
97
+ self.use_cache = use_cache
98
+ self.initializer_range = initializer_range
99
+
100
+ super().__init__(**kwargs)
101
+
102
+
103
+ @add_start_docstrings(
104
+ BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkSemanticConfig", model="BarkSemanticModel"),
105
+ """
106
+ Example:
107
+
108
+ ```python
109
+ >>> from transformers import BarkSemanticConfig, BarkSemanticModel
110
+
111
+ >>> # Initializing a Bark sub-module style configuration
112
+ >>> configuration = BarkSemanticConfig()
113
+
114
+ >>> # Initializing a model (with random weights) from the suno/bark style configuration
115
+ >>> model = BarkSemanticModel(configuration)
116
+
117
+ >>> # Accessing the model configuration
118
+ >>> configuration = model.config
119
+ ```""",
120
+ )
121
+ class BarkSemanticConfig(BarkSubModelConfig):
122
+ model_type = "semantic"
123
+ base_config_key = "semantic_config"
124
+
125
+
126
+ @add_start_docstrings(
127
+ BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkCoarseConfig", model="BarkCoarseModel"),
128
+ """
129
+ Example:
130
+
131
+ ```python
132
+ >>> from transformers import BarkCoarseConfig, BarkCoarseModel
133
+
134
+ >>> # Initializing a Bark sub-module style configuration
135
+ >>> configuration = BarkCoarseConfig()
136
+
137
+ >>> # Initializing a model (with random weights) from the suno/bark style configuration
138
+ >>> model = BarkCoarseModel(configuration)
139
+
140
+ >>> # Accessing the model configuration
141
+ >>> configuration = model.config
142
+ ```""",
143
+ )
144
+ class BarkCoarseConfig(BarkSubModelConfig):
145
+ model_type = "coarse_acoustics"
146
+ base_config_key = "coarse_acoustics_config"
147
+
148
+
149
+ @add_start_docstrings(
150
+ BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkFineConfig", model="BarkFineModel"),
151
+ """
152
+ n_codes_total (`int`, *optional*, defaults to 8):
153
+ The total number of audio codebooks predicted. Used in the fine acoustics sub-model.
154
+ n_codes_given (`int`, *optional*, defaults to 1):
155
+ The number of audio codebooks predicted in the coarse acoustics sub-model. Used in the acoustics
156
+ sub-models.
157
+ Example:
158
+
159
+ ```python
160
+ >>> from transformers import BarkFineConfig, BarkFineModel
161
+
162
+ >>> # Initializing a Bark sub-module style configuration
163
+ >>> configuration = BarkFineConfig()
164
+
165
+ >>> # Initializing a model (with random weights) from the suno/bark style configuration
166
+ >>> model = BarkFineModel(configuration)
167
+
168
+ >>> # Accessing the model configuration
169
+ >>> configuration = model.config
170
+ ```""",
171
+ )
172
+ class BarkFineConfig(BarkSubModelConfig):
173
+ model_type = "fine_acoustics"
174
+ base_config_key = "fine_acoustics_config"
175
+
176
+ def __init__(self, tie_word_embeddings=True, n_codes_total=8, n_codes_given=1, **kwargs):
177
+ self.n_codes_total = n_codes_total
178
+ self.n_codes_given = n_codes_given
179
+
180
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
181
+
182
+
183
+ class BarkConfig(PretrainedConfig):
184
+ """
185
+ This is the configuration class to store the configuration of a [`BarkModel`]. It is used to instantiate a Bark
186
+ model according to the specified sub-models configurations, defining the model architecture.
187
+
188
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Bark
189
+ [suno/bark](https://huggingface.co/suno/bark) architecture.
190
+
191
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
192
+ documentation from [`PretrainedConfig`] for more information.
193
+
194
+ Args:
195
+ semantic_config ([`BarkSemanticConfig`], *optional*):
196
+ Configuration of the underlying semantic sub-model.
197
+ coarse_acoustics_config ([`BarkCoarseConfig`], *optional*):
198
+ Configuration of the underlying coarse acoustics sub-model.
199
+ fine_acoustics_config ([`BarkFineConfig`], *optional*):
200
+ Configuration of the underlying fine acoustics sub-model.
201
+ codec_config ([`AutoConfig`], *optional*):
202
+ Configuration of the underlying codec sub-model.
203
+
204
+ Example:
205
+
206
+ ```python
207
+ >>> from transformers import (
208
+ ... BarkSemanticConfig,
209
+ ... BarkCoarseConfig,
210
+ ... BarkFineConfig,
211
+ ... BarkModel,
212
+ ... BarkConfig,
213
+ ... AutoConfig,
214
+ ... )
215
+
216
+ >>> # Initializing Bark sub-modules configurations.
217
+ >>> semantic_config = BarkSemanticConfig()
218
+ >>> coarse_acoustics_config = BarkCoarseConfig()
219
+ >>> fine_acoustics_config = BarkFineConfig()
220
+ >>> codec_config = AutoConfig.from_pretrained("facebook/encodec_24khz")
221
+
222
+
223
+ >>> # Initializing a Bark module style configuration
224
+ >>> configuration = BarkConfig.from_sub_model_configs(
225
+ ... semantic_config, coarse_acoustics_config, fine_acoustics_config, codec_config
226
+ ... )
227
+
228
+ >>> # Initializing a model (with random weights)
229
+ >>> model = BarkModel(configuration)
230
+
231
+ >>> # Accessing the model configuration
232
+ >>> configuration = model.config
233
+ ```
234
+ """
235
+
236
+ model_type = "bark"
237
+ sub_configs = {
238
+ "semantic_config": BarkSemanticConfig,
239
+ "coarse_acoustics_config": BarkCoarseConfig,
240
+ "fine_acoustics_config": BarkFineConfig,
241
+ "codec_config": AutoConfig,
242
+ }
243
+
244
+ def __init__(
245
+ self,
246
+ semantic_config: Dict = None,
247
+ coarse_acoustics_config: Dict = None,
248
+ fine_acoustics_config: Dict = None,
249
+ codec_config: Dict = None,
250
+ initializer_range=0.02,
251
+ **kwargs,
252
+ ):
253
+ if semantic_config is None:
254
+ semantic_config = {}
255
+ logger.info("semantic_config is None. initializing the semantic model with default values.")
256
+
257
+ if coarse_acoustics_config is None:
258
+ coarse_acoustics_config = {}
259
+ logger.info("coarse_acoustics_config is None. initializing the coarse model with default values.")
260
+
261
+ if fine_acoustics_config is None:
262
+ fine_acoustics_config = {}
263
+ logger.info("fine_acoustics_config is None. initializing the fine model with default values.")
264
+
265
+ if codec_config is None:
266
+ codec_config = {}
267
+ logger.info("codec_config is None. initializing the codec model with default values.")
268
+
269
+ self.semantic_config = BarkSemanticConfig(**semantic_config)
270
+ self.coarse_acoustics_config = BarkCoarseConfig(**coarse_acoustics_config)
271
+ self.fine_acoustics_config = BarkFineConfig(**fine_acoustics_config)
272
+ codec_model_type = codec_config["model_type"] if "model_type" in codec_config else "encodec"
273
+ self.codec_config = CONFIG_MAPPING[codec_model_type](**codec_config)
274
+
275
+ self.initializer_range = initializer_range
276
+
277
+ super().__init__(**kwargs)
278
+
279
+ @classmethod
280
+ def from_sub_model_configs(
281
+ cls,
282
+ semantic_config: BarkSemanticConfig,
283
+ coarse_acoustics_config: BarkCoarseConfig,
284
+ fine_acoustics_config: BarkFineConfig,
285
+ codec_config: PretrainedConfig,
286
+ **kwargs,
287
+ ):
288
+ r"""
289
+ Instantiate a [`BarkConfig`] (or a derived class) from bark sub-models configuration.
290
+
291
+ Returns:
292
+ [`BarkConfig`]: An instance of a configuration object
293
+ """
294
+ return cls(
295
+ semantic_config=semantic_config.to_dict(),
296
+ coarse_acoustics_config=coarse_acoustics_config.to_dict(),
297
+ fine_acoustics_config=fine_acoustics_config.to_dict(),
298
+ codec_config=codec_config.to_dict(),
299
+ **kwargs,
300
+ )
301
+
302
+
303
+ __all__ = ["BarkCoarseConfig", "BarkConfig", "BarkFineConfig", "BarkSemanticConfig"]
lib/python3.12/site-packages/transformers/models/bark/generation_configuration_bark.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """BARK model generation configuration"""
16
+
17
+ import copy
18
+ from typing import Dict
19
+
20
+ from ...generation.configuration_utils import GenerationConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class BarkSemanticGenerationConfig(GenerationConfig):
28
+ model_type = "semantic"
29
+
30
+ def __init__(
31
+ self,
32
+ eos_token_id=10_000,
33
+ renormalize_logits=True,
34
+ max_new_tokens=768,
35
+ output_scores=False,
36
+ return_dict_in_generate=False,
37
+ output_hidden_states=False,
38
+ output_attentions=False,
39
+ temperature=1.0,
40
+ do_sample=False,
41
+ text_encoding_offset=10_048,
42
+ text_pad_token=129_595,
43
+ semantic_infer_token=129_599,
44
+ semantic_vocab_size=10_000,
45
+ max_input_semantic_length=256,
46
+ semantic_rate_hz=49.9,
47
+ min_eos_p=None,
48
+ **kwargs,
49
+ ):
50
+ """Class that holds a generation configuration for [`BarkSemanticModel`].
51
+
52
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
53
+ documentation from [`GenerationConfig`] for more information.
54
+
55
+ Args:
56
+ eos_token_id (`int`, *optional*, defaults to 10_000):
57
+ The id of the *end-of-sequence* token.
58
+ renormalize_logits (`bool`, *optional*, defaults to `True`):
59
+ Whether to renormalize the logits after applying all the logits processors (including the
60
+ custom ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the
61
+ score logits are normalized but some logit processors break the normalization.
62
+ max_new_tokens (`int`, *optional*, defaults to 768):
63
+ The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
64
+ output_scores (`bool`, *optional*, defaults to `False`):
65
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
66
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
67
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
68
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
69
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
70
+ for more details.
71
+ output_attentions (`bool`, *optional*, defaults to `False`):
72
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
73
+ returned tensors for more details.
74
+ temperature (`float`, *optional*, defaults to 1.0):
75
+ The value used to modulate the next token probabilities.
76
+ do_sample (`bool`, *optional*, defaults to `False`):
77
+ Whether or not to use sampling ; use greedy decoding otherwise.
78
+ text_encoding_offset (`int`, *optional*, defaults to 10_048):
79
+ Text encoding offset.
80
+ text_pad_token (`int`, *optional*, defaults to 129_595):
81
+ Text pad token.
82
+ semantic_infer_token (`int`, *optional*, defaults to 129_599):
83
+ Semantic infer token.
84
+ semantic_vocab_size (`int`, *optional*, defaults to 10_000):
85
+ Semantic vocab size.
86
+ max_input_semantic_length (`int`, *optional*, defaults to 256):
87
+ Max length of semantic input vector.
88
+ semantic_rate_hz (`float`, *optional*, defaults to 49.9):
89
+ Semantic rate in Hertz.
90
+ min_eos_p (`float`, *optional*):
91
+ Minimum threshold of the probability of the EOS token for it to be sampled. This is an early stopping
92
+ strategy to mitigate potential unwanted generations at the end of a prompt. The original implementation
93
+ suggests a default value of 0.2.
94
+ """
95
+ super().__init__(
96
+ temperature=temperature,
97
+ do_sample=do_sample,
98
+ eos_token_id=eos_token_id,
99
+ renormalize_logits=renormalize_logits,
100
+ max_new_tokens=max_new_tokens,
101
+ output_scores=output_scores,
102
+ return_dict_in_generate=return_dict_in_generate,
103
+ output_hidden_states=output_hidden_states,
104
+ output_attentions=output_attentions,
105
+ **kwargs,
106
+ )
107
+
108
+ self.text_encoding_offset = text_encoding_offset
109
+ self.text_pad_token = text_pad_token
110
+ self.semantic_pad_token = eos_token_id
111
+ self.semantic_infer_token = semantic_infer_token
112
+ self.semantic_vocab_size = semantic_vocab_size
113
+ self.max_input_semantic_length = max_input_semantic_length
114
+ self.semantic_rate_hz = semantic_rate_hz
115
+ self.min_eos_p = min_eos_p
116
+
117
+
118
+ class BarkCoarseGenerationConfig(GenerationConfig):
119
+ model_type = "coarse_acoustics"
120
+
121
+ def __init__(
122
+ self,
123
+ renormalize_logits=True,
124
+ output_scores=False,
125
+ return_dict_in_generate=False,
126
+ output_hidden_states=False,
127
+ output_attentions=False,
128
+ temperature=1.0,
129
+ do_sample=False,
130
+ coarse_semantic_pad_token=12_048,
131
+ coarse_rate_hz=75,
132
+ n_coarse_codebooks=2,
133
+ coarse_infer_token=12_050,
134
+ max_coarse_input_length=256,
135
+ max_coarse_history: int = 630,
136
+ sliding_window_len: int = 60,
137
+ **kwargs,
138
+ ):
139
+ """Class that holds a generation configuration for [`BarkCoarseModel`].
140
+
141
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
142
+ documentation from [`GenerationConfig`] for more information.
143
+
144
+ Args:
145
+ renormalize_logits (`bool`, *optional*, defaults to `True`):
146
+ Whether to renormalize the logits after applying all the logits processors (including the
147
+ custom ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the
148
+ score logits are normalized but some logit processors break the normalization.
149
+ output_scores (`bool`, *optional*, defaults to `False`):
150
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
151
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
152
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
153
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
154
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
155
+ for more details.
156
+ output_attentions (`bool`, *optional*, defaults to `False`):
157
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
158
+ returned tensors for more details.
159
+ temperature (`float`, *optional*, defaults to 1.0):
160
+ The value used to modulate the next token probabilities.
161
+ do_sample (`bool`, *optional*, defaults to `False`):
162
+ Whether or not to use sampling ; use greedy decoding otherwise.
163
+ coarse_semantic_pad_token (`int`, *optional*, defaults to 12_048):
164
+ Coarse semantic pad token.
165
+ coarse_rate_hz (`int`, *optional*, defaults to 75):
166
+ Coarse rate in Hertz.
167
+ n_coarse_codebooks (`int`, *optional*, defaults to 2):
168
+ Number of coarse codebooks.
169
+ coarse_infer_token (`int`, *optional*, defaults to 12_050):
170
+ Coarse infer token.
171
+ max_coarse_input_length (`int`, *optional*, defaults to 256):
172
+ Max length of input coarse vector.
173
+ max_coarse_history (`int`, *optional*, defaults to 630):
174
+ Max length of the output of the coarse acoustics model used in the fine generation step.
175
+ sliding_window_len (`int`, *optional*, defaults to 60):
176
+ The coarse generation step uses a sliding window to generate raw audio.
177
+ """
178
+ super().__init__(
179
+ temperature=temperature,
180
+ do_sample=do_sample,
181
+ renormalize_logits=renormalize_logits,
182
+ output_scores=output_scores,
183
+ return_dict_in_generate=return_dict_in_generate,
184
+ output_hidden_states=output_hidden_states,
185
+ output_attentions=output_attentions,
186
+ **kwargs,
187
+ )
188
+
189
+ self.coarse_semantic_pad_token = coarse_semantic_pad_token
190
+ self.coarse_rate_hz = coarse_rate_hz
191
+ self.n_coarse_codebooks = n_coarse_codebooks
192
+ self.coarse_infer_token = coarse_infer_token
193
+ self.max_coarse_input_length = max_coarse_input_length
194
+ self.max_coarse_history = max_coarse_history
195
+ self.sliding_window_len = sliding_window_len
196
+
197
+
198
+ class BarkFineGenerationConfig(GenerationConfig):
199
+ model_type = "fine_acoustics"
200
+
201
+ def __init__(
202
+ self,
203
+ temperature=1.0,
204
+ max_fine_history_length=512,
205
+ max_fine_input_length=1024,
206
+ n_fine_codebooks=8,
207
+ **kwargs,
208
+ ):
209
+ """Class that holds a generation configuration for [`BarkFineModel`].
210
+
211
+ [`BarkFineModel`] is an autoencoder model, so should not usually be used for generation. However, under the
212
+ hood, it uses `temperature` when used by [`BarkModel`]
213
+
214
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
215
+ documentation from [`GenerationConfig`] for more information.
216
+
217
+ Args:
218
+ temperature (`float`, *optional*):
219
+ The value used to modulate the next token probabilities.
220
+ max_fine_history_length (`int`, *optional*, defaults to 512):
221
+ Max length of the fine history vector.
222
+ max_fine_input_length (`int`, *optional*, defaults to 1024):
223
+ Max length of fine input vector.
224
+ n_fine_codebooks (`int`, *optional*, defaults to 8):
225
+ Number of codebooks used.
226
+ """
227
+ super().__init__(temperature=temperature)
228
+
229
+ self.max_fine_history_length = max_fine_history_length
230
+ self.max_fine_input_length = max_fine_input_length
231
+ self.n_fine_codebooks = n_fine_codebooks
232
+
233
+ def validate(self, **kwargs):
234
+ """
235
+ Overrides GenerationConfig.validate because BarkFineGenerationConfig don't use any parameters outside
236
+ temperature.
237
+ """
238
+ pass
239
+
240
+
241
+ class BarkGenerationConfig(GenerationConfig):
242
+ model_type = "bark"
243
+ is_composition = True
244
+
245
+ # TODO (joao): nested from_dict
246
+
247
+ def __init__(
248
+ self,
249
+ semantic_config: Dict = None,
250
+ coarse_acoustics_config: Dict = None,
251
+ fine_acoustics_config: Dict = None,
252
+ sample_rate=24_000,
253
+ codebook_size=1024,
254
+ **kwargs,
255
+ ):
256
+ """Class that holds a generation configuration for [`BarkModel`].
257
+
258
+ The [`BarkModel`] does not have a `generate` method, but uses this class to generate speeches with a nested
259
+ [`BarkGenerationConfig`] which uses [`BarkSemanticGenerationConfig`], [`BarkCoarseGenerationConfig`],
260
+ [`BarkFineGenerationConfig`].
261
+
262
+ This configuration inherit from [`GenerationConfig`] and can be used to control the model generation. Read the
263
+ documentation from [`GenerationConfig`] for more information.
264
+
265
+ Args:
266
+ semantic_config (`Dict`, *optional*):
267
+ Semantic generation configuration.
268
+ coarse_acoustics_config (`Dict`, *optional*):
269
+ Coarse generation configuration.
270
+ fine_acoustics_config (`Dict`, *optional*):
271
+ Fine generation configuration.
272
+ sample_rate (`int`, *optional*, defaults to 24_000):
273
+ Sample rate.
274
+ codebook_size (`int`, *optional*, defaults to 1024):
275
+ Vector length for each codebook.
276
+ """
277
+ if semantic_config is None:
278
+ semantic_config = {}
279
+ logger.info("semantic_config is None. initializing the semantic model with default values.")
280
+
281
+ if coarse_acoustics_config is None:
282
+ coarse_acoustics_config = {}
283
+ logger.info("coarse_acoustics_config is None. initializing the coarse model with default values.")
284
+
285
+ if fine_acoustics_config is None:
286
+ fine_acoustics_config = {}
287
+ logger.info("fine_acoustics_config is None. initializing the fine model with default values.")
288
+
289
+ self.semantic_config = BarkSemanticGenerationConfig(**semantic_config)
290
+ self.coarse_acoustics_config = BarkCoarseGenerationConfig(**coarse_acoustics_config)
291
+ self.fine_acoustics_config = BarkFineGenerationConfig(**fine_acoustics_config)
292
+
293
+ self.sample_rate = sample_rate
294
+ self.codebook_size = codebook_size
295
+
296
+ @classmethod
297
+ def from_sub_model_configs(
298
+ cls,
299
+ semantic_config: BarkSemanticGenerationConfig,
300
+ coarse_acoustics_config: BarkCoarseGenerationConfig,
301
+ fine_acoustics_config: BarkFineGenerationConfig,
302
+ **kwargs,
303
+ ):
304
+ r"""
305
+ Instantiate a [`BarkGenerationConfig`] (or a derived class) from bark sub-models generation configuration.
306
+
307
+ Returns:
308
+ [`BarkGenerationConfig`]: An instance of a configuration object
309
+ """
310
+ return cls(
311
+ semantic_config=semantic_config.to_dict(),
312
+ coarse_acoustics_config=coarse_acoustics_config.to_dict(),
313
+ fine_acoustics_config=fine_acoustics_config.to_dict(),
314
+ **kwargs,
315
+ )
316
+
317
+ def to_dict(self):
318
+ """
319
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
320
+
321
+ Returns:
322
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
323
+ """
324
+ output = copy.deepcopy(self.__dict__)
325
+
326
+ output["semantic_config"] = self.semantic_config.to_dict()
327
+ output["coarse_acoustics_config"] = self.coarse_acoustics_config.to_dict()
328
+ output["fine_acoustics_config"] = self.fine_acoustics_config.to_dict()
329
+
330
+ output["model_type"] = self.__class__.model_type
331
+ return output
lib/python3.12/site-packages/transformers/models/bark/modeling_bark.py ADDED
@@ -0,0 +1,1848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch BARK model."""
16
+
17
+ import math
18
+ from typing import Dict, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import functional as F
24
+
25
+ from ...generation import GenerationMixin
26
+ from ...generation.logits_process import (
27
+ AlternatingCodebooksLogitsProcessor,
28
+ BarkEosPrioritizerLogitsProcessor,
29
+ SuppressTokensLogitsProcessor,
30
+ )
31
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
32
+ from ...modeling_flash_attention_utils import flash_attn_supports_top_left_mask, is_flash_attn_available
33
+ from ...modeling_outputs import CausalLMOutputWithPast, MaskedLMOutput
34
+ from ...modeling_utils import PreTrainedModel, get_parameter_device
35
+ from ...utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_accelerate_available,
39
+ logging,
40
+ )
41
+ from ..auto import AutoModel
42
+ from .configuration_bark import (
43
+ BarkCoarseConfig,
44
+ BarkConfig,
45
+ BarkFineConfig,
46
+ BarkSemanticConfig,
47
+ BarkSubModelConfig,
48
+ )
49
+ from .generation_configuration_bark import (
50
+ BarkCoarseGenerationConfig,
51
+ BarkFineGenerationConfig,
52
+ BarkSemanticGenerationConfig,
53
+ )
54
+
55
+
56
+ if is_flash_attn_available():
57
+ from ...modeling_flash_attention_utils import _flash_attention_forward
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+
63
+ _CHECKPOINT_FOR_DOC = "suno/bark-small"
64
+ _CONFIG_FOR_DOC = "BarkConfig"
65
+
66
+
67
+ class BarkSelfAttention(nn.Module):
68
+ # adapted from GPTNeoSelfAttention and Bark code
69
+ # BarkSelfAttention can have two attention type, i.e full attention or causal attention
70
+
71
+ def __init__(self, config, is_causal=False):
72
+ super().__init__()
73
+
74
+ # regularization
75
+ self.dropout = config.dropout
76
+ self.attn_dropout = nn.Dropout(config.dropout)
77
+ self.resid_dropout = nn.Dropout(config.dropout)
78
+
79
+ self.embed_dim = config.hidden_size
80
+ self.num_heads = config.num_heads
81
+ self.head_dim = self.embed_dim // self.num_heads
82
+
83
+ if config.hidden_size % config.num_heads != 0:
84
+ raise ValueError(
85
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
86
+ f" {self.num_heads})."
87
+ )
88
+
89
+ # key, query, value projections for all heads, but in a batch
90
+ self.att_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=config.bias)
91
+ # output projection
92
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.bias)
93
+
94
+ self.is_causal = is_causal
95
+ if is_causal:
96
+ block_size = config.block_size
97
+ bias = torch.tril(torch.ones((block_size, block_size), dtype=bool)).view(1, 1, block_size, block_size)
98
+ self.register_buffer("bias", bias)
99
+
100
+ # Copied from transformers.models.gpt_neo.modeling_gpt_neo.GPTNeoSelfAttention._split_heads
101
+ def _split_heads(self, tensor, num_heads, attn_head_size):
102
+ """
103
+ Splits hidden_size dim into attn_head_size and num_heads
104
+ """
105
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
106
+ tensor = tensor.view(new_shape)
107
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
108
+
109
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
110
+ """
111
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
112
+ """
113
+
114
+ # re-assemble all head outputs side by side
115
+ # (batch, num_heads, seq_len, attn_head_size) -> (batch, seq_len, num_heads*attn_head_size)
116
+ tensor = tensor.transpose(1, 2).contiguous()
117
+ tensor = tensor.view(tensor.size()[:-2] + (num_heads * attn_head_size,))
118
+
119
+ return tensor
120
+
121
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
122
+ # unlike GPTNeo's SelfAttention, divide by the square root of the dimension of the query and the key
123
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * (1.0 / math.sqrt(self.head_dim))
124
+
125
+ if self.is_causal:
126
+ query_length, key_length = query.size(-2), key.size(-2)
127
+
128
+ # fill the upper left part of the attention weights with inf
129
+ attn_weights = attn_weights.masked_fill(
130
+ self.bias[:, :, key_length - query_length : key_length, :key_length] == 0,
131
+ torch.finfo(attn_weights.dtype).min,
132
+ )
133
+
134
+ if attention_mask is not None:
135
+ # Apply the attention mask
136
+ attn_weights = attn_weights + attention_mask
137
+
138
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
139
+ attn_weights = attn_weights.to(value.dtype)
140
+ attn_weights = self.attn_dropout(attn_weights)
141
+
142
+ # Mask heads if we want to
143
+ if head_mask is not None:
144
+ attn_weights = attn_weights * head_mask
145
+
146
+ # (batch, num_heads, seq_len, seq_len) x (batch, num_heads, seq_len, attn_head_size)
147
+ # -> (batch, num_heads, seq_len, attn_head_size)
148
+ attn_output = torch.matmul(attn_weights, value)
149
+
150
+ return attn_output, attn_weights
151
+
152
+ def forward(
153
+ self,
154
+ hidden_states,
155
+ attention_mask=None,
156
+ past_key_values=None,
157
+ head_mask=None,
158
+ use_cache=False,
159
+ output_attentions=False,
160
+ ):
161
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
162
+ query, key, value = self.att_proj(hidden_states).split(self.embed_dim, dim=2)
163
+
164
+ query = self._split_heads(query, self.num_heads, self.head_dim)
165
+ key = self._split_heads(key, self.num_heads, self.head_dim)
166
+ value = self._split_heads(value, self.num_heads, self.head_dim)
167
+
168
+ if past_key_values is not None:
169
+ past_key = past_key_values[0]
170
+ past_value = past_key_values[1]
171
+ key = torch.cat((past_key, key), dim=-2)
172
+ value = torch.cat((past_value, value), dim=-2)
173
+
174
+ if use_cache is True:
175
+ present = (key, value)
176
+ else:
177
+ present = None
178
+
179
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
180
+
181
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
182
+ attn_output = self.out_proj(attn_output)
183
+ attn_output = self.resid_dropout(attn_output)
184
+
185
+ outputs = (attn_output, present)
186
+ if output_attentions:
187
+ outputs += (attn_weights,)
188
+
189
+ return outputs
190
+
191
+
192
+ class BarkSelfFlashAttention2(BarkSelfAttention):
193
+ """
194
+ Bark flash attention module. This module inherits from `BarkSelfAttention` as the weights of the module stays
195
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
196
+ flash attention and deal with padding tokens in case the input contains any of them.
197
+ """
198
+
199
+ def __init__(self, *args, **kwargs):
200
+ super().__init__(*args, **kwargs)
201
+
202
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
203
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
204
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
205
+ self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
206
+
207
+ def _split_heads(self, tensor, num_heads, attn_head_size):
208
+ """
209
+ Splits hidden_size dim into attn_head_size and num_heads
210
+ """
211
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
212
+ tensor = tensor.view(new_shape)
213
+ # Flash attention requires the input to have the shape
214
+ # batch_size x seq_length x head_dim x hidden_dim - (batch, seq_length, head, head_features)
215
+ return tensor
216
+
217
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
218
+ """
219
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
220
+ """
221
+ # re-assemble all head outputs side by side
222
+ # (batch, seq_len, num_heads, attn_head_size) -> (batch, seq_len, num_heads*attn_head_size)
223
+ tensor = tensor.view(tensor.size()[:-2] + (num_heads * attn_head_size,))
224
+ return tensor
225
+
226
+ def forward(
227
+ self,
228
+ hidden_states,
229
+ attention_mask=None,
230
+ past_key_values=None,
231
+ head_mask=None,
232
+ use_cache=False,
233
+ output_attentions=False,
234
+ ):
235
+ batch_size, query_len, _ = hidden_states.size()
236
+
237
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
238
+ query, key, value = self.att_proj(hidden_states).split(self.embed_dim, dim=2)
239
+
240
+ query = self._split_heads(query, self.num_heads, self.head_dim)
241
+ key = self._split_heads(key, self.num_heads, self.head_dim)
242
+ value = self._split_heads(value, self.num_heads, self.head_dim)
243
+
244
+ if past_key_values is not None:
245
+ # (batch, head, seq_length, head_features) -> (batch, seq_length, head, head_features)
246
+ past_key = past_key_values[0].transpose(1, 2)
247
+ past_value = past_key_values[1].transpose(1, 2)
248
+ # and merge on seq_length
249
+ key = torch.cat((past_key, key), dim=1)
250
+ value = torch.cat((past_value, value), dim=1)
251
+
252
+ if use_cache is True:
253
+ # (batch, head, seq_length, head_features)
254
+ present = (key.transpose(1, 2), value.transpose(1, 2))
255
+ else:
256
+ present = None
257
+
258
+ attn_output = _flash_attention_forward(
259
+ query,
260
+ key,
261
+ value,
262
+ attention_mask,
263
+ query_len,
264
+ dropout=self.dropout if self.training else 0.0,
265
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
266
+ is_causal=self.is_causal,
267
+ )
268
+
269
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
270
+ attn_output = self.out_proj(attn_output)
271
+ attn_output = self.resid_dropout(attn_output)
272
+
273
+ outputs = (attn_output, present)
274
+ if output_attentions:
275
+ attn_weights = None
276
+ outputs += (attn_weights,)
277
+
278
+ return outputs
279
+
280
+
281
+ BARK_ATTENTION_CLASSES = {
282
+ "eager": BarkSelfAttention,
283
+ "flash_attention_2": BarkSelfFlashAttention2,
284
+ }
285
+
286
+
287
+ class BarkLayerNorm(nn.Module):
288
+ """LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False."""
289
+
290
+ def __init__(self, hidden_size, bias=True):
291
+ super().__init__()
292
+ self.weight = nn.Parameter(torch.ones(hidden_size))
293
+ self.bias = nn.Parameter(torch.zeros(hidden_size)) if bias else None
294
+
295
+ def forward(self, input):
296
+ return F.layer_norm(input, self.weight.shape, self.weight, self.bias, eps=1e-5)
297
+
298
+
299
+ class BarkMLP(nn.Module):
300
+ def __init__(self, config):
301
+ super().__init__()
302
+ self.in_proj = nn.Linear(config.hidden_size, 4 * config.hidden_size, bias=config.bias)
303
+ self.out_proj = nn.Linear(4 * config.hidden_size, config.hidden_size, bias=config.bias)
304
+ self.dropout = nn.Dropout(config.dropout)
305
+ self.gelu = nn.GELU()
306
+
307
+ def forward(self, hidden_states):
308
+ hidden_states = self.in_proj(hidden_states)
309
+ hidden_states = self.gelu(hidden_states)
310
+ hidden_states = self.out_proj(hidden_states)
311
+ hidden_states = self.dropout(hidden_states)
312
+ return hidden_states
313
+
314
+
315
+ class BarkBlock(nn.Module):
316
+ def __init__(self, config, is_causal=False):
317
+ super().__init__()
318
+
319
+ if is_causal:
320
+ # if causal, uses handmade LayerNorm, so that the layerNorm bias is optional
321
+ # this handmade layerNorm is used to stick with Bark choice of leaving optional bias in
322
+ # AutoRegressive models (corresponding to the "Text" and the "Coarse" modules)
323
+ self.layernorm_1 = BarkLayerNorm(config.hidden_size, bias=config.bias)
324
+ self.layernorm_2 = BarkLayerNorm(config.hidden_size, bias=config.bias)
325
+ else:
326
+ self.layernorm_1 = nn.LayerNorm(config.hidden_size)
327
+ self.layernorm_2 = nn.LayerNorm(config.hidden_size)
328
+
329
+ self.attn = BARK_ATTENTION_CLASSES[config._attn_implementation](config, is_causal=is_causal)
330
+
331
+ self.mlp = BarkMLP(config)
332
+
333
+ def forward(
334
+ self,
335
+ hidden_states,
336
+ past_key_values=None,
337
+ attention_mask=None,
338
+ head_mask=None,
339
+ use_cache=False,
340
+ output_attentions=False,
341
+ ):
342
+ intermediary_hidden_states = self.layernorm_1(hidden_states)
343
+
344
+ attn_outputs = self.attn(
345
+ intermediary_hidden_states,
346
+ past_key_values=past_key_values,
347
+ attention_mask=attention_mask,
348
+ head_mask=head_mask,
349
+ use_cache=use_cache,
350
+ output_attentions=output_attentions,
351
+ )
352
+
353
+ attn_output = attn_outputs[0] # output_attn: output, present_key_values, (attn_weights)
354
+ outputs = attn_outputs[1:]
355
+
356
+ intermediary_hidden_states = hidden_states + attn_output
357
+ intermediary_hidden_states = intermediary_hidden_states + self.mlp(
358
+ self.layernorm_2(intermediary_hidden_states)
359
+ )
360
+
361
+ if use_cache:
362
+ outputs = (intermediary_hidden_states,) + outputs
363
+ else:
364
+ outputs = (intermediary_hidden_states,) + outputs[1:]
365
+
366
+ return outputs # hidden_states, ((present), attentions)
367
+
368
+
369
+ class BarkPreTrainedModel(PreTrainedModel):
370
+ """
371
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
372
+ models.
373
+ """
374
+
375
+ config_class = BarkConfig
376
+ supports_gradient_checkpointing = False
377
+ _supports_flash_attn_2 = True
378
+
379
+ def _init_weights(self, module):
380
+ """Initialize the weights."""
381
+ if isinstance(module, (nn.Linear,)):
382
+ # Slightly different from the TF version which uses truncated_normal for initialization
383
+ # cf https://github.com/pytorch/pytorch/pull/5617
384
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
385
+ if module.bias is not None:
386
+ module.bias.data.zero_()
387
+ elif isinstance(module, nn.Embedding):
388
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
389
+ if module.padding_idx is not None:
390
+ module.weight.data[module.padding_idx].zero_()
391
+ elif isinstance(module, nn.LayerNorm):
392
+ module.bias.data.zero_()
393
+ module.weight.data.fill_(1.0)
394
+
395
+ def __init__(self, *inputs, **kwargs):
396
+ super().__init__(*inputs, **kwargs)
397
+
398
+ @property
399
+ def device(self) -> torch.device:
400
+ """
401
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
402
+ device).
403
+ """
404
+
405
+ # if has _hf_hook, has been offloaded so the device has to be found in the hook
406
+ if not hasattr(self, "_hf_hook"):
407
+ return get_parameter_device(self)
408
+ for module in self.modules():
409
+ if (
410
+ hasattr(module, "_hf_hook")
411
+ and hasattr(module._hf_hook, "execution_device")
412
+ and module._hf_hook.execution_device is not None
413
+ ):
414
+ return torch.device(module._hf_hook.execution_device)
415
+
416
+ return get_parameter_device(self)
417
+
418
+
419
+ BARK_MODEL_START_DOCSTRING = """
420
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
421
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
422
+ etc.)
423
+
424
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
425
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
426
+ and behavior.
427
+
428
+ Parameters:
429
+ config ([`{config}`]):
430
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
431
+ load the weights associated with the model, only the configuration. Check out the
432
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
433
+ """
434
+
435
+
436
+ BARK_START_DOCSTRING = r"""
437
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
438
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
439
+ etc.)
440
+
441
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
442
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
443
+ and behavior.
444
+
445
+ Parameters:
446
+ config ([`BarkConfig`]):
447
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
448
+ load the weights associated with the model, only the configuration. Check out the
449
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
450
+ """
451
+
452
+
453
+ BARK_FINE_INPUTS_DOCSTRING = r"""
454
+ Args:
455
+ codebook_idx (`int`):
456
+ Index of the codebook that will be predicted.
457
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, number_of_codebooks)`):
458
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
459
+ it. Initially, indices of the first two codebooks are obtained from the `coarse` sub-model. The rest is
460
+ predicted recursively by attending the previously predicted channels. The model predicts on windows of
461
+ length 1024.
462
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
463
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
464
+
465
+ - 1 for tokens that are **not masked**,
466
+ - 0 for tokens that are **masked**.
467
+
468
+ [What are attention masks?](../glossary#attention-mask)
469
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
470
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
471
+ config.max_position_embeddings - 1]`.
472
+
473
+ [What are position IDs?](../glossary#position-ids)
474
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
475
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
476
+
477
+ - 1 indicates the head is **not masked**,
478
+ - 0 indicates the head is **masked**.
479
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): NOT IMPLEMENTED YET.
480
+ input_embeds (`torch.FloatTensor` of shape `(batch_size, input_sequence_length, hidden_size)`, *optional*):
481
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. If
482
+ `past_key_values` is used, optionally only the last `input_embeds` have to be input (see
483
+ `past_key_values`). This is useful if you want more control over how to convert `input_ids` indices into
484
+ associated vectors than the model's internal embedding lookup matrix.
485
+ output_attentions (`bool`, *optional*):
486
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
487
+ tensors for more detail.
488
+ output_hidden_states (`bool`, *optional*):
489
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
490
+ more detail.
491
+ return_dict (`bool`, *optional*):
492
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
493
+ """
494
+
495
+ BARK_CAUSAL_MODEL_INPUTS_DOCSTRING = r"""
496
+ Args:
497
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
498
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
499
+ it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
500
+ [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids)
501
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache` is passed or when `config.use_cache=True`):
502
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
503
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`.
504
+
505
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
506
+ `past_key_values` input) to speed up sequential decoding.
507
+
508
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
509
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
510
+ `input_ids` of shape `(batch_size, sequence_length)`.
511
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
512
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
513
+
514
+ - 1 for tokens that are **not masked**,
515
+ - 0 for tokens that are **masked**.
516
+
517
+ [What are attention masks?](../glossary#attention-mask)
518
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
519
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
520
+ config.max_position_embeddings - 1]`.
521
+
522
+ [What are position IDs?](../glossary#position-ids)
523
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
524
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
525
+
526
+ - 1 indicates the head is **not masked**,
527
+ - 0 indicates the head is **masked**.
528
+ input_embeds (`torch.FloatTensor` of shape `(batch_size, input_sequence_length, hidden_size)`, *optional*):
529
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
530
+ Here, due to `Bark` particularities, if `past_key_values` is used, `input_embeds` will be ignored and you
531
+ have to use `input_ids`. If `past_key_values` is not used and `use_cache` is set to `True`, `input_embeds`
532
+ is used in priority instead of `input_ids`.
533
+ use_cache (`bool`, *optional*):
534
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
535
+ `past_key_values`).
536
+ output_attentions (`bool`, *optional*):
537
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
538
+ tensors for more detail.
539
+ output_hidden_states (`bool`, *optional*):
540
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
541
+ more detail.
542
+ return_dict (`bool`, *optional*):
543
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
544
+ """
545
+
546
+
547
+ # GPT2-like autoregressive model
548
+ class BarkCausalModel(BarkPreTrainedModel, GenerationMixin):
549
+ config_class = BarkSubModelConfig
550
+
551
+ def __init__(self, config):
552
+ super().__init__(config)
553
+ self.config = config
554
+
555
+ # initialize as an autoregressive GPT-like model
556
+ self.input_embeds_layer = nn.Embedding(config.input_vocab_size, config.hidden_size)
557
+ self.position_embeds_layer = nn.Embedding(config.block_size, config.hidden_size)
558
+
559
+ self.drop = nn.Dropout(config.dropout)
560
+
561
+ self.layers = nn.ModuleList([BarkBlock(config, is_causal=True) for _ in range(config.num_layers)])
562
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
563
+
564
+ self.layernorm_final = BarkLayerNorm(config.hidden_size, bias=config.bias)
565
+
566
+ self.lm_head = nn.Linear(config.hidden_size, config.output_vocab_size, bias=False)
567
+ self.gradient_checkpointing = False
568
+
569
+ # Initialize weights and apply final processing
570
+ self.post_init()
571
+
572
+ def get_input_embeddings(self):
573
+ return self.input_embeds_layer
574
+
575
+ def set_input_embeddings(self, new_embeddings):
576
+ self.input_embeds_layer = new_embeddings
577
+
578
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
579
+ # Overwritten -- bark has a model-specific hack
580
+ input_embeds = kwargs.get("input_embeds", None)
581
+
582
+ attention_mask = kwargs.get("attention_mask", None)
583
+ position_ids = kwargs.get("position_ids", None)
584
+
585
+ if past_key_values is not None:
586
+ # Omit tokens covered by past_key_values
587
+ seq_len = input_ids.shape[1]
588
+ past_length = past_key_values[0][0].shape[2]
589
+
590
+ # Some generation methods already pass only the last input ID
591
+ if input_ids.shape[1] > past_length:
592
+ remove_prefix_length = past_length
593
+ else:
594
+ # Default to old behavior: keep only final ID
595
+ remove_prefix_length = input_ids.shape[1] - 1
596
+
597
+ input_ids = input_ids[:, remove_prefix_length:]
598
+
599
+ # input_embeds have already been used and is not required anymore
600
+ input_embeds = None
601
+ else:
602
+ if input_embeds is not None and kwargs.get("use_cache"):
603
+ seq_len = input_embeds.shape[1]
604
+ else:
605
+ seq_len = input_ids.shape[1]
606
+
607
+ # ensure that attention_mask and position_ids shapes are aligned with the weird Bark hack of reducing
608
+ # sequence length on the first forward pass
609
+ if attention_mask is not None:
610
+ attention_mask = attention_mask[:, :seq_len]
611
+ if position_ids is not None:
612
+ position_ids = position_ids[:, :seq_len]
613
+
614
+ if attention_mask is not None and position_ids is None:
615
+ # create position_ids on the fly for batch generation
616
+ position_ids = attention_mask.long().cumsum(-1) - 1
617
+ position_ids.masked_fill_(attention_mask == 0, 1)
618
+ if past_key_values:
619
+ position_ids = position_ids[:, -input_ids.shape[1] :]
620
+ else:
621
+ position_ids = None
622
+
623
+ if input_embeds is not None and kwargs.get("use_cache"):
624
+ return {
625
+ "input_ids": None,
626
+ "input_embeds": input_embeds,
627
+ "past_key_values": past_key_values,
628
+ "use_cache": kwargs.get("use_cache"),
629
+ "position_ids": position_ids,
630
+ "attention_mask": attention_mask,
631
+ }
632
+ return {
633
+ "input_ids": input_ids,
634
+ "past_key_values": past_key_values,
635
+ "use_cache": kwargs.get("use_cache"),
636
+ "position_ids": position_ids,
637
+ "attention_mask": attention_mask,
638
+ }
639
+
640
+ @add_start_docstrings_to_model_forward(BARK_CAUSAL_MODEL_INPUTS_DOCSTRING)
641
+ def forward(
642
+ self,
643
+ input_ids: Optional[torch.Tensor] = None,
644
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
645
+ attention_mask: Optional[torch.Tensor] = None,
646
+ position_ids: Optional[torch.Tensor] = None,
647
+ head_mask: Optional[torch.Tensor] = None,
648
+ labels: Optional[torch.LongTensor] = None,
649
+ input_embeds: Optional[torch.Tensor] = None,
650
+ use_cache: Optional[bool] = None,
651
+ output_attentions: Optional[bool] = None,
652
+ output_hidden_states: Optional[bool] = None,
653
+ return_dict: Optional[bool] = None,
654
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithPast]:
655
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
656
+ output_hidden_states = (
657
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
658
+ )
659
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
660
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
661
+
662
+ loss = None
663
+ if labels is not None:
664
+ raise NotImplementedError(
665
+ "Training is not implemented yet for Bark - ensure you do not pass `labels` to the model."
666
+ )
667
+
668
+ # Verify if input_embeds already exists
669
+ # then compute embeddings.
670
+ if input_ids is not None and input_embeds is not None:
671
+ raise ValueError("You cannot specify both input_ids and input_embeds at the same time")
672
+ elif input_embeds is not None and past_key_values is None:
673
+ # we want to return the input_embeds in priority so that it is in line with a weird hack
674
+ # of Bark which concatenate two bits of the input_embeds on the first forward pass of the semantic model
675
+ pass
676
+ elif input_ids is not None:
677
+ input_embeds = self.input_embeds_layer(input_ids) # token embeddings of shape (b, t, n_embd)
678
+ elif input_embeds is not None:
679
+ pass
680
+ else:
681
+ raise ValueError("You have to specify either input_ids or input_embeds")
682
+
683
+ input_shape = input_embeds.size()[:-1]
684
+ batch_size = input_embeds.shape[0]
685
+ seq_length = input_shape[-1]
686
+
687
+ device = input_ids.device if input_ids is not None else input_embeds.device
688
+
689
+ if past_key_values is None:
690
+ past_length = 0
691
+ past_key_values = tuple([None] * len(self.layers))
692
+ else:
693
+ past_length = past_key_values[0][0].size(-2)
694
+
695
+ if position_ids is None:
696
+ position_ids = torch.arange(past_length, seq_length + past_length, dtype=torch.long, device=device)
697
+ position_ids = position_ids.unsqueeze(0) # shape (1, seq_length)
698
+
699
+ position_embeds = self.position_embeds_layer(position_ids) # position embeddings of shape (1, t, n_embd)
700
+
701
+ # Attention mask.
702
+ if attention_mask is not None:
703
+ if batch_size <= 0:
704
+ raise ValueError("batch_size has to be defined and > 0")
705
+ if self._use_flash_attention_2:
706
+ attention_mask = attention_mask if 0 in attention_mask else None
707
+ else:
708
+ attention_mask = attention_mask.view(batch_size, -1)
709
+ # [bsz, to_seq_length] -> [bsz, 1, 1, to_seq_length]
710
+ # from_seq_length is 1 to easily broadcast
711
+ attention_mask = _prepare_4d_attention_mask(attention_mask, input_embeds.dtype, tgt_len=1)
712
+
713
+ # Prepare head mask if needed
714
+ # 1.0 in head_mask indicate we keep the head
715
+ # attention_probs has shape bsz x num_heads x N x N
716
+ # head_mask has shape num_layers x batch x num_heads x N x N
717
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
718
+
719
+ hidden_states = self.drop(input_embeds + position_embeds)
720
+ output_shape = input_shape + (hidden_states.size(-1),)
721
+
722
+ if self.gradient_checkpointing and self.training:
723
+ if use_cache:
724
+ logger.warning_once(
725
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
726
+ )
727
+ use_cache = False
728
+
729
+ present_key_values = () if use_cache else None
730
+ all_self_attentions = () if output_attentions else None
731
+ all_hidden_states = () if output_hidden_states else None
732
+
733
+ for i, (block, past_layer_key_values) in enumerate(zip(self.layers, past_key_values)):
734
+ if output_hidden_states:
735
+ all_hidden_states = all_hidden_states + (hidden_states,)
736
+
737
+ if self.gradient_checkpointing and self.training:
738
+ outputs = self._gradient_checkpointing_func(
739
+ block.__call__,
740
+ hidden_states,
741
+ None,
742
+ attention_mask,
743
+ head_mask[i],
744
+ use_cache,
745
+ output_attentions,
746
+ )
747
+ else:
748
+ outputs = block(
749
+ hidden_states,
750
+ past_key_values=past_layer_key_values,
751
+ attention_mask=attention_mask,
752
+ head_mask=head_mask[i],
753
+ use_cache=use_cache,
754
+ output_attentions=output_attentions,
755
+ )
756
+
757
+ hidden_states = outputs[0]
758
+
759
+ if use_cache:
760
+ present_key_values = present_key_values + (outputs[1],)
761
+
762
+ if output_attentions:
763
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
764
+
765
+ hidden_states = self.layernorm_final(hidden_states)
766
+
767
+ hidden_states = hidden_states.view(output_shape)
768
+
769
+ # Add last hidden state
770
+ if output_hidden_states:
771
+ all_hidden_states = all_hidden_states + (hidden_states,)
772
+
773
+ logits = self.lm_head(hidden_states)
774
+
775
+ if not return_dict:
776
+ return tuple(
777
+ v for v in [None, logits, present_key_values, all_hidden_states, all_self_attentions] if v is not None
778
+ )
779
+
780
+ return CausalLMOutputWithPast(
781
+ loss=loss,
782
+ logits=logits,
783
+ past_key_values=present_key_values,
784
+ hidden_states=all_hidden_states,
785
+ attentions=all_self_attentions,
786
+ )
787
+
788
+ @staticmethod
789
+ def _reorder_cache(
790
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
791
+ ) -> Tuple[Tuple[torch.Tensor]]:
792
+ """
793
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
794
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
795
+ beam_idx at every generation step.
796
+ """
797
+ # Necessary for beam_search
798
+ return tuple(
799
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
800
+ for layer_past in past_key_values
801
+ )
802
+
803
+
804
+ @add_start_docstrings(
805
+ """Bark semantic (or text) model. It shares the same architecture as the coarse model.
806
+ It is a GPT-2 like autoregressive model with a language modeling head on top.""",
807
+ BARK_MODEL_START_DOCSTRING.format(config="BarkSemanticConfig"),
808
+ )
809
+ class BarkSemanticModel(BarkCausalModel):
810
+ base_model_prefix = "semantic"
811
+ config_class = BarkSemanticConfig
812
+
813
+ def generate(
814
+ self,
815
+ input_ids: torch.Tensor,
816
+ semantic_generation_config: BarkSemanticGenerationConfig = None,
817
+ history_prompt: Optional[Dict[str, torch.Tensor]] = None,
818
+ attention_mask: Optional[torch.Tensor] = None,
819
+ **kwargs,
820
+ ) -> torch.LongTensor:
821
+ """
822
+ Generates text semantic tokens from an input prompt and an additional optional `Bark` speaker prompt.
823
+
824
+ Args:
825
+ input_ids (`Optional[torch.Tensor]` of shape (batch_size, seq_len), *optional*):
826
+ Input ids, i.e tokenized input sentences. Will be truncated up to
827
+ semantic_generation_config.max_input_semantic_length tokens. Note that the output audios will be as
828
+ long as the longest generation among the batch.
829
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
830
+ Generation config indicating how to generate the semantic tokens.
831
+ history_prompt (`Optional[Dict[str,torch.Tensor]]`, *optional*):
832
+ Optional `Bark` speaker prompt.
833
+ attention_mask (`Optional[torch.Tensor]`, *optional*):
834
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
835
+
836
+ - 1 for tokens that are **not masked**,
837
+ - 0 for tokens that are **masked**.
838
+
839
+ [What are attention masks?](../glossary#attention-mask)
840
+ Returns:
841
+ torch.LongTensor: Output semantic tokens.
842
+ """
843
+ if semantic_generation_config is None:
844
+ raise ValueError("`semantic_generation_config` has to be provided")
845
+
846
+ batch_size = input_ids.shape[0]
847
+
848
+ max_input_semantic_length = semantic_generation_config.max_input_semantic_length
849
+
850
+ input_ids = input_ids + semantic_generation_config.text_encoding_offset
851
+
852
+ if attention_mask is not None:
853
+ input_ids = input_ids.masked_fill((1 - attention_mask).bool(), semantic_generation_config.text_pad_token)
854
+
855
+ if history_prompt is not None:
856
+ semantic_history = history_prompt["semantic_prompt"][-max_input_semantic_length:]
857
+ semantic_history = nn.functional.pad(
858
+ semantic_history,
859
+ (0, max_input_semantic_length - len(semantic_history)),
860
+ value=semantic_generation_config.semantic_pad_token,
861
+ mode="constant",
862
+ )
863
+ else:
864
+ semantic_history = torch.tensor(
865
+ [semantic_generation_config.semantic_pad_token] * max_input_semantic_length, dtype=torch.int
866
+ ).to(self.device)
867
+
868
+ semantic_history = torch.repeat_interleave(semantic_history[None], batch_size, dim=0)
869
+
870
+ infer_array = torch.tensor(
871
+ [[semantic_generation_config.semantic_infer_token]] * batch_size, dtype=torch.int
872
+ ).to(self.device)
873
+
874
+ input_embeds = torch.cat(
875
+ [
876
+ self.input_embeds_layer(input_ids[:, :max_input_semantic_length])
877
+ + self.input_embeds_layer(semantic_history[:, : max_input_semantic_length + 1]),
878
+ self.input_embeds_layer(infer_array),
879
+ ],
880
+ dim=1,
881
+ )
882
+
883
+ tokens_to_suppress = list(
884
+ range(semantic_generation_config.semantic_vocab_size, semantic_generation_config.semantic_pad_token)
885
+ )
886
+ tokens_to_suppress.extend(
887
+ list(range(semantic_generation_config.semantic_pad_token + 1, self.config.output_vocab_size))
888
+ )
889
+
890
+ suppress_tokens_logits_processor = SuppressTokensLogitsProcessor(tokens_to_suppress, device=input_ids.device)
891
+
892
+ min_eos_p = kwargs.get("min_eos_p", semantic_generation_config.min_eos_p)
893
+ early_stopping_logits_processor = BarkEosPrioritizerLogitsProcessor(
894
+ eos_token_id=semantic_generation_config.eos_token_id, min_eos_p=min_eos_p, device=input_ids.device
895
+ )
896
+
897
+ # pass input_ids in order to stay consistent with the transformers generate method even though it is not used
898
+ # (except to get the input seq_len - that's why we keep the first 257 tokens)
899
+ semantic_output = super().generate(
900
+ torch.ones((batch_size, max_input_semantic_length + 1), dtype=torch.int, device=self.device),
901
+ input_embeds=input_embeds,
902
+ logits_processor=[suppress_tokens_logits_processor, early_stopping_logits_processor],
903
+ generation_config=semantic_generation_config,
904
+ **kwargs,
905
+ ) # size: 10048
906
+
907
+ # take the generated semantic tokens
908
+ semantic_output = semantic_output[:, max_input_semantic_length + 1 :]
909
+
910
+ return semantic_output
911
+
912
+
913
+ @add_start_docstrings(
914
+ """Bark coarse acoustics model.
915
+ It shares the same architecture as the semantic (or text) model. It is a GPT-2 like autoregressive model with a
916
+ language modeling head on top.""",
917
+ BARK_MODEL_START_DOCSTRING.format(config="BarkCoarseConfig"),
918
+ )
919
+ class BarkCoarseModel(BarkCausalModel):
920
+ base_model_prefix = "coarse_acoustics"
921
+ config_class = BarkCoarseConfig
922
+
923
+ def preprocess_histories(
924
+ self,
925
+ max_coarse_history: int,
926
+ semantic_to_coarse_ratio: int,
927
+ batch_size: int,
928
+ semantic_generation_config: int,
929
+ codebook_size: int,
930
+ history_prompt: Optional[Dict[str, torch.Tensor]] = None,
931
+ ):
932
+ """
933
+ Preprocess the optional `Bark` speaker prompts before `self.generate`.
934
+
935
+ Args:
936
+ max_coarse_history (`int`):
937
+ Maximum size of coarse tokens used.
938
+ semantic_to_coarse_ratio (`int`):
939
+ Ratio of semantic to coarse frequency
940
+ batch_size (`int`):
941
+ Batch size, i.e the number of samples.
942
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
943
+ Generation config indicating how to generate the semantic tokens.
944
+ codebook_size (`int`):
945
+ Codebook channel size, i.e. the size of the output vocabulary per codebook channel.
946
+ history_prompt (`Optional[Dict[str,torch.Tensor]]`):
947
+ Optional `Bark` speaker prompt.
948
+ Returns: Returns:
949
+ `tuple(torch.FloatTensor)`:
950
+ - **x_semantic_history** (`torch.FloatTensor` -- Processed semantic speaker prompt.
951
+ - **x_coarse_history** (`torch.FloatTensor`) -- Processed coarse speaker prompt.
952
+ """
953
+ if history_prompt is not None:
954
+ x_semantic_history = torch.repeat_interleave(history_prompt["semantic_prompt"][None], batch_size, dim=0)
955
+ # clone to avoid modifying history_prompt.coarse_prompt
956
+ x_coarse_history = history_prompt["coarse_prompt"].clone()
957
+
958
+ # offset x_coarse_history
959
+ if codebook_size is not None:
960
+ for n in range(1, x_coarse_history.shape[0]):
961
+ # offset
962
+ x_coarse_history[n, :] += codebook_size * n
963
+
964
+ # flatten x_coarse_history
965
+ x_coarse_history = torch.transpose(x_coarse_history, 0, 1).reshape(-1)
966
+
967
+ x_coarse_history = x_coarse_history + semantic_generation_config.semantic_vocab_size
968
+
969
+ x_coarse_history = torch.repeat_interleave(x_coarse_history[None], batch_size, dim=0)
970
+ # e.g: after SEMANTIC_VOCAB_SIZE (10000), 1024 tokens dedicated to first codebook, 1024 next tokens
971
+ # dedicated to second codebook.
972
+
973
+ max_semantic_history = int(np.floor(max_coarse_history / semantic_to_coarse_ratio))
974
+ # trim histories correctly
975
+ n_semantic_hist_provided = min(
976
+ [
977
+ max_semantic_history,
978
+ x_semantic_history.shape[1] - x_semantic_history.shape[1] % 2,
979
+ int(np.floor(x_coarse_history.shape[1] / semantic_to_coarse_ratio)),
980
+ ]
981
+ )
982
+
983
+ n_coarse_hist_provided = int(round(n_semantic_hist_provided * semantic_to_coarse_ratio))
984
+
985
+ x_semantic_history = x_semantic_history[:, -n_semantic_hist_provided:].int()
986
+ x_coarse_history = x_coarse_history[:, -n_coarse_hist_provided:].int()
987
+ # bit of a hack for time alignment (sounds better) - from Bark original implementation
988
+ x_coarse_history = x_coarse_history[:, :-2]
989
+
990
+ else:
991
+ # shape: (batch_size, 0)
992
+ x_semantic_history = torch.tensor([[]] * batch_size, dtype=torch.int, device=self.device)
993
+ x_coarse_history = torch.tensor([[]] * batch_size, dtype=torch.int, device=self.device)
994
+
995
+ return x_semantic_history, x_coarse_history
996
+
997
+ def generate(
998
+ self,
999
+ semantic_output: torch.Tensor,
1000
+ semantic_generation_config: BarkSemanticGenerationConfig = None,
1001
+ coarse_generation_config: BarkCoarseGenerationConfig = None,
1002
+ codebook_size: int = 1024,
1003
+ history_prompt: Optional[Dict[str, torch.Tensor]] = None,
1004
+ return_output_lengths: Optional[bool] = None,
1005
+ **kwargs,
1006
+ ) -> Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]]:
1007
+ """
1008
+ Generates coarse acoustics tokens from input text semantic tokens and an additional optional `Bark` speaker
1009
+ prompt.
1010
+
1011
+ Args:
1012
+ semantic_output (`torch.Tensor` of shape (batch_size, seq_len), *optional*):
1013
+ Input text semantic ids, i.e the output of `BarkSemanticModel.generate`.
1014
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
1015
+ Generation config indicating how to generate the semantic tokens.
1016
+ coarse_generation_config (`BarkCoarseGenerationConfig`):
1017
+ Generation config indicating how to generate the coarse tokens.
1018
+ codebook_size (`int`, *optional*, defaults to 1024):
1019
+ Codebook channel size, i.e. the size of the output vocabulary per codebook channel.
1020
+ history_prompt (`Optional[Dict[str,torch.Tensor]]`, *optional*):
1021
+ Optional `Bark` speaker prompt.
1022
+ return_output_lengths (`bool`, *optional*):
1023
+ Whether or not to return the output lengths. Useful when batching.
1024
+ Returns:
1025
+ By default:
1026
+ torch.LongTensor: Output coarse acoustics tokens.
1027
+ If `return_output_lengths=True`:
1028
+ `Tuple(torch.Tensor, torch.Tensor): The output coarse acoustics tokens, and the length of each sample
1029
+ of the batch.
1030
+ """
1031
+
1032
+ if semantic_generation_config is None:
1033
+ raise ValueError("`semantic_generation_config` has to be provided")
1034
+
1035
+ if coarse_generation_config is None:
1036
+ raise ValueError("`coarse_generation_config` has to be provided")
1037
+
1038
+ max_coarse_input_length = coarse_generation_config.max_coarse_input_length
1039
+ max_coarse_history = coarse_generation_config.max_coarse_history
1040
+ sliding_window_len = coarse_generation_config.sliding_window_len
1041
+
1042
+ # replace semantic_pad_token (eos_tok and pad_tok here) with coarse_semantic_pad_token i.e the pad_token
1043
+ # used in the next model
1044
+ semantic_output.masked_fill_(
1045
+ semantic_output == semantic_generation_config.semantic_pad_token,
1046
+ coarse_generation_config.coarse_semantic_pad_token,
1047
+ )
1048
+
1049
+ semantic_to_coarse_ratio = (
1050
+ coarse_generation_config.coarse_rate_hz
1051
+ / semantic_generation_config.semantic_rate_hz
1052
+ * coarse_generation_config.n_coarse_codebooks
1053
+ )
1054
+ max_semantic_history = int(np.floor(max_coarse_history / semantic_to_coarse_ratio))
1055
+
1056
+ output_lengths = (semantic_output != coarse_generation_config.coarse_semantic_pad_token).sum(1)
1057
+ output_lengths = torch.floor(
1058
+ output_lengths * semantic_to_coarse_ratio / coarse_generation_config.n_coarse_codebooks
1059
+ )
1060
+ output_lengths = torch.round(output_lengths * coarse_generation_config.n_coarse_codebooks).int()
1061
+
1062
+ max_generated_len = torch.max(output_lengths).item()
1063
+
1064
+ batch_size = semantic_output.shape[0]
1065
+
1066
+ x_semantic_history, x_coarse = self.preprocess_histories(
1067
+ history_prompt=history_prompt,
1068
+ max_coarse_history=max_coarse_history,
1069
+ semantic_to_coarse_ratio=semantic_to_coarse_ratio,
1070
+ batch_size=batch_size,
1071
+ semantic_generation_config=semantic_generation_config,
1072
+ codebook_size=codebook_size,
1073
+ )
1074
+ base_semantic_idx = x_semantic_history.shape[1]
1075
+
1076
+ semantic_output = torch.hstack([x_semantic_history, semantic_output])
1077
+
1078
+ n_window_steps = int(np.ceil(max_generated_len / sliding_window_len))
1079
+
1080
+ total_generated_len = 0
1081
+
1082
+ len_coarse_history = x_coarse.shape[1]
1083
+
1084
+ for _ in range(n_window_steps):
1085
+ semantic_idx = base_semantic_idx + int(round(total_generated_len / semantic_to_coarse_ratio))
1086
+
1087
+ # pad from right side
1088
+ input_coarse = semantic_output[:, np.max([0, semantic_idx - max_semantic_history]) :]
1089
+ input_coarse = input_coarse[:, :max_coarse_input_length]
1090
+ input_coarse = F.pad(
1091
+ input_coarse,
1092
+ (0, max_coarse_input_length - input_coarse.shape[-1]),
1093
+ "constant",
1094
+ coarse_generation_config.coarse_semantic_pad_token,
1095
+ )
1096
+
1097
+ input_coarse = torch.hstack(
1098
+ [
1099
+ input_coarse,
1100
+ torch.tensor([[coarse_generation_config.coarse_infer_token]] * batch_size, device=self.device),
1101
+ x_coarse[:, -max_coarse_history:],
1102
+ ]
1103
+ )
1104
+
1105
+ alternatingLogitsProcessor = AlternatingCodebooksLogitsProcessor(
1106
+ input_coarse.shape[1],
1107
+ semantic_generation_config.semantic_vocab_size,
1108
+ codebook_size,
1109
+ )
1110
+
1111
+ output_coarse = super().generate(
1112
+ input_coarse,
1113
+ logits_processor=[alternatingLogitsProcessor],
1114
+ max_new_tokens=min(sliding_window_len, max_generated_len - total_generated_len),
1115
+ generation_config=coarse_generation_config,
1116
+ **kwargs,
1117
+ )
1118
+
1119
+ input_coarse_len = input_coarse.shape[1]
1120
+
1121
+ x_coarse = torch.hstack([x_coarse, output_coarse[:, input_coarse_len:]])
1122
+ total_generated_len = x_coarse.shape[1] - len_coarse_history
1123
+
1124
+ del output_coarse
1125
+
1126
+ coarse_output = x_coarse[:, len_coarse_history:]
1127
+
1128
+ if return_output_lengths:
1129
+ return coarse_output, output_lengths
1130
+
1131
+ return coarse_output
1132
+
1133
+
1134
+ @add_start_docstrings(
1135
+ """Bark fine acoustics model. It is a non-causal GPT-like model with `config.n_codes_total` embedding layers and
1136
+ language modeling heads, one for each codebook.""",
1137
+ BARK_MODEL_START_DOCSTRING.format(config="BarkFineConfig"),
1138
+ )
1139
+ class BarkFineModel(BarkPreTrainedModel):
1140
+ base_model_prefix = "fine_acoustics"
1141
+ config_class = BarkFineConfig
1142
+ main_input_name = "codebook_idx"
1143
+
1144
+ def __init__(self, config):
1145
+ # non-causal gpt-like model with one embedding layer and one lm_head for each codebook of Encodec
1146
+ super().__init__(config)
1147
+ self.config = config
1148
+
1149
+ # initialize a modified non causal GPT-like model
1150
+ # note that for there is one embedding layer and one lm_head for each codebook of Encodec
1151
+ self.input_embeds_layers = nn.ModuleList(
1152
+ [nn.Embedding(config.input_vocab_size, config.hidden_size) for _ in range(config.n_codes_total)]
1153
+ )
1154
+ self.position_embeds_layer = nn.Embedding(config.block_size, config.hidden_size)
1155
+
1156
+ self.drop = nn.Dropout(config.dropout)
1157
+
1158
+ self.layers = nn.ModuleList([BarkBlock(config, is_causal=False) for _ in range(config.num_layers)])
1159
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1160
+
1161
+ self.layernorm_final = nn.LayerNorm(config.hidden_size)
1162
+
1163
+ self.lm_heads = nn.ModuleList(
1164
+ [
1165
+ nn.Linear(config.hidden_size, config.output_vocab_size, bias=False)
1166
+ for _ in range(config.n_codes_given, config.n_codes_total)
1167
+ ]
1168
+ )
1169
+ self.gradient_checkpointing = False
1170
+ self.n_codes_total = config.n_codes_total
1171
+
1172
+ # Initialize weights and apply final processing
1173
+ self.post_init()
1174
+
1175
+ def get_input_embeddings(self):
1176
+ # one embedding layers for each codebook
1177
+ return self.input_embeds_layers
1178
+
1179
+ def set_input_embeddings(self, new_embeddings):
1180
+ # one embedding layers for each codebook
1181
+ self.input_embeds_layers = new_embeddings
1182
+
1183
+ def get_output_embeddings(self):
1184
+ # one lm_head for each codebook
1185
+ return self.lm_heads
1186
+
1187
+ def set_output_embeddings(self, new_output_embeddings):
1188
+ # one lm_head for each codebook
1189
+ self.lm_heads = new_output_embeddings
1190
+
1191
+ def _resize_token_embeddings(self, new_num_tokens, pad_to_multiple_of=None, mean_resizing=True):
1192
+ old_embeddings_list = self.get_input_embeddings()
1193
+ new_embeddings_list = nn.ModuleList(
1194
+ [
1195
+ self._get_resized_embeddings(old_embeddings, new_num_tokens, pad_to_multiple_of, mean_resizing)
1196
+ for old_embeddings in old_embeddings_list
1197
+ ]
1198
+ )
1199
+ self.set_input_embeddings(new_embeddings_list)
1200
+ new_num_tokens = new_embeddings_list[0].weight.shape[0]
1201
+
1202
+ # if word embeddings are not tied, make sure that lm head is resized as well
1203
+ if self.get_output_embeddings() is not None and not self.config.tie_word_embeddings:
1204
+ old_lm_head_list = self.get_output_embeddings()
1205
+ new_lm_head_list = nn.ModuleList(
1206
+ [self._get_resized_lm_head(old_lm_head, new_num_tokens) for old_lm_head in old_lm_head_list]
1207
+ )
1208
+ self.set_output_embeddings(new_lm_head_list)
1209
+
1210
+ return self.get_input_embeddings()
1211
+
1212
+ def resize_token_embeddings(
1213
+ self,
1214
+ new_num_tokens: Optional[int] = None,
1215
+ pad_to_multiple_of: Optional[int] = None,
1216
+ mean_resizing: bool = True,
1217
+ ) -> nn.Embedding:
1218
+ """
1219
+ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`.
1220
+
1221
+ Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method.
1222
+
1223
+ Arguments:
1224
+ new_num_tokens (`int`, *optional*):
1225
+ The number of new tokens in the embedding matrix. Increasing the size will add newly initialized
1226
+ vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just
1227
+ returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything.
1228
+ pad_to_multiple_of (`int`, *optional*):
1229
+ If set will pad the embedding matrix to a multiple of the provided value.
1230
+
1231
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
1232
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more
1233
+ details about this, or help on choosing the correct value for resizing, refer to this guide:
1234
+ https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc
1235
+ mean_resizing (`bool`):
1236
+ Whether to initialize the added embeddings from a multivariate normal distribution that has old embeddings' mean and
1237
+ covariance or to initialize them with a normal distribution that has a mean of zero and std equals `config.initializer_range`.
1238
+
1239
+ Setting `mean_resizing` to `True` is useful when increasing the size of the embeddings of causal language models,
1240
+ where the generated tokens' probabilities won't be affected by the added embeddings because initializing the new embeddings with the
1241
+ old embeddings' mean will reduce the kl-divergence between the next token probability before and after adding the new embeddings.
1242
+ Refer to this article for more information: https://nlp.stanford.edu/~johnhew/vocab-expansion.html
1243
+
1244
+ Return:
1245
+ `torch.nn.Embedding`: Pointer to the input tokens Embeddings Module of the model.
1246
+ """
1247
+ model_embeds = self._resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1248
+ if new_num_tokens is None and pad_to_multiple_of is None:
1249
+ return model_embeds
1250
+
1251
+ # Update base model and current model config
1252
+ self.config.output_vocab_size = model_embeds[0].weight.shape[0]
1253
+ self.config.vocab_size = model_embeds[0].weight.shape[0]
1254
+ self.output_vocab_size = model_embeds[0].weight.shape[0]
1255
+ self.vocab_size = model_embeds[0].weight.shape[0]
1256
+
1257
+ # Tie weights again if needed
1258
+ self.tie_weights()
1259
+
1260
+ return model_embeds
1261
+
1262
+ def _tie_weights(self):
1263
+ if getattr(self.config, "tie_word_embeddings", True):
1264
+ self._tied_weights_keys = []
1265
+ output_embeddings = self.get_output_embeddings()
1266
+ input_embeddings = self.get_input_embeddings()
1267
+
1268
+ for i in range(self.config.n_codes_total - self.config.n_codes_given):
1269
+ # self.input_embeds_layers[i + 1].weight = self.lm_heads[i].weight
1270
+ self._tie_or_clone_weights(output_embeddings[i], input_embeddings[i + 1])
1271
+ self._tied_weights_keys.append(f"lm_heads.{i}.weight")
1272
+
1273
+ def tie_weights(self):
1274
+ """
1275
+ Tie the weights between the input embeddings list and the output embeddings list.
1276
+
1277
+ If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the
1278
+ weights instead.
1279
+ """
1280
+ if getattr(self.config, "tie_word_embeddings", True):
1281
+ self._tied_weights_keys = []
1282
+ output_embeddings = self.get_output_embeddings()
1283
+ input_embeddings = self.get_input_embeddings()
1284
+
1285
+ for i in range(self.config.n_codes_total - self.config.n_codes_given):
1286
+ # self.input_embeds_layers[i + 1].weight = self.lm_heads[i].weight
1287
+ self._tie_or_clone_weights(output_embeddings[i], input_embeddings[i + 1])
1288
+ self._tied_weights_keys.append(f"lm_heads.{i}.weight")
1289
+
1290
+ for module in self.modules():
1291
+ if hasattr(module, "_tie_weights"):
1292
+ module._tie_weights()
1293
+
1294
+ @add_start_docstrings_to_model_forward(BARK_FINE_INPUTS_DOCSTRING)
1295
+ def forward(
1296
+ self,
1297
+ codebook_idx: int, # an additionnal idx corresponding to the id of the codebook that will be predicted
1298
+ input_ids: Optional[torch.Tensor] = None,
1299
+ attention_mask: Optional[torch.Tensor] = None,
1300
+ position_ids: Optional[torch.Tensor] = None,
1301
+ head_mask: Optional[torch.Tensor] = None,
1302
+ labels: Optional[torch.LongTensor] = None,
1303
+ input_embeds: Optional[torch.Tensor] = None,
1304
+ output_attentions: Optional[bool] = None,
1305
+ output_hidden_states: Optional[bool] = None,
1306
+ return_dict: Optional[bool] = None,
1307
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1308
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1309
+ output_hidden_states = (
1310
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1311
+ )
1312
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1313
+
1314
+ loss = None
1315
+ if labels is not None:
1316
+ raise NotImplementedError("Training is not implemented yet")
1317
+
1318
+ if codebook_idx == 0:
1319
+ raise ValueError("Cannot predict 0th codebook - 0th codebook should be predicted by the coarse model")
1320
+
1321
+ if input_ids is not None and input_embeds is not None:
1322
+ raise ValueError("You cannot specify both input_ids and input_embeds at the same time")
1323
+
1324
+ if input_ids is None and input_embeds is None:
1325
+ raise ValueError("You have to specify either input_ids or input_embeds")
1326
+
1327
+ if input_ids is not None:
1328
+ # the input_embeddings are the sum of the j previous codebooks embeddings before
1329
+ # the current codebook_idx codebook
1330
+
1331
+ # forward the GPT model itself
1332
+ input_embeds = [
1333
+ input_embeds_layer(input_ids[:, :, i]).unsqueeze(-1)
1334
+ for i, input_embeds_layer in enumerate(self.input_embeds_layers)
1335
+ ] # token embeddings of shape (b, t, n_embd)
1336
+ input_embeds = torch.cat(input_embeds, dim=-1)
1337
+ input_embeds = input_embeds[:, :, :, : codebook_idx + 1].sum(dim=-1)
1338
+
1339
+ input_shape = input_embeds.size()[:-1]
1340
+ batch_size = input_embeds.shape[0]
1341
+ seq_length = input_shape[1]
1342
+
1343
+ device = input_ids.device if input_ids is not None else input_embeds.device
1344
+
1345
+ if position_ids is None:
1346
+ position_ids = torch.arange(0, seq_length, dtype=torch.long, device=device)
1347
+ position_ids = position_ids.unsqueeze(0) # shape (1, seq_length)
1348
+
1349
+ position_embeds = self.position_embeds_layer(position_ids) # position embeddings of shape (1, t, n_embd)
1350
+
1351
+ # Attention mask.
1352
+ if attention_mask is not None:
1353
+ if batch_size <= 0:
1354
+ raise ValueError("batch_size has to be defined and > 0")
1355
+ if self._use_flash_attention_2:
1356
+ attention_mask = attention_mask if 0 in attention_mask else None
1357
+ else:
1358
+ # [bsz, to_seq_length] -> [bsz, 1, 1, to_seq_length]
1359
+ # from_seq_length is 1 to easily broadcast
1360
+ attention_mask = _prepare_4d_attention_mask(attention_mask, input_embeds.dtype, tgt_len=1)
1361
+
1362
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
1363
+
1364
+ hidden_states = self.drop(input_embeds + position_embeds)
1365
+ output_shape = input_shape + (hidden_states.size(-1),)
1366
+
1367
+ all_self_attentions = () if output_attentions else None
1368
+ all_hidden_states = () if output_hidden_states else None
1369
+
1370
+ for i, block in enumerate(self.layers):
1371
+ if output_hidden_states:
1372
+ all_hidden_states = all_hidden_states + (hidden_states,)
1373
+
1374
+ outputs = block(
1375
+ hidden_states,
1376
+ attention_mask=attention_mask,
1377
+ head_mask=head_mask[i],
1378
+ output_attentions=output_attentions,
1379
+ )
1380
+
1381
+ hidden_states = outputs[0]
1382
+
1383
+ if output_attentions:
1384
+ all_self_attentions = all_self_attentions + (outputs[1],)
1385
+
1386
+ hidden_states = self.layernorm_final(hidden_states)
1387
+ hidden_states = hidden_states.view(output_shape)
1388
+
1389
+ # Add last hidden state
1390
+ if output_hidden_states:
1391
+ all_hidden_states = all_hidden_states + (hidden_states,)
1392
+
1393
+ logits = self.lm_heads[codebook_idx - self.config.n_codes_given](hidden_states)
1394
+
1395
+ if not return_dict:
1396
+ return tuple(v for v in [None, logits, all_hidden_states, all_self_attentions] if v is not None)
1397
+
1398
+ return MaskedLMOutput(
1399
+ loss=loss,
1400
+ logits=logits,
1401
+ hidden_states=all_hidden_states,
1402
+ attentions=all_self_attentions,
1403
+ )
1404
+
1405
+ def generate(
1406
+ self,
1407
+ coarse_output: torch.Tensor,
1408
+ semantic_generation_config: BarkSemanticGenerationConfig = None,
1409
+ coarse_generation_config: BarkCoarseGenerationConfig = None,
1410
+ fine_generation_config: BarkFineGenerationConfig = None,
1411
+ codebook_size: int = 1024,
1412
+ history_prompt: Optional[Dict[str, torch.Tensor]] = None,
1413
+ **kwargs,
1414
+ ) -> torch.LongTensor:
1415
+ """
1416
+ Generates fine acoustics tokens from input coarse acoustics tokens and an additional optional `Bark` speaker
1417
+ prompt.
1418
+
1419
+ Args:
1420
+ coarse_output (`torch.Tensor` of shape (batch_size, seq_len)):
1421
+ Input coarse acoustics ids, i.e the output of `BarkCoarseModel.generate`.
1422
+ semantic_generation_config (`BarkSemanticGenerationConfig`):
1423
+ Generation config indicating how to generate the semantic tokens.
1424
+ coarse_generation_config (`BarkCoarseGenerationConfig`):
1425
+ Generation config indicating how to generate the coarse tokens.
1426
+ fine_generation_config (`BarkFineGenerationConfig`):
1427
+ Generation config indicating how to generate the fine tokens.
1428
+ codebook_size (`int`, *optional*, defaults to 1024):
1429
+ Codebook channel size, i.e. the size of the output vocabulary per codebook channel.
1430
+ history_prompt (`Optional[Dict[str,torch.Tensor]]`, *optional*):
1431
+ Optional `Bark` speaker prompt.
1432
+ Returns:
1433
+ torch.LongTensor: Output fine acoustics tokens.
1434
+ """
1435
+ if semantic_generation_config is None:
1436
+ raise ValueError("`semantic_generation_config` has to be provided")
1437
+
1438
+ if coarse_generation_config is None:
1439
+ raise ValueError("`coarse_generation_config` has to be provided")
1440
+
1441
+ if fine_generation_config is None:
1442
+ raise ValueError("`fine_generation_config` has to be provided")
1443
+
1444
+ # since we don't really use GenerationConfig through the fine model (autoencoder)
1445
+ # and since only temperature is used from the classic GenerationConfig parameters
1446
+ # manually impose the kwargs priority over the generation config
1447
+ temperature = kwargs.get("temperature", fine_generation_config.temperature)
1448
+
1449
+ max_fine_history_length = fine_generation_config.max_fine_history_length
1450
+ max_fine_input_length = fine_generation_config.max_fine_input_length
1451
+
1452
+ # shape: (batch, n_coarse_codebooks * seq_len)
1453
+ # new_shape: (batch, seq_len, n_coarse_codebooks)
1454
+ coarse_output = coarse_output.view(coarse_output.shape[0], -1, coarse_generation_config.n_coarse_codebooks)
1455
+
1456
+ # brings ids into the range [0, codebook_size -1]
1457
+ coarse_output = torch.remainder(coarse_output - semantic_generation_config.semantic_vocab_size, codebook_size)
1458
+ batch_size = coarse_output.shape[0]
1459
+
1460
+ if history_prompt is not None:
1461
+ x_fine_history = torch.repeat_interleave(history_prompt["fine_prompt"].T[None], batch_size, dim=0)
1462
+ # transpose to get to shape (seq_len, n_fine_codebooks)
1463
+ else:
1464
+ x_fine_history = None
1465
+
1466
+ n_coarse = coarse_generation_config.n_coarse_codebooks
1467
+
1468
+ # pad the last 6th codebooks
1469
+ fine_input = F.pad(
1470
+ coarse_output,
1471
+ (0, fine_generation_config.n_fine_codebooks - n_coarse),
1472
+ "constant",
1473
+ codebook_size,
1474
+ )
1475
+
1476
+ # prepend history if available (max max_fine_history_length)
1477
+ if x_fine_history is not None:
1478
+ fine_input = torch.cat([x_fine_history[:, -max_fine_history_length:, :], fine_input], dim=1)
1479
+
1480
+ # len of the fine_history that has been added to fine_input
1481
+ n_history = x_fine_history[:, -max_fine_history_length:, :].shape[1]
1482
+ else:
1483
+ n_history = 0
1484
+
1485
+ n_remove_from_end = 0
1486
+ # need to pad if too short (since non-causal model)
1487
+ if fine_input.shape[1] < max_fine_input_length:
1488
+ n_remove_from_end = max_fine_input_length - fine_input.shape[1]
1489
+ fine_input = F.pad(fine_input, (0, 0, 0, n_remove_from_end), mode="constant", value=codebook_size)
1490
+
1491
+ # we can be lazy about fractional loop and just keep overwriting codebooks.
1492
+ # seems that coarse_output.shape[1] - (max_fine_input_length - n_history) is equal to minus n_remove_from_end
1493
+ # So if we needed to pad because too short, n_loops is always 1 (because n_remove_from_end > 0)
1494
+ # If not, we loop over at least twice.
1495
+
1496
+ n_loops = (coarse_output.shape[1] - (max_fine_input_length - n_history)) / max_fine_history_length
1497
+ n_loops = int(np.ceil(n_loops))
1498
+ n_loops = max(0, n_loops) + 1
1499
+
1500
+ for n_outer in range(n_loops):
1501
+ start_idx = min([n_outer * max_fine_history_length, fine_input.shape[1] - max_fine_input_length])
1502
+
1503
+ start_fill_idx = min(
1504
+ [n_history + n_outer * max_fine_history_length, fine_input.shape[1] - max_fine_history_length]
1505
+ )
1506
+ rel_start_fill_idx = start_fill_idx - start_idx
1507
+ input_buffer = fine_input[:, start_idx : start_idx + max_fine_input_length, :]
1508
+ for n_inner in range(n_coarse, fine_generation_config.n_fine_codebooks):
1509
+ logits = self.forward(n_inner, input_buffer).logits
1510
+ if temperature is None or temperature == 1.0:
1511
+ relevant_logits = logits[:, rel_start_fill_idx:, :codebook_size]
1512
+ codebook_preds = torch.argmax(relevant_logits, -1)
1513
+ else:
1514
+ relevant_logits = logits[:, :, :codebook_size] / temperature
1515
+ # apply softmax
1516
+ probs = F.softmax(relevant_logits, dim=-1)[:, rel_start_fill_idx:max_fine_input_length]
1517
+ # reshape to 2D: (batch_size, seq_len, codebook_size) -> (batch_size*seq_len, codebook_size)
1518
+ probs = probs.reshape((-1, codebook_size))
1519
+ # multinomial then reshape : (batch_size*seq_len)-> (batch_size,seq_len)
1520
+ codebook_preds = torch.multinomial(probs, num_samples=1).view(batch_size, -1)
1521
+ codebook_preds = codebook_preds.to(torch.int32)
1522
+ input_buffer[:, rel_start_fill_idx:, n_inner] = codebook_preds
1523
+ del logits, codebook_preds
1524
+
1525
+ # transfer into fine_input
1526
+ for n_inner in range(n_coarse, fine_generation_config.n_fine_codebooks):
1527
+ fine_input[
1528
+ :, start_fill_idx : start_fill_idx + (max_fine_input_length - rel_start_fill_idx), n_inner
1529
+ ] = input_buffer[:, rel_start_fill_idx:, n_inner]
1530
+ del input_buffer
1531
+
1532
+ fine_input = fine_input.transpose(1, 2)[:, :, n_history:]
1533
+ if n_remove_from_end > 0:
1534
+ fine_input = fine_input[:, :, :-n_remove_from_end]
1535
+
1536
+ if fine_input.shape[-1] != coarse_output.shape[-2]:
1537
+ raise ValueError("input and output should have the same seq_len")
1538
+
1539
+ return fine_input
1540
+
1541
+
1542
+ @add_start_docstrings(
1543
+ """
1544
+ The full Bark model, a text-to-speech model composed of 4 sub-models:
1545
+ - [`BarkSemanticModel`] (also referred to as the 'text' model): a causal auto-regressive transformer model that
1546
+ takes
1547
+ as input tokenized text, and predicts semantic text tokens that capture the meaning of the text.
1548
+ - [`BarkCoarseModel`] (also refered to as the 'coarse acoustics' model), also a causal autoregressive transformer,
1549
+ that takes into input the results of the last model. It aims at regressing the first two audio codebooks necessary
1550
+ to `encodec`.
1551
+ - [`BarkFineModel`] (the 'fine acoustics' model), this time a non-causal autoencoder transformer, which iteratively
1552
+ predicts the last codebooks based on the sum of the previous codebooks embeddings.
1553
+ - having predicted all the codebook channels from the [`EncodecModel`], Bark uses it to decode the output audio
1554
+ array.
1555
+
1556
+ It should be noted that each of the first three modules can support conditional speaker embeddings to condition the
1557
+ output sound according to specific predefined voice.
1558
+ """,
1559
+ BARK_START_DOCSTRING,
1560
+ )
1561
+ class BarkModel(BarkPreTrainedModel):
1562
+ config_class = BarkConfig
1563
+
1564
+ def __init__(self, config):
1565
+ super().__init__(config)
1566
+
1567
+ self.semantic = BarkSemanticModel(config.semantic_config)
1568
+ self.coarse_acoustics = BarkCoarseModel(config.coarse_acoustics_config)
1569
+ self.fine_acoustics = BarkFineModel(config.fine_acoustics_config)
1570
+
1571
+ self.codec_model = AutoModel.from_config(config.codec_config)
1572
+
1573
+ self.config = config
1574
+
1575
+ @classmethod
1576
+ def can_generate(cls) -> bool:
1577
+ # Bark has a unique model structure, where the external class (`BarkModel`) doesn't need to inherit from
1578
+ # `GenerationMixin` (it has a non-standard generation method), but one of the internal models do
1579
+ # (`BarkSemanticModel`). This means that the base `can_generate()` will return `False`, but we need to
1580
+ # override it so as to do `GenerationConfig` handling in multiple parts of the codebase.
1581
+ return True
1582
+
1583
+ @property
1584
+ def device(self) -> torch.device:
1585
+ """
1586
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
1587
+ device).
1588
+ """
1589
+ # for bark_model, device must be verified on its sub-models
1590
+ # if has _hf_hook, has been offloaded so the device has to be found in the hook
1591
+ if not hasattr(self.semantic, "_hf_hook"):
1592
+ return get_parameter_device(self)
1593
+ for module in self.semantic.modules():
1594
+ if (
1595
+ hasattr(module, "_hf_hook")
1596
+ and hasattr(module._hf_hook, "execution_device")
1597
+ and module._hf_hook.execution_device is not None
1598
+ ):
1599
+ return torch.device(module._hf_hook.execution_device)
1600
+
1601
+ def enable_cpu_offload(self, gpu_id: Optional[int] = 0):
1602
+ r"""
1603
+ Offloads all sub-models to CPU using accelerate, reducing memory usage with a low impact on performance. This
1604
+ method moves one whole sub-model at a time to the GPU when it is used, and the sub-model remains in GPU until
1605
+ the next sub-model runs.
1606
+
1607
+ Args:
1608
+ gpu_id (`int`, *optional*, defaults to 0):
1609
+ GPU id on which the sub-models will be loaded and offloaded.
1610
+ """
1611
+ if is_accelerate_available():
1612
+ from accelerate import cpu_offload_with_hook
1613
+ else:
1614
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate`.")
1615
+
1616
+ device = torch.device(f"cuda:{gpu_id}")
1617
+
1618
+ if self.device.type != "cpu":
1619
+ self.to("cpu")
1620
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
1621
+
1622
+ # this layer is used outside the first foward pass of semantic so need to be loaded before semantic
1623
+ self.semantic.input_embeds_layer, _ = cpu_offload_with_hook(self.semantic.input_embeds_layer, device)
1624
+
1625
+ hook = None
1626
+ for cpu_offloaded_model in [
1627
+ self.semantic,
1628
+ self.coarse_acoustics,
1629
+ self.fine_acoustics,
1630
+ ]:
1631
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
1632
+
1633
+ self.fine_acoustics_hook = hook
1634
+
1635
+ _, hook = cpu_offload_with_hook(self.codec_model, device, prev_module_hook=hook)
1636
+
1637
+ # We'll offload the last model manually.
1638
+ self.codec_model_hook = hook
1639
+
1640
+ def codec_decode(self, fine_output, output_lengths=None):
1641
+ """Turn quantized audio codes into audio array using encodec."""
1642
+
1643
+ fine_output = fine_output.transpose(0, 1)
1644
+ emb = self.codec_model.quantizer.decode(fine_output)
1645
+
1646
+ if output_lengths is not None:
1647
+ # encodec uses LSTMs which behaves differently with appended padding
1648
+ # decoding with encodec takes around 0.1% of the total generation time
1649
+ # to keep generation quality, we break batching
1650
+ out = [sample[:, :l].unsqueeze(0) for (sample, l) in zip(emb, output_lengths)]
1651
+ audio_arr = [self.codec_model.decoder(sample).squeeze() for sample in out]
1652
+ else:
1653
+ out = self.codec_model.decoder(emb)
1654
+ audio_arr = out.squeeze(1) # squeeze the codebook dimension
1655
+
1656
+ return audio_arr
1657
+
1658
+ @torch.no_grad()
1659
+ def generate(
1660
+ self,
1661
+ input_ids: Optional[torch.Tensor] = None,
1662
+ history_prompt: Optional[Dict[str, torch.Tensor]] = None,
1663
+ return_output_lengths: Optional[bool] = None,
1664
+ **kwargs,
1665
+ ) -> torch.LongTensor:
1666
+ """
1667
+ Generates audio from an input prompt and an additional optional `Bark` speaker prompt.
1668
+
1669
+ Args:
1670
+ input_ids (`Optional[torch.Tensor]` of shape (batch_size, seq_len), *optional*):
1671
+ Input ids. Will be truncated up to 256 tokens. Note that the output audios will be as long as the
1672
+ longest generation among the batch.
1673
+ history_prompt (`Optional[Dict[str,torch.Tensor]]`, *optional*):
1674
+ Optional `Bark` speaker prompt. Note that for now, this model takes only one speaker prompt per batch.
1675
+ kwargs (*optional*): Remaining dictionary of keyword arguments. Keyword arguments are of two types:
1676
+
1677
+ - Without a prefix, they will be entered as `**kwargs` for the `generate` method of each sub-model.
1678
+ - With a *semantic_*, *coarse_*, *fine_* prefix, they will be input for the `generate` method of the
1679
+ semantic, coarse and fine respectively. It has the priority over the keywords without a prefix.
1680
+
1681
+ This means you can, for example, specify a generation strategy for all sub-models except one.
1682
+ return_output_lengths (`bool`, *optional*):
1683
+ Whether or not to return the waveform lengths. Useful when batching.
1684
+ Returns:
1685
+ By default:
1686
+ - **audio_waveform** (`torch.Tensor` of shape (batch_size, seq_len)): Generated audio waveform.
1687
+ When `return_output_lengths=True`:
1688
+ Returns a tuple made of:
1689
+ - **audio_waveform** (`torch.Tensor` of shape (batch_size, seq_len)): Generated audio waveform.
1690
+ - **output_lengths** (`torch.Tensor` of shape (batch_size)): The length of each waveform in the batch
1691
+ Example:
1692
+
1693
+ ```python
1694
+ >>> from transformers import AutoProcessor, BarkModel
1695
+
1696
+ >>> processor = AutoProcessor.from_pretrained("suno/bark-small")
1697
+ >>> model = BarkModel.from_pretrained("suno/bark-small")
1698
+
1699
+ >>> # To add a voice preset, you can pass `voice_preset` to `BarkProcessor.__call__(...)`
1700
+ >>> voice_preset = "v2/en_speaker_6"
1701
+
1702
+ >>> inputs = processor("Hello, my dog is cute, I need him in my life", voice_preset=voice_preset)
1703
+
1704
+ >>> audio_array = model.generate(**inputs, semantic_max_new_tokens=100)
1705
+ >>> audio_array = audio_array.cpu().numpy().squeeze()
1706
+ ```
1707
+ """
1708
+ # TODO (joao):workaround until nested generation config is compatible with PreTrained Model
1709
+ # todo: dict
1710
+ semantic_generation_config = BarkSemanticGenerationConfig(**self.generation_config.semantic_config)
1711
+ coarse_generation_config = BarkCoarseGenerationConfig(**self.generation_config.coarse_acoustics_config)
1712
+ fine_generation_config = BarkFineGenerationConfig(**self.generation_config.fine_acoustics_config)
1713
+
1714
+ kwargs_semantic = {
1715
+ # if "attention_mask" is set, it should not be passed to CoarseModel and FineModel
1716
+ "attention_mask": kwargs.pop("attention_mask", None),
1717
+ "min_eos_p": kwargs.pop("min_eos_p", None),
1718
+ }
1719
+ kwargs_coarse = {}
1720
+ kwargs_fine = {}
1721
+ for key, value in kwargs.items():
1722
+ if key.startswith("semantic_"):
1723
+ key = key[len("semantic_") :]
1724
+ kwargs_semantic[key] = value
1725
+ elif key.startswith("coarse_"):
1726
+ key = key[len("coarse_") :]
1727
+ kwargs_coarse[key] = value
1728
+ elif key.startswith("fine_"):
1729
+ key = key[len("fine_") :]
1730
+ kwargs_fine[key] = value
1731
+ else:
1732
+ # If the key is already in a specific config, then it's been set with a
1733
+ # submodules specific value and we don't override
1734
+ if key not in kwargs_semantic:
1735
+ kwargs_semantic[key] = value
1736
+ if key not in kwargs_coarse:
1737
+ kwargs_coarse[key] = value
1738
+ if key not in kwargs_fine:
1739
+ kwargs_fine[key] = value
1740
+
1741
+ # 1. Generate from the semantic model
1742
+ if "generation_config" in kwargs_semantic:
1743
+ kwargs_semantic.pop("generation_config")
1744
+ semantic_output = self.semantic.generate(
1745
+ input_ids,
1746
+ history_prompt=history_prompt,
1747
+ semantic_generation_config=semantic_generation_config,
1748
+ **kwargs_semantic,
1749
+ )
1750
+
1751
+ # 2. Generate from the coarse model
1752
+ if "generation_config" in kwargs_coarse:
1753
+ kwargs_coarse.pop("generation_config")
1754
+ coarse_output = self.coarse_acoustics.generate(
1755
+ semantic_output,
1756
+ history_prompt=history_prompt,
1757
+ semantic_generation_config=semantic_generation_config,
1758
+ coarse_generation_config=coarse_generation_config,
1759
+ codebook_size=self.generation_config.codebook_size,
1760
+ return_output_lengths=return_output_lengths,
1761
+ **kwargs_coarse,
1762
+ )
1763
+
1764
+ output_lengths = None
1765
+ if return_output_lengths:
1766
+ coarse_output, output_lengths = coarse_output
1767
+ # (batch_size, seq_len*coarse_codebooks) -> (batch_size, seq_len)
1768
+ output_lengths = output_lengths // coarse_generation_config.n_coarse_codebooks
1769
+
1770
+ # 3. "generate" from the fine model
1771
+ if "generation_config" in kwargs_fine:
1772
+ kwargs_fine.pop("generation_config")
1773
+ output = self.fine_acoustics.generate(
1774
+ coarse_output,
1775
+ history_prompt=history_prompt,
1776
+ semantic_generation_config=semantic_generation_config,
1777
+ coarse_generation_config=coarse_generation_config,
1778
+ fine_generation_config=fine_generation_config,
1779
+ codebook_size=self.generation_config.codebook_size,
1780
+ **kwargs_fine,
1781
+ )
1782
+
1783
+ if getattr(self, "fine_acoustics_hook", None) is not None:
1784
+ # Manually offload fine_acoustics to CPU
1785
+ # and load codec_model to GPU
1786
+ # since bark doesn't use codec_model forward pass
1787
+ self.fine_acoustics_hook.offload()
1788
+ self.codec_model = self.codec_model.to(self.device)
1789
+
1790
+ # 4. Decode the output and generate audio array
1791
+ audio = self.codec_decode(output, output_lengths)
1792
+
1793
+ if getattr(self, "codec_model_hook", None) is not None:
1794
+ # Offload codec_model to CPU
1795
+ self.codec_model_hook.offload()
1796
+
1797
+ if return_output_lengths:
1798
+ output_lengths = [len(sample) for sample in audio]
1799
+ audio = nn.utils.rnn.pad_sequence(audio, batch_first=True, padding_value=0)
1800
+ return audio, output_lengths
1801
+
1802
+ return audio
1803
+
1804
+ @classmethod
1805
+ def _check_and_enable_flash_attn_2(
1806
+ cls,
1807
+ config,
1808
+ torch_dtype: Optional[torch.dtype] = None,
1809
+ device_map: Optional[Union[str, Dict[str, int]]] = None,
1810
+ hard_check_only: bool = False,
1811
+ check_device_map: bool = False,
1812
+ ):
1813
+ """
1814
+ `_check_and_enable_flash_attn_2` originally don't expand flash attention enabling to the model
1815
+ sub-configurations. We override the original method to make sure that Bark sub-models are using Flash Attention
1816
+ if necessary.
1817
+
1818
+ If you don't know about Flash Attention, check out the official repository of flash attention:
1819
+ https://github.com/Dao-AILab/flash-attention
1820
+
1821
+ For using Flash Attention 1.0 you can do it directly via the `BetterTransformer` API, have a look at this
1822
+ specific section of the documentation to learn more about it:
1823
+ https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#decoder-models
1824
+
1825
+ The method checks if the current setup is compatible with Flash Attention as it requires the model to be in
1826
+ half precision and not ran on CPU.
1827
+
1828
+ If all checks pass and `hard_check_only` is False, the method will set the config attribute `_attn_implementation` to "flash_attention_2" so that the model
1829
+ can initialize the correct attention module
1830
+ """
1831
+ config = super()._check_and_enable_flash_attn_2(
1832
+ config, torch_dtype, device_map, hard_check_only=hard_check_only, check_device_map=check_device_map
1833
+ )
1834
+
1835
+ config.semantic_config._attn_implementation = config._attn_implementation
1836
+ config.coarse_acoustics_config._attn_implementation = config._attn_implementation
1837
+ config.fine_acoustics_config._attn_implementation = config._attn_implementation
1838
+ return config
1839
+
1840
+
1841
+ __all__ = [
1842
+ "BarkFineModel",
1843
+ "BarkSemanticModel",
1844
+ "BarkCoarseModel",
1845
+ "BarkModel",
1846
+ "BarkPreTrainedModel",
1847
+ "BarkCausalModel",
1848
+ ]
lib/python3.12/site-packages/transformers/models/bark/processing_bark.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Suno AI Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for Bark
17
+ """
18
+
19
+ import json
20
+ import os
21
+ from typing import Optional
22
+
23
+ import numpy as np
24
+
25
+ from ...feature_extraction_utils import BatchFeature
26
+ from ...processing_utils import ProcessorMixin
27
+ from ...utils import logging
28
+ from ...utils.hub import cached_file
29
+ from ..auto import AutoTokenizer
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ class BarkProcessor(ProcessorMixin):
36
+ r"""
37
+ Constructs a Bark processor which wraps a text tokenizer and optional Bark voice presets into a single processor.
38
+
39
+ Args:
40
+ tokenizer ([`PreTrainedTokenizer`]):
41
+ An instance of [`PreTrainedTokenizer`].
42
+ speaker_embeddings (`Dict[Dict[str]]`, *optional*):
43
+ Optional nested speaker embeddings dictionary. The first level contains voice preset names (e.g
44
+ `"en_speaker_4"`). The second level contains `"semantic_prompt"`, `"coarse_prompt"` and `"fine_prompt"`
45
+ embeddings. The values correspond to the path of the corresponding `np.ndarray`. See
46
+ [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c) for
47
+ a list of `voice_preset_names`.
48
+
49
+ """
50
+
51
+ tokenizer_class = "AutoTokenizer"
52
+ attributes = ["tokenizer"]
53
+
54
+ preset_shape = {
55
+ "semantic_prompt": 1,
56
+ "coarse_prompt": 2,
57
+ "fine_prompt": 2,
58
+ }
59
+
60
+ def __init__(self, tokenizer, speaker_embeddings=None):
61
+ super().__init__(tokenizer)
62
+
63
+ self.speaker_embeddings = speaker_embeddings
64
+
65
+ @classmethod
66
+ def from_pretrained(
67
+ cls, pretrained_processor_name_or_path, speaker_embeddings_dict_path="speaker_embeddings_path.json", **kwargs
68
+ ):
69
+ r"""
70
+ Instantiate a Bark processor associated with a pretrained model.
71
+
72
+ Args:
73
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
74
+ This can be either:
75
+
76
+ - a string, the *model id* of a pretrained [`BarkProcessor`] hosted inside a model repo on
77
+ huggingface.co.
78
+ - a path to a *directory* containing a processor saved using the [`~BarkProcessor.save_pretrained`]
79
+ method, e.g., `./my_model_directory/`.
80
+ speaker_embeddings_dict_path (`str`, *optional*, defaults to `"speaker_embeddings_path.json"`):
81
+ The name of the `.json` file containing the speaker_embeddings dictionary located in
82
+ `pretrained_model_name_or_path`. If `None`, no speaker_embeddings is loaded.
83
+ **kwargs
84
+ Additional keyword arguments passed along to both
85
+ [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`].
86
+ """
87
+
88
+ if speaker_embeddings_dict_path is not None:
89
+ speaker_embeddings_path = cached_file(
90
+ pretrained_processor_name_or_path,
91
+ speaker_embeddings_dict_path,
92
+ subfolder=kwargs.pop("subfolder", None),
93
+ cache_dir=kwargs.pop("cache_dir", None),
94
+ force_download=kwargs.pop("force_download", False),
95
+ proxies=kwargs.pop("proxies", None),
96
+ resume_download=kwargs.pop("resume_download", None),
97
+ local_files_only=kwargs.pop("local_files_only", False),
98
+ token=kwargs.pop("use_auth_token", None),
99
+ revision=kwargs.pop("revision", None),
100
+ _raise_exceptions_for_gated_repo=False,
101
+ _raise_exceptions_for_missing_entries=False,
102
+ _raise_exceptions_for_connection_errors=False,
103
+ )
104
+ if speaker_embeddings_path is None:
105
+ logger.warning(
106
+ f"""`{os.path.join(pretrained_processor_name_or_path, speaker_embeddings_dict_path)}` does not exists
107
+ , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json
108
+ dictionary if wanted, otherwise set `speaker_embeddings_dict_path=None`."""
109
+ )
110
+ speaker_embeddings = None
111
+ else:
112
+ with open(speaker_embeddings_path) as speaker_embeddings_json:
113
+ speaker_embeddings = json.load(speaker_embeddings_json)
114
+ else:
115
+ speaker_embeddings = None
116
+
117
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_processor_name_or_path, **kwargs)
118
+
119
+ return cls(tokenizer=tokenizer, speaker_embeddings=speaker_embeddings)
120
+
121
+ def save_pretrained(
122
+ self,
123
+ save_directory,
124
+ speaker_embeddings_dict_path="speaker_embeddings_path.json",
125
+ speaker_embeddings_directory="speaker_embeddings",
126
+ push_to_hub: bool = False,
127
+ **kwargs,
128
+ ):
129
+ """
130
+ Saves the attributes of this processor (tokenizer...) in the specified directory so that it can be reloaded
131
+ using the [`~BarkProcessor.from_pretrained`] method.
132
+
133
+ Args:
134
+ save_directory (`str` or `os.PathLike`):
135
+ Directory where the tokenizer files and the speaker embeddings will be saved (directory will be created
136
+ if it does not exist).
137
+ speaker_embeddings_dict_path (`str`, *optional*, defaults to `"speaker_embeddings_path.json"`):
138
+ The name of the `.json` file that will contains the speaker_embeddings nested path dictionary, if it
139
+ exists, and that will be located in `pretrained_model_name_or_path/speaker_embeddings_directory`.
140
+ speaker_embeddings_directory (`str`, *optional*, defaults to `"speaker_embeddings/"`):
141
+ The name of the folder in which the speaker_embeddings arrays will be saved.
142
+ push_to_hub (`bool`, *optional*, defaults to `False`):
143
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
144
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
145
+ namespace).
146
+ kwargs:
147
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
148
+ """
149
+ if self.speaker_embeddings is not None:
150
+ os.makedirs(os.path.join(save_directory, speaker_embeddings_directory, "v2"), exist_ok=True)
151
+
152
+ embeddings_dict = {}
153
+
154
+ embeddings_dict["repo_or_path"] = save_directory
155
+
156
+ for prompt_key in self.speaker_embeddings:
157
+ if prompt_key != "repo_or_path":
158
+ voice_preset = self._load_voice_preset(prompt_key)
159
+
160
+ tmp_dict = {}
161
+ for key in self.speaker_embeddings[prompt_key]:
162
+ np.save(
163
+ os.path.join(
164
+ embeddings_dict["repo_or_path"], speaker_embeddings_directory, f"{prompt_key}_{key}"
165
+ ),
166
+ voice_preset[key],
167
+ allow_pickle=False,
168
+ )
169
+ tmp_dict[key] = os.path.join(speaker_embeddings_directory, f"{prompt_key}_{key}.npy")
170
+
171
+ embeddings_dict[prompt_key] = tmp_dict
172
+
173
+ with open(os.path.join(save_directory, speaker_embeddings_dict_path), "w") as fp:
174
+ json.dump(embeddings_dict, fp)
175
+
176
+ super().save_pretrained(save_directory, push_to_hub, **kwargs)
177
+
178
+ def _load_voice_preset(self, voice_preset: Optional[str] = None, **kwargs):
179
+ voice_preset_paths = self.speaker_embeddings[voice_preset]
180
+
181
+ voice_preset_dict = {}
182
+ for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
183
+ if key not in voice_preset_paths:
184
+ raise ValueError(
185
+ f"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]."
186
+ )
187
+
188
+ path = cached_file(
189
+ self.speaker_embeddings.get("repo_or_path", "/"),
190
+ voice_preset_paths[key],
191
+ subfolder=kwargs.pop("subfolder", None),
192
+ cache_dir=kwargs.pop("cache_dir", None),
193
+ force_download=kwargs.pop("force_download", False),
194
+ proxies=kwargs.pop("proxies", None),
195
+ resume_download=kwargs.pop("resume_download", None),
196
+ local_files_only=kwargs.pop("local_files_only", False),
197
+ token=kwargs.pop("use_auth_token", None),
198
+ revision=kwargs.pop("revision", None),
199
+ _raise_exceptions_for_gated_repo=False,
200
+ _raise_exceptions_for_missing_entries=False,
201
+ _raise_exceptions_for_connection_errors=False,
202
+ )
203
+ if path is None:
204
+ raise ValueError(
205
+ f"""`{os.path.join(self.speaker_embeddings.get("repo_or_path", "/"), voice_preset_paths[key])}` does not exists
206
+ , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}
207
+ embeddings."""
208
+ )
209
+
210
+ voice_preset_dict[key] = np.load(path)
211
+
212
+ return voice_preset_dict
213
+
214
+ def _validate_voice_preset_dict(self, voice_preset: Optional[dict] = None):
215
+ for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
216
+ if key not in voice_preset:
217
+ raise ValueError(f"Voice preset unrecognized, missing {key} as a key.")
218
+
219
+ if not isinstance(voice_preset[key], np.ndarray):
220
+ raise TypeError(f"{key} voice preset must be a {str(self.preset_shape[key])}D ndarray.")
221
+
222
+ if len(voice_preset[key].shape) != self.preset_shape[key]:
223
+ raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key])}D ndarray.")
224
+
225
+ def __call__(
226
+ self,
227
+ text=None,
228
+ voice_preset=None,
229
+ return_tensors="pt",
230
+ max_length=256,
231
+ add_special_tokens=False,
232
+ return_attention_mask=True,
233
+ return_token_type_ids=False,
234
+ **kwargs,
235
+ ):
236
+ """
237
+ Main method to prepare for the model one or several sequences(s). This method forwards the `text` and `kwargs`
238
+ arguments to the AutoTokenizer's [`~AutoTokenizer.__call__`] to encode the text. The method also proposes a
239
+ voice preset which is a dictionary of arrays that conditions `Bark`'s output. `kwargs` arguments are forwarded
240
+ to the tokenizer and to `cached_file` method if `voice_preset` is a valid filename.
241
+
242
+ Args:
243
+ text (`str`, `List[str]`, `List[List[str]]`):
244
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
245
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
246
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
247
+ voice_preset (`str`, `Dict[np.ndarray]`):
248
+ The voice preset, i.e the speaker embeddings. It can either be a valid voice_preset name, e.g
249
+ `"en_speaker_1"`, or directly a dictionary of `np.ndarray` embeddings for each submodel of `Bark`. Or
250
+ it can be a valid file name of a local `.npz` single voice preset.
251
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
252
+ If set, will return tensors of a particular framework. Acceptable values are:
253
+
254
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
255
+ - `'np'`: Return NumPy `np.ndarray` objects.
256
+
257
+ Returns:
258
+ Tuple([`BatchEncoding`], [`BatchFeature`]): A tuple composed of a [`BatchEncoding`], i.e the output of the
259
+ `tokenizer` and a [`BatchFeature`], i.e the voice preset with the right tensors type.
260
+ """
261
+ if voice_preset is not None and not isinstance(voice_preset, dict):
262
+ if (
263
+ isinstance(voice_preset, str)
264
+ and self.speaker_embeddings is not None
265
+ and voice_preset in self.speaker_embeddings
266
+ ):
267
+ voice_preset = self._load_voice_preset(voice_preset)
268
+
269
+ else:
270
+ if isinstance(voice_preset, str) and not voice_preset.endswith(".npz"):
271
+ voice_preset = voice_preset + ".npz"
272
+
273
+ voice_preset = np.load(voice_preset)
274
+
275
+ if voice_preset is not None:
276
+ self._validate_voice_preset_dict(voice_preset, **kwargs)
277
+ voice_preset = BatchFeature(data=voice_preset, tensor_type=return_tensors)
278
+
279
+ encoded_text = self.tokenizer(
280
+ text,
281
+ return_tensors=return_tensors,
282
+ padding="max_length",
283
+ max_length=max_length,
284
+ return_attention_mask=return_attention_mask,
285
+ return_token_type_ids=return_token_type_ids,
286
+ add_special_tokens=add_special_tokens,
287
+ **kwargs,
288
+ )
289
+
290
+ if voice_preset is not None:
291
+ encoded_text["history_prompt"] = voice_preset
292
+
293
+ return encoded_text
294
+
295
+
296
+ __all__ = ["BarkProcessor"]
lib/python3.12/site-packages/transformers/models/bert/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_bert import *
22
+ from .modeling_bert import *
23
+ from .modeling_flax_bert import *
24
+ from .modeling_tf_bert import *
25
+ from .tokenization_bert import *
26
+ from .tokenization_bert_fast import *
27
+ from .tokenization_bert_tf import *
28
+ else:
29
+ import sys
30
+
31
+ _file = globals()["__file__"]
32
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/bert/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (829 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-312.pyc ADDED
Binary file (7.01 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-312.pyc ADDED
Binary file (92.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-312.pyc ADDED
Binary file (70 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-312.pyc ADDED
Binary file (95.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-312.pyc ADDED
Binary file (22.6 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-312.pyc ADDED
Binary file (7.91 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-312.pyc ADDED
Binary file (12.6 kB). View file
 
lib/python3.12/site-packages/transformers/models/bert/configuration_bert.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """BERT model configuration"""
17
+
18
+ from collections import OrderedDict
19
+ from typing import Mapping
20
+
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class BertConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`BertModel`] or a [`TFBertModel`]. It is used to
32
+ instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
33
+ configuration with the defaults will yield a similar configuration to that of the BERT
34
+ [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 30522):
42
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
44
+ hidden_size (`int`, *optional*, defaults to 768):
45
+ Dimensionality of the encoder layers and the pooler layer.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention probabilities.
59
+ max_position_embeddings (`int`, *optional*, defaults to 512):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ type_vocab_size (`int`, *optional*, defaults to 2):
63
+ The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
67
+ The epsilon used by the layer normalization layers.
68
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
69
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
70
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
71
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
72
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
73
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
74
+ is_decoder (`bool`, *optional*, defaults to `False`):
75
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ classifier_dropout (`float`, *optional*):
80
+ The dropout ratio for the classification head.
81
+
82
+ Examples:
83
+
84
+ ```python
85
+ >>> from transformers import BertConfig, BertModel
86
+
87
+ >>> # Initializing a BERT google-bert/bert-base-uncased style configuration
88
+ >>> configuration = BertConfig()
89
+
90
+ >>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
91
+ >>> model = BertModel(configuration)
92
+
93
+ >>> # Accessing the model configuration
94
+ >>> configuration = model.config
95
+ ```"""
96
+
97
+ model_type = "bert"
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_size=30522,
102
+ hidden_size=768,
103
+ num_hidden_layers=12,
104
+ num_attention_heads=12,
105
+ intermediate_size=3072,
106
+ hidden_act="gelu",
107
+ hidden_dropout_prob=0.1,
108
+ attention_probs_dropout_prob=0.1,
109
+ max_position_embeddings=512,
110
+ type_vocab_size=2,
111
+ initializer_range=0.02,
112
+ layer_norm_eps=1e-12,
113
+ pad_token_id=0,
114
+ position_embedding_type="absolute",
115
+ use_cache=True,
116
+ classifier_dropout=None,
117
+ **kwargs,
118
+ ):
119
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
120
+
121
+ self.vocab_size = vocab_size
122
+ self.hidden_size = hidden_size
123
+ self.num_hidden_layers = num_hidden_layers
124
+ self.num_attention_heads = num_attention_heads
125
+ self.hidden_act = hidden_act
126
+ self.intermediate_size = intermediate_size
127
+ self.hidden_dropout_prob = hidden_dropout_prob
128
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
129
+ self.max_position_embeddings = max_position_embeddings
130
+ self.type_vocab_size = type_vocab_size
131
+ self.initializer_range = initializer_range
132
+ self.layer_norm_eps = layer_norm_eps
133
+ self.position_embedding_type = position_embedding_type
134
+ self.use_cache = use_cache
135
+ self.classifier_dropout = classifier_dropout
136
+
137
+
138
+ class BertOnnxConfig(OnnxConfig):
139
+ @property
140
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
141
+ if self.task == "multiple-choice":
142
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
143
+ else:
144
+ dynamic_axis = {0: "batch", 1: "sequence"}
145
+ return OrderedDict(
146
+ [
147
+ ("input_ids", dynamic_axis),
148
+ ("attention_mask", dynamic_axis),
149
+ ("token_type_ids", dynamic_axis),
150
+ ]
151
+ )
152
+
153
+
154
+ __all__ = ["BertConfig", "BertOnnxConfig"]
lib/python3.12/site-packages/transformers/models/bert/modeling_bert.py ADDED
@@ -0,0 +1,2019 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch BERT model."""
17
+
18
+ import math
19
+ import os
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from packaging import version
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from ...activations import ACT2FN
31
+ from ...generation import GenerationMixin
32
+ from ...modeling_attn_mask_utils import (
33
+ _prepare_4d_attention_mask_for_sdpa,
34
+ _prepare_4d_causal_attention_mask_for_sdpa,
35
+ )
36
+ from ...modeling_outputs import (
37
+ BaseModelOutputWithPastAndCrossAttentions,
38
+ BaseModelOutputWithPoolingAndCrossAttentions,
39
+ CausalLMOutputWithCrossAttentions,
40
+ MaskedLMOutput,
41
+ MultipleChoiceModelOutput,
42
+ NextSentencePredictorOutput,
43
+ QuestionAnsweringModelOutput,
44
+ SequenceClassifierOutput,
45
+ TokenClassifierOutput,
46
+ )
47
+ from ...modeling_utils import PreTrainedModel
48
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
49
+ from ...utils import (
50
+ ModelOutput,
51
+ add_code_sample_docstrings,
52
+ add_start_docstrings,
53
+ add_start_docstrings_to_model_forward,
54
+ get_torch_version,
55
+ logging,
56
+ replace_return_docstrings,
57
+ )
58
+ from .configuration_bert import BertConfig
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
64
+ _CONFIG_FOR_DOC = "BertConfig"
65
+
66
+ # TokenClassification docstring
67
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
68
+ _TOKEN_CLASS_EXPECTED_OUTPUT = (
69
+ "['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
70
+ )
71
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.01
72
+
73
+ # QuestionAnswering docstring
74
+ _CHECKPOINT_FOR_QA = "deepset/bert-base-cased-squad2"
75
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
76
+ _QA_EXPECTED_LOSS = 7.41
77
+ _QA_TARGET_START_INDEX = 14
78
+ _QA_TARGET_END_INDEX = 15
79
+
80
+ # SequenceClassification docstring
81
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "textattack/bert-base-uncased-yelp-polarity"
82
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
83
+ _SEQ_CLASS_EXPECTED_LOSS = 0.01
84
+
85
+
86
+ def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
87
+ """Load tf checkpoints in a pytorch model."""
88
+ try:
89
+ import re
90
+
91
+ import numpy as np
92
+ import tensorflow as tf
93
+ except ImportError:
94
+ logger.error(
95
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
96
+ "https://www.tensorflow.org/install/ for installation instructions."
97
+ )
98
+ raise
99
+ tf_path = os.path.abspath(tf_checkpoint_path)
100
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
101
+ # Load weights from TF model
102
+ init_vars = tf.train.list_variables(tf_path)
103
+ names = []
104
+ arrays = []
105
+ for name, shape in init_vars:
106
+ logger.info(f"Loading TF weight {name} with shape {shape}")
107
+ array = tf.train.load_variable(tf_path, name)
108
+ names.append(name)
109
+ arrays.append(array)
110
+
111
+ for name, array in zip(names, arrays):
112
+ name = name.split("/")
113
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
114
+ # which are not required for using pretrained model
115
+ if any(
116
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
117
+ for n in name
118
+ ):
119
+ logger.info(f"Skipping {'/'.join(name)}")
120
+ continue
121
+ pointer = model
122
+ for m_name in name:
123
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
124
+ scope_names = re.split(r"_(\d+)", m_name)
125
+ else:
126
+ scope_names = [m_name]
127
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
128
+ pointer = getattr(pointer, "weight")
129
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
130
+ pointer = getattr(pointer, "bias")
131
+ elif scope_names[0] == "output_weights":
132
+ pointer = getattr(pointer, "weight")
133
+ elif scope_names[0] == "squad":
134
+ pointer = getattr(pointer, "classifier")
135
+ else:
136
+ try:
137
+ pointer = getattr(pointer, scope_names[0])
138
+ except AttributeError:
139
+ logger.info(f"Skipping {'/'.join(name)}")
140
+ continue
141
+ if len(scope_names) >= 2:
142
+ num = int(scope_names[1])
143
+ pointer = pointer[num]
144
+ if m_name[-11:] == "_embeddings":
145
+ pointer = getattr(pointer, "weight")
146
+ elif m_name == "kernel":
147
+ array = np.transpose(array)
148
+ try:
149
+ if pointer.shape != array.shape:
150
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
151
+ except ValueError as e:
152
+ e.args += (pointer.shape, array.shape)
153
+ raise
154
+ logger.info(f"Initialize PyTorch weight {name}")
155
+ pointer.data = torch.from_numpy(array)
156
+ return model
157
+
158
+
159
+ class BertEmbeddings(nn.Module):
160
+ """Construct the embeddings from word, position and token_type embeddings."""
161
+
162
+ def __init__(self, config):
163
+ super().__init__()
164
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
165
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
166
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
167
+
168
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
169
+ # any TensorFlow checkpoint file
170
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
171
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
172
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
173
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
174
+ self.register_buffer(
175
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
176
+ )
177
+ self.register_buffer(
178
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
179
+ )
180
+
181
+ def forward(
182
+ self,
183
+ input_ids: Optional[torch.LongTensor] = None,
184
+ token_type_ids: Optional[torch.LongTensor] = None,
185
+ position_ids: Optional[torch.LongTensor] = None,
186
+ inputs_embeds: Optional[torch.FloatTensor] = None,
187
+ past_key_values_length: int = 0,
188
+ ) -> torch.Tensor:
189
+ if input_ids is not None:
190
+ input_shape = input_ids.size()
191
+ else:
192
+ input_shape = inputs_embeds.size()[:-1]
193
+
194
+ seq_length = input_shape[1]
195
+
196
+ if position_ids is None:
197
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
198
+
199
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
200
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
201
+ # issue #5664
202
+ if token_type_ids is None:
203
+ if hasattr(self, "token_type_ids"):
204
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
205
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
206
+ token_type_ids = buffered_token_type_ids_expanded
207
+ else:
208
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
209
+
210
+ if inputs_embeds is None:
211
+ inputs_embeds = self.word_embeddings(input_ids)
212
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
213
+
214
+ embeddings = inputs_embeds + token_type_embeddings
215
+ if self.position_embedding_type == "absolute":
216
+ position_embeddings = self.position_embeddings(position_ids)
217
+ embeddings += position_embeddings
218
+ embeddings = self.LayerNorm(embeddings)
219
+ embeddings = self.dropout(embeddings)
220
+ return embeddings
221
+
222
+
223
+ class BertSelfAttention(nn.Module):
224
+ def __init__(self, config, position_embedding_type=None):
225
+ super().__init__()
226
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
227
+ raise ValueError(
228
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
229
+ f"heads ({config.num_attention_heads})"
230
+ )
231
+
232
+ self.num_attention_heads = config.num_attention_heads
233
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
234
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
235
+
236
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
237
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
238
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
239
+
240
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
241
+ self.position_embedding_type = position_embedding_type or getattr(
242
+ config, "position_embedding_type", "absolute"
243
+ )
244
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
245
+ self.max_position_embeddings = config.max_position_embeddings
246
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
247
+
248
+ self.is_decoder = config.is_decoder
249
+
250
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
251
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
252
+ x = x.view(new_x_shape)
253
+ return x.permute(0, 2, 1, 3)
254
+
255
+ def forward(
256
+ self,
257
+ hidden_states: torch.Tensor,
258
+ attention_mask: Optional[torch.FloatTensor] = None,
259
+ head_mask: Optional[torch.FloatTensor] = None,
260
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
261
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
262
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
263
+ output_attentions: Optional[bool] = False,
264
+ ) -> Tuple[torch.Tensor]:
265
+ mixed_query_layer = self.query(hidden_states)
266
+
267
+ # If this is instantiated as a cross-attention module, the keys
268
+ # and values come from an encoder; the attention mask needs to be
269
+ # such that the encoder's padding tokens are not attended to.
270
+ is_cross_attention = encoder_hidden_states is not None
271
+
272
+ if is_cross_attention and past_key_value is not None:
273
+ # reuse k,v, cross_attentions
274
+ key_layer = past_key_value[0]
275
+ value_layer = past_key_value[1]
276
+ attention_mask = encoder_attention_mask
277
+ elif is_cross_attention:
278
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
279
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
280
+ attention_mask = encoder_attention_mask
281
+ elif past_key_value is not None:
282
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
283
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
284
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
285
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
286
+ else:
287
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
288
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
289
+
290
+ query_layer = self.transpose_for_scores(mixed_query_layer)
291
+
292
+ use_cache = past_key_value is not None
293
+ if self.is_decoder:
294
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
295
+ # Further calls to cross_attention layer can then reuse all cross-attention
296
+ # key/value_states (first "if" case)
297
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
298
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
299
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
300
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
301
+ past_key_value = (key_layer, value_layer)
302
+
303
+ # Take the dot product between "query" and "key" to get the raw attention scores.
304
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
305
+
306
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
307
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
308
+ if use_cache:
309
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
310
+ -1, 1
311
+ )
312
+ else:
313
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
314
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
315
+ distance = position_ids_l - position_ids_r
316
+
317
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
318
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
319
+
320
+ if self.position_embedding_type == "relative_key":
321
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
322
+ attention_scores = attention_scores + relative_position_scores
323
+ elif self.position_embedding_type == "relative_key_query":
324
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
325
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
326
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
327
+
328
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
329
+ if attention_mask is not None:
330
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
331
+ attention_scores = attention_scores + attention_mask
332
+
333
+ # Normalize the attention scores to probabilities.
334
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
335
+
336
+ # This is actually dropping out entire tokens to attend to, which might
337
+ # seem a bit unusual, but is taken from the original Transformer paper.
338
+ attention_probs = self.dropout(attention_probs)
339
+
340
+ # Mask heads if we want to
341
+ if head_mask is not None:
342
+ attention_probs = attention_probs * head_mask
343
+
344
+ context_layer = torch.matmul(attention_probs, value_layer)
345
+
346
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
347
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
348
+ context_layer = context_layer.view(new_context_layer_shape)
349
+
350
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
351
+
352
+ if self.is_decoder:
353
+ outputs = outputs + (past_key_value,)
354
+ return outputs
355
+
356
+
357
+ class BertSdpaSelfAttention(BertSelfAttention):
358
+ def __init__(self, config, position_embedding_type=None):
359
+ super().__init__(config, position_embedding_type=position_embedding_type)
360
+ self.dropout_prob = config.attention_probs_dropout_prob
361
+ self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
362
+
363
+ # Adapted from BertSelfAttention
364
+ def forward(
365
+ self,
366
+ hidden_states: torch.Tensor,
367
+ attention_mask: Optional[torch.Tensor] = None,
368
+ head_mask: Optional[torch.FloatTensor] = None,
369
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
370
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
371
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
372
+ output_attentions: Optional[bool] = False,
373
+ ) -> Tuple[torch.Tensor]:
374
+ if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
375
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
376
+ logger.warning_once(
377
+ "BertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
378
+ "non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
379
+ "the manual attention implementation, but specifying the manual implementation will be required from "
380
+ "Transformers version v5.0.0 onwards. This warning can be removed using the argument "
381
+ '`attn_implementation="eager"` when loading the model.'
382
+ )
383
+ return super().forward(
384
+ hidden_states,
385
+ attention_mask,
386
+ head_mask,
387
+ encoder_hidden_states,
388
+ encoder_attention_mask,
389
+ past_key_value,
390
+ output_attentions,
391
+ )
392
+
393
+ bsz, tgt_len, _ = hidden_states.size()
394
+
395
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
396
+
397
+ # If this is instantiated as a cross-attention module, the keys and values come from an encoder; the attention
398
+ # mask needs to be such that the encoder's padding tokens are not attended to.
399
+ is_cross_attention = encoder_hidden_states is not None
400
+
401
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
402
+ attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
403
+
404
+ # Check `seq_length` of `past_key_value` == `len(current_states)` to support prefix tuning
405
+ if is_cross_attention and past_key_value and past_key_value[0].shape[2] == current_states.shape[1]:
406
+ key_layer, value_layer = past_key_value
407
+ else:
408
+ key_layer = self.transpose_for_scores(self.key(current_states))
409
+ value_layer = self.transpose_for_scores(self.value(current_states))
410
+ if past_key_value is not None and not is_cross_attention:
411
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
412
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
413
+
414
+ if self.is_decoder:
415
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
416
+ # Further calls to cross_attention layer can then reuse all cross-attention
417
+ # key/value_states (first "if" case)
418
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
419
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
420
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
421
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
422
+ past_key_value = (key_layer, value_layer)
423
+
424
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
425
+ # attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
426
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
427
+ if self.require_contiguous_qkv and query_layer.device.type == "cuda" and attention_mask is not None:
428
+ query_layer = query_layer.contiguous()
429
+ key_layer = key_layer.contiguous()
430
+ value_layer = value_layer.contiguous()
431
+
432
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
433
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
434
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
435
+ # a causal mask in case tgt_len == 1.
436
+ is_causal = (
437
+ True if self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1 else False
438
+ )
439
+
440
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
441
+ query_layer,
442
+ key_layer,
443
+ value_layer,
444
+ attn_mask=attention_mask,
445
+ dropout_p=self.dropout_prob if self.training else 0.0,
446
+ is_causal=is_causal,
447
+ )
448
+
449
+ attn_output = attn_output.transpose(1, 2)
450
+ attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
451
+
452
+ outputs = (attn_output,)
453
+ if self.is_decoder:
454
+ outputs = outputs + (past_key_value,)
455
+ return outputs
456
+
457
+
458
+ class BertSelfOutput(nn.Module):
459
+ def __init__(self, config):
460
+ super().__init__()
461
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
462
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
463
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
464
+
465
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
466
+ hidden_states = self.dense(hidden_states)
467
+ hidden_states = self.dropout(hidden_states)
468
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
469
+ return hidden_states
470
+
471
+
472
+ BERT_SELF_ATTENTION_CLASSES = {
473
+ "eager": BertSelfAttention,
474
+ "sdpa": BertSdpaSelfAttention,
475
+ }
476
+
477
+
478
+ class BertAttention(nn.Module):
479
+ def __init__(self, config, position_embedding_type=None):
480
+ super().__init__()
481
+ self.self = BERT_SELF_ATTENTION_CLASSES[config._attn_implementation](
482
+ config, position_embedding_type=position_embedding_type
483
+ )
484
+ self.output = BertSelfOutput(config)
485
+ self.pruned_heads = set()
486
+
487
+ def prune_heads(self, heads):
488
+ if len(heads) == 0:
489
+ return
490
+ heads, index = find_pruneable_heads_and_indices(
491
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
492
+ )
493
+
494
+ # Prune linear layers
495
+ self.self.query = prune_linear_layer(self.self.query, index)
496
+ self.self.key = prune_linear_layer(self.self.key, index)
497
+ self.self.value = prune_linear_layer(self.self.value, index)
498
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
499
+
500
+ # Update hyper params and store pruned heads
501
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
502
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
503
+ self.pruned_heads = self.pruned_heads.union(heads)
504
+
505
+ def forward(
506
+ self,
507
+ hidden_states: torch.Tensor,
508
+ attention_mask: Optional[torch.FloatTensor] = None,
509
+ head_mask: Optional[torch.FloatTensor] = None,
510
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
511
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
512
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
513
+ output_attentions: Optional[bool] = False,
514
+ ) -> Tuple[torch.Tensor]:
515
+ self_outputs = self.self(
516
+ hidden_states,
517
+ attention_mask,
518
+ head_mask,
519
+ encoder_hidden_states,
520
+ encoder_attention_mask,
521
+ past_key_value,
522
+ output_attentions,
523
+ )
524
+ attention_output = self.output(self_outputs[0], hidden_states)
525
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
526
+ return outputs
527
+
528
+
529
+ class BertIntermediate(nn.Module):
530
+ def __init__(self, config):
531
+ super().__init__()
532
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
533
+ if isinstance(config.hidden_act, str):
534
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
535
+ else:
536
+ self.intermediate_act_fn = config.hidden_act
537
+
538
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
539
+ hidden_states = self.dense(hidden_states)
540
+ hidden_states = self.intermediate_act_fn(hidden_states)
541
+ return hidden_states
542
+
543
+
544
+ class BertOutput(nn.Module):
545
+ def __init__(self, config):
546
+ super().__init__()
547
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
548
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
549
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
550
+
551
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
552
+ hidden_states = self.dense(hidden_states)
553
+ hidden_states = self.dropout(hidden_states)
554
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
555
+ return hidden_states
556
+
557
+
558
+ class BertLayer(nn.Module):
559
+ def __init__(self, config):
560
+ super().__init__()
561
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
562
+ self.seq_len_dim = 1
563
+ self.attention = BertAttention(config)
564
+ self.is_decoder = config.is_decoder
565
+ self.add_cross_attention = config.add_cross_attention
566
+ if self.add_cross_attention:
567
+ if not self.is_decoder:
568
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
569
+ self.crossattention = BertAttention(config, position_embedding_type="absolute")
570
+ self.intermediate = BertIntermediate(config)
571
+ self.output = BertOutput(config)
572
+
573
+ def forward(
574
+ self,
575
+ hidden_states: torch.Tensor,
576
+ attention_mask: Optional[torch.FloatTensor] = None,
577
+ head_mask: Optional[torch.FloatTensor] = None,
578
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
579
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
580
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
581
+ output_attentions: Optional[bool] = False,
582
+ ) -> Tuple[torch.Tensor]:
583
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
584
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
585
+ self_attention_outputs = self.attention(
586
+ hidden_states,
587
+ attention_mask,
588
+ head_mask,
589
+ output_attentions=output_attentions,
590
+ past_key_value=self_attn_past_key_value,
591
+ )
592
+ attention_output = self_attention_outputs[0]
593
+
594
+ # if decoder, the last output is tuple of self-attn cache
595
+ if self.is_decoder:
596
+ outputs = self_attention_outputs[1:-1]
597
+ present_key_value = self_attention_outputs[-1]
598
+ else:
599
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
600
+
601
+ cross_attn_present_key_value = None
602
+ if self.is_decoder and encoder_hidden_states is not None:
603
+ if not hasattr(self, "crossattention"):
604
+ raise ValueError(
605
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
606
+ " by setting `config.add_cross_attention=True`"
607
+ )
608
+
609
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
610
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
611
+ cross_attention_outputs = self.crossattention(
612
+ attention_output,
613
+ attention_mask,
614
+ head_mask,
615
+ encoder_hidden_states,
616
+ encoder_attention_mask,
617
+ cross_attn_past_key_value,
618
+ output_attentions,
619
+ )
620
+ attention_output = cross_attention_outputs[0]
621
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
622
+
623
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
624
+ cross_attn_present_key_value = cross_attention_outputs[-1]
625
+ present_key_value = present_key_value + cross_attn_present_key_value
626
+
627
+ layer_output = apply_chunking_to_forward(
628
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
629
+ )
630
+ outputs = (layer_output,) + outputs
631
+
632
+ # if decoder, return the attn key/values as the last output
633
+ if self.is_decoder:
634
+ outputs = outputs + (present_key_value,)
635
+
636
+ return outputs
637
+
638
+ def feed_forward_chunk(self, attention_output):
639
+ intermediate_output = self.intermediate(attention_output)
640
+ layer_output = self.output(intermediate_output, attention_output)
641
+ return layer_output
642
+
643
+
644
+ class BertEncoder(nn.Module):
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.config = config
648
+ self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
649
+ self.gradient_checkpointing = False
650
+
651
+ def forward(
652
+ self,
653
+ hidden_states: torch.Tensor,
654
+ attention_mask: Optional[torch.FloatTensor] = None,
655
+ head_mask: Optional[torch.FloatTensor] = None,
656
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
657
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
658
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
659
+ use_cache: Optional[bool] = None,
660
+ output_attentions: Optional[bool] = False,
661
+ output_hidden_states: Optional[bool] = False,
662
+ return_dict: Optional[bool] = True,
663
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
664
+ all_hidden_states = () if output_hidden_states else None
665
+ all_self_attentions = () if output_attentions else None
666
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
667
+
668
+ if self.gradient_checkpointing and self.training:
669
+ if use_cache:
670
+ logger.warning_once(
671
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
672
+ )
673
+ use_cache = False
674
+
675
+ next_decoder_cache = () if use_cache else None
676
+ for i, layer_module in enumerate(self.layer):
677
+ if output_hidden_states:
678
+ all_hidden_states = all_hidden_states + (hidden_states,)
679
+
680
+ layer_head_mask = head_mask[i] if head_mask is not None else None
681
+ past_key_value = past_key_values[i] if past_key_values is not None else None
682
+
683
+ if self.gradient_checkpointing and self.training:
684
+ layer_outputs = self._gradient_checkpointing_func(
685
+ layer_module.__call__,
686
+ hidden_states,
687
+ attention_mask,
688
+ layer_head_mask,
689
+ encoder_hidden_states,
690
+ encoder_attention_mask,
691
+ past_key_value,
692
+ output_attentions,
693
+ )
694
+ else:
695
+ layer_outputs = layer_module(
696
+ hidden_states,
697
+ attention_mask,
698
+ layer_head_mask,
699
+ encoder_hidden_states,
700
+ encoder_attention_mask,
701
+ past_key_value,
702
+ output_attentions,
703
+ )
704
+
705
+ hidden_states = layer_outputs[0]
706
+ if use_cache:
707
+ next_decoder_cache += (layer_outputs[-1],)
708
+ if output_attentions:
709
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
710
+ if self.config.add_cross_attention:
711
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
712
+
713
+ if output_hidden_states:
714
+ all_hidden_states = all_hidden_states + (hidden_states,)
715
+
716
+ if not return_dict:
717
+ return tuple(
718
+ v
719
+ for v in [
720
+ hidden_states,
721
+ next_decoder_cache,
722
+ all_hidden_states,
723
+ all_self_attentions,
724
+ all_cross_attentions,
725
+ ]
726
+ if v is not None
727
+ )
728
+ return BaseModelOutputWithPastAndCrossAttentions(
729
+ last_hidden_state=hidden_states,
730
+ past_key_values=next_decoder_cache,
731
+ hidden_states=all_hidden_states,
732
+ attentions=all_self_attentions,
733
+ cross_attentions=all_cross_attentions,
734
+ )
735
+
736
+
737
+ class BertPooler(nn.Module):
738
+ def __init__(self, config):
739
+ super().__init__()
740
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
741
+ self.activation = nn.Tanh()
742
+
743
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
744
+ # We "pool" the model by simply taking the hidden state corresponding
745
+ # to the first token.
746
+ first_token_tensor = hidden_states[:, 0]
747
+ pooled_output = self.dense(first_token_tensor)
748
+ pooled_output = self.activation(pooled_output)
749
+ return pooled_output
750
+
751
+
752
+ class BertPredictionHeadTransform(nn.Module):
753
+ def __init__(self, config):
754
+ super().__init__()
755
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
756
+ if isinstance(config.hidden_act, str):
757
+ self.transform_act_fn = ACT2FN[config.hidden_act]
758
+ else:
759
+ self.transform_act_fn = config.hidden_act
760
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
761
+
762
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
763
+ hidden_states = self.dense(hidden_states)
764
+ hidden_states = self.transform_act_fn(hidden_states)
765
+ hidden_states = self.LayerNorm(hidden_states)
766
+ return hidden_states
767
+
768
+
769
+ class BertLMPredictionHead(nn.Module):
770
+ def __init__(self, config):
771
+ super().__init__()
772
+ self.transform = BertPredictionHeadTransform(config)
773
+
774
+ # The output weights are the same as the input embeddings, but there is
775
+ # an output-only bias for each token.
776
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
777
+
778
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
779
+
780
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
781
+ self.decoder.bias = self.bias
782
+
783
+ def _tie_weights(self):
784
+ self.decoder.bias = self.bias
785
+
786
+ def forward(self, hidden_states):
787
+ hidden_states = self.transform(hidden_states)
788
+ hidden_states = self.decoder(hidden_states)
789
+ return hidden_states
790
+
791
+
792
+ class BertOnlyMLMHead(nn.Module):
793
+ def __init__(self, config):
794
+ super().__init__()
795
+ self.predictions = BertLMPredictionHead(config)
796
+
797
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
798
+ prediction_scores = self.predictions(sequence_output)
799
+ return prediction_scores
800
+
801
+
802
+ class BertOnlyNSPHead(nn.Module):
803
+ def __init__(self, config):
804
+ super().__init__()
805
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
806
+
807
+ def forward(self, pooled_output):
808
+ seq_relationship_score = self.seq_relationship(pooled_output)
809
+ return seq_relationship_score
810
+
811
+
812
+ class BertPreTrainingHeads(nn.Module):
813
+ def __init__(self, config):
814
+ super().__init__()
815
+ self.predictions = BertLMPredictionHead(config)
816
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
817
+
818
+ def forward(self, sequence_output, pooled_output):
819
+ prediction_scores = self.predictions(sequence_output)
820
+ seq_relationship_score = self.seq_relationship(pooled_output)
821
+ return prediction_scores, seq_relationship_score
822
+
823
+
824
+ class BertPreTrainedModel(PreTrainedModel):
825
+ """
826
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
827
+ models.
828
+ """
829
+
830
+ config_class = BertConfig
831
+ load_tf_weights = load_tf_weights_in_bert
832
+ base_model_prefix = "bert"
833
+ supports_gradient_checkpointing = True
834
+ _supports_sdpa = True
835
+
836
+ def _init_weights(self, module):
837
+ """Initialize the weights"""
838
+ if isinstance(module, nn.Linear):
839
+ # Slightly different from the TF version which uses truncated_normal for initialization
840
+ # cf https://github.com/pytorch/pytorch/pull/5617
841
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
842
+ if module.bias is not None:
843
+ module.bias.data.zero_()
844
+ elif isinstance(module, nn.Embedding):
845
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
846
+ if module.padding_idx is not None:
847
+ module.weight.data[module.padding_idx].zero_()
848
+ elif isinstance(module, nn.LayerNorm):
849
+ module.bias.data.zero_()
850
+ module.weight.data.fill_(1.0)
851
+ elif isinstance(module, BertLMPredictionHead):
852
+ module.bias.data.zero_()
853
+
854
+
855
+ @dataclass
856
+ class BertForPreTrainingOutput(ModelOutput):
857
+ """
858
+ Output type of [`BertForPreTraining`].
859
+
860
+ Args:
861
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
862
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
863
+ (classification) loss.
864
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
865
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
866
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
867
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
868
+ before SoftMax).
869
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
870
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
871
+ shape `(batch_size, sequence_length, hidden_size)`.
872
+
873
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
874
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
875
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
876
+ sequence_length)`.
877
+
878
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
879
+ heads.
880
+ """
881
+
882
+ loss: Optional[torch.FloatTensor] = None
883
+ prediction_logits: Optional[torch.FloatTensor] = None
884
+ seq_relationship_logits: Optional[torch.FloatTensor] = None
885
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
886
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
887
+
888
+
889
+ BERT_START_DOCSTRING = r"""
890
+
891
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
892
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
893
+ etc.)
894
+
895
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
896
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
897
+ and behavior.
898
+
899
+ Parameters:
900
+ config ([`BertConfig`]): Model configuration class with all the parameters of the model.
901
+ Initializing with a config file does not load the weights associated with the model, only the
902
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
903
+ """
904
+
905
+ BERT_INPUTS_DOCSTRING = r"""
906
+ Args:
907
+ input_ids (`torch.LongTensor` of shape `({0})`):
908
+ Indices of input sequence tokens in the vocabulary.
909
+
910
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
911
+ [`PreTrainedTokenizer.__call__`] for details.
912
+
913
+ [What are input IDs?](../glossary#input-ids)
914
+ attention_mask (`torch.FloatTensor` of shape `({0})`or `(batch_size, sequence_length, target_length)`, *optional*):
915
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
916
+
917
+ - 1 for tokens that are **not masked**,
918
+ - 0 for tokens that are **masked**.
919
+
920
+ [What are attention masks?](../glossary#attention-mask)
921
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
922
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
923
+ 1]`:
924
+
925
+ - 0 corresponds to a *sentence A* token,
926
+ - 1 corresponds to a *sentence B* token.
927
+
928
+ [What are token type IDs?](../glossary#token-type-ids)
929
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
930
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
931
+ config.max_position_embeddings - 1]`.
932
+
933
+ [What are position IDs?](../glossary#position-ids)
934
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
935
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
936
+
937
+ - 1 indicates the head is **not masked**,
938
+ - 0 indicates the head is **masked**.
939
+
940
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
941
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
942
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
943
+ model's internal embedding lookup matrix.
944
+ output_attentions (`bool`, *optional*):
945
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
946
+ tensors for more detail.
947
+ output_hidden_states (`bool`, *optional*):
948
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
949
+ more detail.
950
+ return_dict (`bool`, *optional*):
951
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
952
+ """
953
+
954
+
955
+ @add_start_docstrings(
956
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
957
+ BERT_START_DOCSTRING,
958
+ )
959
+ class BertModel(BertPreTrainedModel):
960
+ """
961
+
962
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
963
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
964
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
965
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
966
+
967
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
968
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
969
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
970
+ """
971
+
972
+ _no_split_modules = ["BertEmbeddings", "BertLayer"]
973
+
974
+ def __init__(self, config, add_pooling_layer=True):
975
+ super().__init__(config)
976
+ self.config = config
977
+
978
+ self.embeddings = BertEmbeddings(config)
979
+ self.encoder = BertEncoder(config)
980
+
981
+ self.pooler = BertPooler(config) if add_pooling_layer else None
982
+
983
+ self.attn_implementation = config._attn_implementation
984
+ self.position_embedding_type = config.position_embedding_type
985
+
986
+ # Initialize weights and apply final processing
987
+ self.post_init()
988
+
989
+ def get_input_embeddings(self):
990
+ return self.embeddings.word_embeddings
991
+
992
+ def set_input_embeddings(self, value):
993
+ self.embeddings.word_embeddings = value
994
+
995
+ def _prune_heads(self, heads_to_prune):
996
+ """
997
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
998
+ class PreTrainedModel
999
+ """
1000
+ for layer, heads in heads_to_prune.items():
1001
+ self.encoder.layer[layer].attention.prune_heads(heads)
1002
+
1003
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1004
+ @add_code_sample_docstrings(
1005
+ checkpoint=_CHECKPOINT_FOR_DOC,
1006
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
1007
+ config_class=_CONFIG_FOR_DOC,
1008
+ )
1009
+ def forward(
1010
+ self,
1011
+ input_ids: Optional[torch.Tensor] = None,
1012
+ attention_mask: Optional[torch.Tensor] = None,
1013
+ token_type_ids: Optional[torch.Tensor] = None,
1014
+ position_ids: Optional[torch.Tensor] = None,
1015
+ head_mask: Optional[torch.Tensor] = None,
1016
+ inputs_embeds: Optional[torch.Tensor] = None,
1017
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1018
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1019
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1020
+ use_cache: Optional[bool] = None,
1021
+ output_attentions: Optional[bool] = None,
1022
+ output_hidden_states: Optional[bool] = None,
1023
+ return_dict: Optional[bool] = None,
1024
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
1025
+ r"""
1026
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1027
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1028
+ the model is configured as a decoder.
1029
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, target_length)`, *optional*):
1030
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1031
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1032
+
1033
+ - 1 for tokens that are **not masked**,
1034
+ - 0 for tokens that are **masked**.
1035
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1036
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1037
+
1038
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1039
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1040
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1041
+ use_cache (`bool`, *optional*):
1042
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1043
+ `past_key_values`).
1044
+ """
1045
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1046
+ output_hidden_states = (
1047
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1048
+ )
1049
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1050
+
1051
+ if self.config.is_decoder:
1052
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1053
+ else:
1054
+ use_cache = False
1055
+
1056
+ if input_ids is not None and inputs_embeds is not None:
1057
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1058
+ elif input_ids is not None:
1059
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1060
+ input_shape = input_ids.size()
1061
+ elif inputs_embeds is not None:
1062
+ input_shape = inputs_embeds.size()[:-1]
1063
+ else:
1064
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1065
+
1066
+ batch_size, seq_length = input_shape
1067
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1068
+
1069
+ # past_key_values_length
1070
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1071
+
1072
+ if token_type_ids is None:
1073
+ if hasattr(self.embeddings, "token_type_ids"):
1074
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
1075
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
1076
+ token_type_ids = buffered_token_type_ids_expanded
1077
+ else:
1078
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
1079
+
1080
+ embedding_output = self.embeddings(
1081
+ input_ids=input_ids,
1082
+ position_ids=position_ids,
1083
+ token_type_ids=token_type_ids,
1084
+ inputs_embeds=inputs_embeds,
1085
+ past_key_values_length=past_key_values_length,
1086
+ )
1087
+
1088
+ if attention_mask is None:
1089
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
1090
+
1091
+ use_sdpa_attention_masks = (
1092
+ self.attn_implementation == "sdpa"
1093
+ and self.position_embedding_type == "absolute"
1094
+ and head_mask is None
1095
+ and not output_attentions
1096
+ )
1097
+
1098
+ # Expand the attention mask
1099
+ if use_sdpa_attention_masks and attention_mask.dim() == 2:
1100
+ # Expand the attention mask for SDPA.
1101
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
1102
+ if self.config.is_decoder:
1103
+ extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1104
+ attention_mask,
1105
+ input_shape,
1106
+ embedding_output,
1107
+ past_key_values_length,
1108
+ )
1109
+ else:
1110
+ extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1111
+ attention_mask, embedding_output.dtype, tgt_len=seq_length
1112
+ )
1113
+ else:
1114
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
1115
+ # ourselves in which case we just need to make it broadcastable to all heads.
1116
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
1117
+
1118
+ # If a 2D or 3D attention mask is provided for the cross-attention
1119
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1120
+ if self.config.is_decoder and encoder_hidden_states is not None:
1121
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1122
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1123
+ if encoder_attention_mask is None:
1124
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1125
+
1126
+ if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
1127
+ # Expand the attention mask for SDPA.
1128
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
1129
+ encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1130
+ encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
1131
+ )
1132
+ else:
1133
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1134
+ else:
1135
+ encoder_extended_attention_mask = None
1136
+
1137
+ # Prepare head mask if needed
1138
+ # 1.0 in head_mask indicate we keep the head
1139
+ # attention_probs has shape bsz x n_heads x N x N
1140
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1141
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1142
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1143
+
1144
+ encoder_outputs = self.encoder(
1145
+ embedding_output,
1146
+ attention_mask=extended_attention_mask,
1147
+ head_mask=head_mask,
1148
+ encoder_hidden_states=encoder_hidden_states,
1149
+ encoder_attention_mask=encoder_extended_attention_mask,
1150
+ past_key_values=past_key_values,
1151
+ use_cache=use_cache,
1152
+ output_attentions=output_attentions,
1153
+ output_hidden_states=output_hidden_states,
1154
+ return_dict=return_dict,
1155
+ )
1156
+ sequence_output = encoder_outputs[0]
1157
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1158
+
1159
+ if not return_dict:
1160
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1161
+
1162
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1163
+ last_hidden_state=sequence_output,
1164
+ pooler_output=pooled_output,
1165
+ past_key_values=encoder_outputs.past_key_values,
1166
+ hidden_states=encoder_outputs.hidden_states,
1167
+ attentions=encoder_outputs.attentions,
1168
+ cross_attentions=encoder_outputs.cross_attentions,
1169
+ )
1170
+
1171
+
1172
+ @add_start_docstrings(
1173
+ """
1174
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1175
+ sentence prediction (classification)` head.
1176
+ """,
1177
+ BERT_START_DOCSTRING,
1178
+ )
1179
+ class BertForPreTraining(BertPreTrainedModel):
1180
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1181
+
1182
+ def __init__(self, config):
1183
+ super().__init__(config)
1184
+
1185
+ self.bert = BertModel(config)
1186
+ self.cls = BertPreTrainingHeads(config)
1187
+
1188
+ # Initialize weights and apply final processing
1189
+ self.post_init()
1190
+
1191
+ def get_output_embeddings(self):
1192
+ return self.cls.predictions.decoder
1193
+
1194
+ def set_output_embeddings(self, new_embeddings):
1195
+ self.cls.predictions.decoder = new_embeddings
1196
+ self.cls.predictions.bias = new_embeddings.bias
1197
+
1198
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1199
+ @replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1200
+ def forward(
1201
+ self,
1202
+ input_ids: Optional[torch.Tensor] = None,
1203
+ attention_mask: Optional[torch.Tensor] = None,
1204
+ token_type_ids: Optional[torch.Tensor] = None,
1205
+ position_ids: Optional[torch.Tensor] = None,
1206
+ head_mask: Optional[torch.Tensor] = None,
1207
+ inputs_embeds: Optional[torch.Tensor] = None,
1208
+ labels: Optional[torch.Tensor] = None,
1209
+ next_sentence_label: Optional[torch.Tensor] = None,
1210
+ output_attentions: Optional[bool] = None,
1211
+ output_hidden_states: Optional[bool] = None,
1212
+ return_dict: Optional[bool] = None,
1213
+ ) -> Union[Tuple[torch.Tensor], BertForPreTrainingOutput]:
1214
+ r"""
1215
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1216
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1217
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1218
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1219
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1220
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1221
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1222
+
1223
+ - 0 indicates sequence B is a continuation of sequence A,
1224
+ - 1 indicates sequence B is a random sequence.
1225
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
1226
+ Used to hide legacy arguments that have been deprecated.
1227
+
1228
+ Returns:
1229
+
1230
+ Example:
1231
+
1232
+ ```python
1233
+ >>> from transformers import AutoTokenizer, BertForPreTraining
1234
+ >>> import torch
1235
+
1236
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1237
+ >>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
1238
+
1239
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1240
+ >>> outputs = model(**inputs)
1241
+
1242
+ >>> prediction_logits = outputs.prediction_logits
1243
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1244
+ ```
1245
+ """
1246
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1247
+
1248
+ outputs = self.bert(
1249
+ input_ids,
1250
+ attention_mask=attention_mask,
1251
+ token_type_ids=token_type_ids,
1252
+ position_ids=position_ids,
1253
+ head_mask=head_mask,
1254
+ inputs_embeds=inputs_embeds,
1255
+ output_attentions=output_attentions,
1256
+ output_hidden_states=output_hidden_states,
1257
+ return_dict=return_dict,
1258
+ )
1259
+
1260
+ sequence_output, pooled_output = outputs[:2]
1261
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1262
+
1263
+ total_loss = None
1264
+ if labels is not None and next_sentence_label is not None:
1265
+ loss_fct = CrossEntropyLoss()
1266
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1267
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1268
+ total_loss = masked_lm_loss + next_sentence_loss
1269
+
1270
+ if not return_dict:
1271
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1272
+ return ((total_loss,) + output) if total_loss is not None else output
1273
+
1274
+ return BertForPreTrainingOutput(
1275
+ loss=total_loss,
1276
+ prediction_logits=prediction_scores,
1277
+ seq_relationship_logits=seq_relationship_score,
1278
+ hidden_states=outputs.hidden_states,
1279
+ attentions=outputs.attentions,
1280
+ )
1281
+
1282
+
1283
+ @add_start_docstrings(
1284
+ """Bert Model with a `language modeling` head on top for CLM fine-tuning.""", BERT_START_DOCSTRING
1285
+ )
1286
+ class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
1287
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1288
+
1289
+ def __init__(self, config):
1290
+ super().__init__(config)
1291
+
1292
+ if not config.is_decoder:
1293
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
1294
+
1295
+ self.bert = BertModel(config, add_pooling_layer=False)
1296
+ self.cls = BertOnlyMLMHead(config)
1297
+
1298
+ # Initialize weights and apply final processing
1299
+ self.post_init()
1300
+
1301
+ def get_output_embeddings(self):
1302
+ return self.cls.predictions.decoder
1303
+
1304
+ def set_output_embeddings(self, new_embeddings):
1305
+ self.cls.predictions.decoder = new_embeddings
1306
+ self.cls.predictions.bias = new_embeddings.bias
1307
+
1308
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1309
+ @add_code_sample_docstrings(
1310
+ checkpoint=_CHECKPOINT_FOR_DOC,
1311
+ output_type=CausalLMOutputWithCrossAttentions,
1312
+ config_class=_CONFIG_FOR_DOC,
1313
+ )
1314
+ def forward(
1315
+ self,
1316
+ input_ids: Optional[torch.Tensor] = None,
1317
+ attention_mask: Optional[torch.Tensor] = None,
1318
+ token_type_ids: Optional[torch.Tensor] = None,
1319
+ position_ids: Optional[torch.Tensor] = None,
1320
+ head_mask: Optional[torch.Tensor] = None,
1321
+ inputs_embeds: Optional[torch.Tensor] = None,
1322
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1323
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1324
+ labels: Optional[torch.Tensor] = None,
1325
+ past_key_values: Optional[List[torch.Tensor]] = None,
1326
+ use_cache: Optional[bool] = None,
1327
+ output_attentions: Optional[bool] = None,
1328
+ output_hidden_states: Optional[bool] = None,
1329
+ return_dict: Optional[bool] = None,
1330
+ **loss_kwargs,
1331
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1332
+ r"""
1333
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1334
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1335
+ the model is configured as a decoder.
1336
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1337
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1338
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1339
+
1340
+ - 1 for tokens that are **not masked**,
1341
+ - 0 for tokens that are **masked**.
1342
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1343
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1344
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1345
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1346
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1347
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1348
+
1349
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1350
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1351
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1352
+ use_cache (`bool`, *optional*):
1353
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1354
+ `past_key_values`).
1355
+ """
1356
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1357
+ if labels is not None:
1358
+ use_cache = False
1359
+
1360
+ outputs = self.bert(
1361
+ input_ids,
1362
+ attention_mask=attention_mask,
1363
+ token_type_ids=token_type_ids,
1364
+ position_ids=position_ids,
1365
+ head_mask=head_mask,
1366
+ inputs_embeds=inputs_embeds,
1367
+ encoder_hidden_states=encoder_hidden_states,
1368
+ encoder_attention_mask=encoder_attention_mask,
1369
+ past_key_values=past_key_values,
1370
+ use_cache=use_cache,
1371
+ output_attentions=output_attentions,
1372
+ output_hidden_states=output_hidden_states,
1373
+ return_dict=return_dict,
1374
+ )
1375
+
1376
+ sequence_output = outputs[0]
1377
+ prediction_scores = self.cls(sequence_output)
1378
+
1379
+ lm_loss = None
1380
+ if labels is not None:
1381
+ lm_loss = self.loss_function(prediction_scores, labels, self.config.vocab_size, **loss_kwargs)
1382
+
1383
+ if not return_dict:
1384
+ output = (prediction_scores,) + outputs[2:]
1385
+ return ((lm_loss,) + output) if lm_loss is not None else output
1386
+
1387
+ return CausalLMOutputWithCrossAttentions(
1388
+ loss=lm_loss,
1389
+ logits=prediction_scores,
1390
+ past_key_values=outputs.past_key_values,
1391
+ hidden_states=outputs.hidden_states,
1392
+ attentions=outputs.attentions,
1393
+ cross_attentions=outputs.cross_attentions,
1394
+ )
1395
+
1396
+ def _reorder_cache(self, past_key_values, beam_idx):
1397
+ reordered_past = ()
1398
+ for layer_past in past_key_values:
1399
+ reordered_past += (
1400
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1401
+ )
1402
+ return reordered_past
1403
+
1404
+
1405
+ @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
1406
+ class BertForMaskedLM(BertPreTrainedModel):
1407
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1408
+
1409
+ def __init__(self, config):
1410
+ super().__init__(config)
1411
+
1412
+ if config.is_decoder:
1413
+ logger.warning(
1414
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
1415
+ "bi-directional self-attention."
1416
+ )
1417
+
1418
+ self.bert = BertModel(config, add_pooling_layer=False)
1419
+ self.cls = BertOnlyMLMHead(config)
1420
+
1421
+ # Initialize weights and apply final processing
1422
+ self.post_init()
1423
+
1424
+ def get_output_embeddings(self):
1425
+ return self.cls.predictions.decoder
1426
+
1427
+ def set_output_embeddings(self, new_embeddings):
1428
+ self.cls.predictions.decoder = new_embeddings
1429
+ self.cls.predictions.bias = new_embeddings.bias
1430
+
1431
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1432
+ @add_code_sample_docstrings(
1433
+ checkpoint=_CHECKPOINT_FOR_DOC,
1434
+ output_type=MaskedLMOutput,
1435
+ config_class=_CONFIG_FOR_DOC,
1436
+ expected_output="'paris'",
1437
+ expected_loss=0.88,
1438
+ )
1439
+ def forward(
1440
+ self,
1441
+ input_ids: Optional[torch.Tensor] = None,
1442
+ attention_mask: Optional[torch.Tensor] = None,
1443
+ token_type_ids: Optional[torch.Tensor] = None,
1444
+ position_ids: Optional[torch.Tensor] = None,
1445
+ head_mask: Optional[torch.Tensor] = None,
1446
+ inputs_embeds: Optional[torch.Tensor] = None,
1447
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1448
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1449
+ labels: Optional[torch.Tensor] = None,
1450
+ output_attentions: Optional[bool] = None,
1451
+ output_hidden_states: Optional[bool] = None,
1452
+ return_dict: Optional[bool] = None,
1453
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1454
+ r"""
1455
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1456
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1457
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1458
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1459
+ """
1460
+
1461
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1462
+
1463
+ outputs = self.bert(
1464
+ input_ids,
1465
+ attention_mask=attention_mask,
1466
+ token_type_ids=token_type_ids,
1467
+ position_ids=position_ids,
1468
+ head_mask=head_mask,
1469
+ inputs_embeds=inputs_embeds,
1470
+ encoder_hidden_states=encoder_hidden_states,
1471
+ encoder_attention_mask=encoder_attention_mask,
1472
+ output_attentions=output_attentions,
1473
+ output_hidden_states=output_hidden_states,
1474
+ return_dict=return_dict,
1475
+ )
1476
+
1477
+ sequence_output = outputs[0]
1478
+ prediction_scores = self.cls(sequence_output)
1479
+
1480
+ masked_lm_loss = None
1481
+ if labels is not None:
1482
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1483
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1484
+
1485
+ if not return_dict:
1486
+ output = (prediction_scores,) + outputs[2:]
1487
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1488
+
1489
+ return MaskedLMOutput(
1490
+ loss=masked_lm_loss,
1491
+ logits=prediction_scores,
1492
+ hidden_states=outputs.hidden_states,
1493
+ attentions=outputs.attentions,
1494
+ )
1495
+
1496
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1497
+ input_shape = input_ids.shape
1498
+ effective_batch_size = input_shape[0]
1499
+
1500
+ # add a dummy token
1501
+ if self.config.pad_token_id is None:
1502
+ raise ValueError("The PAD token should be defined for generation")
1503
+
1504
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1505
+ dummy_token = torch.full(
1506
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1507
+ )
1508
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1509
+
1510
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1511
+
1512
+ @classmethod
1513
+ def can_generate(cls) -> bool:
1514
+ """
1515
+ Legacy correction: BertForMaskedLM can't call `generate()` from GenerationMixin.
1516
+ Remove after v4.50, when we stop making `PreTrainedModel` inherit from `GenerationMixin`.
1517
+ """
1518
+ return False
1519
+
1520
+
1521
+ @add_start_docstrings(
1522
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1523
+ BERT_START_DOCSTRING,
1524
+ )
1525
+ class BertForNextSentencePrediction(BertPreTrainedModel):
1526
+ def __init__(self, config):
1527
+ super().__init__(config)
1528
+
1529
+ self.bert = BertModel(config)
1530
+ self.cls = BertOnlyNSPHead(config)
1531
+
1532
+ # Initialize weights and apply final processing
1533
+ self.post_init()
1534
+
1535
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1536
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1537
+ def forward(
1538
+ self,
1539
+ input_ids: Optional[torch.Tensor] = None,
1540
+ attention_mask: Optional[torch.Tensor] = None,
1541
+ token_type_ids: Optional[torch.Tensor] = None,
1542
+ position_ids: Optional[torch.Tensor] = None,
1543
+ head_mask: Optional[torch.Tensor] = None,
1544
+ inputs_embeds: Optional[torch.Tensor] = None,
1545
+ labels: Optional[torch.Tensor] = None,
1546
+ output_attentions: Optional[bool] = None,
1547
+ output_hidden_states: Optional[bool] = None,
1548
+ return_dict: Optional[bool] = None,
1549
+ **kwargs,
1550
+ ) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
1551
+ r"""
1552
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1553
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1554
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1555
+
1556
+ - 0 indicates sequence B is a continuation of sequence A,
1557
+ - 1 indicates sequence B is a random sequence.
1558
+
1559
+ Returns:
1560
+
1561
+ Example:
1562
+
1563
+ ```python
1564
+ >>> from transformers import AutoTokenizer, BertForNextSentencePrediction
1565
+ >>> import torch
1566
+
1567
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1568
+ >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1569
+
1570
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1571
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1572
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1573
+
1574
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1575
+ >>> logits = outputs.logits
1576
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1577
+ ```
1578
+ """
1579
+
1580
+ if "next_sentence_label" in kwargs:
1581
+ warnings.warn(
1582
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1583
+ " `labels` instead.",
1584
+ FutureWarning,
1585
+ )
1586
+ labels = kwargs.pop("next_sentence_label")
1587
+
1588
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1589
+
1590
+ outputs = self.bert(
1591
+ input_ids,
1592
+ attention_mask=attention_mask,
1593
+ token_type_ids=token_type_ids,
1594
+ position_ids=position_ids,
1595
+ head_mask=head_mask,
1596
+ inputs_embeds=inputs_embeds,
1597
+ output_attentions=output_attentions,
1598
+ output_hidden_states=output_hidden_states,
1599
+ return_dict=return_dict,
1600
+ )
1601
+
1602
+ pooled_output = outputs[1]
1603
+
1604
+ seq_relationship_scores = self.cls(pooled_output)
1605
+
1606
+ next_sentence_loss = None
1607
+ if labels is not None:
1608
+ loss_fct = CrossEntropyLoss()
1609
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1610
+
1611
+ if not return_dict:
1612
+ output = (seq_relationship_scores,) + outputs[2:]
1613
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1614
+
1615
+ return NextSentencePredictorOutput(
1616
+ loss=next_sentence_loss,
1617
+ logits=seq_relationship_scores,
1618
+ hidden_states=outputs.hidden_states,
1619
+ attentions=outputs.attentions,
1620
+ )
1621
+
1622
+
1623
+ @add_start_docstrings(
1624
+ """
1625
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1626
+ output) e.g. for GLUE tasks.
1627
+ """,
1628
+ BERT_START_DOCSTRING,
1629
+ )
1630
+ class BertForSequenceClassification(BertPreTrainedModel):
1631
+ def __init__(self, config):
1632
+ super().__init__(config)
1633
+ self.num_labels = config.num_labels
1634
+ self.config = config
1635
+
1636
+ self.bert = BertModel(config)
1637
+ classifier_dropout = (
1638
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1639
+ )
1640
+ self.dropout = nn.Dropout(classifier_dropout)
1641
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1642
+
1643
+ # Initialize weights and apply final processing
1644
+ self.post_init()
1645
+
1646
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1647
+ @add_code_sample_docstrings(
1648
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1649
+ output_type=SequenceClassifierOutput,
1650
+ config_class=_CONFIG_FOR_DOC,
1651
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1652
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1653
+ )
1654
+ def forward(
1655
+ self,
1656
+ input_ids: Optional[torch.Tensor] = None,
1657
+ attention_mask: Optional[torch.Tensor] = None,
1658
+ token_type_ids: Optional[torch.Tensor] = None,
1659
+ position_ids: Optional[torch.Tensor] = None,
1660
+ head_mask: Optional[torch.Tensor] = None,
1661
+ inputs_embeds: Optional[torch.Tensor] = None,
1662
+ labels: Optional[torch.Tensor] = None,
1663
+ output_attentions: Optional[bool] = None,
1664
+ output_hidden_states: Optional[bool] = None,
1665
+ return_dict: Optional[bool] = None,
1666
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1667
+ r"""
1668
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1669
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1670
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1671
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1672
+ """
1673
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1674
+
1675
+ outputs = self.bert(
1676
+ input_ids,
1677
+ attention_mask=attention_mask,
1678
+ token_type_ids=token_type_ids,
1679
+ position_ids=position_ids,
1680
+ head_mask=head_mask,
1681
+ inputs_embeds=inputs_embeds,
1682
+ output_attentions=output_attentions,
1683
+ output_hidden_states=output_hidden_states,
1684
+ return_dict=return_dict,
1685
+ )
1686
+
1687
+ pooled_output = outputs[1]
1688
+
1689
+ pooled_output = self.dropout(pooled_output)
1690
+ logits = self.classifier(pooled_output)
1691
+
1692
+ loss = None
1693
+ if labels is not None:
1694
+ if self.config.problem_type is None:
1695
+ if self.num_labels == 1:
1696
+ self.config.problem_type = "regression"
1697
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1698
+ self.config.problem_type = "single_label_classification"
1699
+ else:
1700
+ self.config.problem_type = "multi_label_classification"
1701
+
1702
+ if self.config.problem_type == "regression":
1703
+ loss_fct = MSELoss()
1704
+ if self.num_labels == 1:
1705
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1706
+ else:
1707
+ loss = loss_fct(logits, labels)
1708
+ elif self.config.problem_type == "single_label_classification":
1709
+ loss_fct = CrossEntropyLoss()
1710
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1711
+ elif self.config.problem_type == "multi_label_classification":
1712
+ loss_fct = BCEWithLogitsLoss()
1713
+ loss = loss_fct(logits, labels)
1714
+ if not return_dict:
1715
+ output = (logits,) + outputs[2:]
1716
+ return ((loss,) + output) if loss is not None else output
1717
+
1718
+ return SequenceClassifierOutput(
1719
+ loss=loss,
1720
+ logits=logits,
1721
+ hidden_states=outputs.hidden_states,
1722
+ attentions=outputs.attentions,
1723
+ )
1724
+
1725
+
1726
+ @add_start_docstrings(
1727
+ """
1728
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1729
+ softmax) e.g. for RocStories/SWAG tasks.
1730
+ """,
1731
+ BERT_START_DOCSTRING,
1732
+ )
1733
+ class BertForMultipleChoice(BertPreTrainedModel):
1734
+ def __init__(self, config):
1735
+ super().__init__(config)
1736
+
1737
+ self.bert = BertModel(config)
1738
+ classifier_dropout = (
1739
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1740
+ )
1741
+ self.dropout = nn.Dropout(classifier_dropout)
1742
+ self.classifier = nn.Linear(config.hidden_size, 1)
1743
+
1744
+ # Initialize weights and apply final processing
1745
+ self.post_init()
1746
+
1747
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1748
+ @add_code_sample_docstrings(
1749
+ checkpoint=_CHECKPOINT_FOR_DOC,
1750
+ output_type=MultipleChoiceModelOutput,
1751
+ config_class=_CONFIG_FOR_DOC,
1752
+ )
1753
+ def forward(
1754
+ self,
1755
+ input_ids: Optional[torch.Tensor] = None,
1756
+ attention_mask: Optional[torch.Tensor] = None,
1757
+ token_type_ids: Optional[torch.Tensor] = None,
1758
+ position_ids: Optional[torch.Tensor] = None,
1759
+ head_mask: Optional[torch.Tensor] = None,
1760
+ inputs_embeds: Optional[torch.Tensor] = None,
1761
+ labels: Optional[torch.Tensor] = None,
1762
+ output_attentions: Optional[bool] = None,
1763
+ output_hidden_states: Optional[bool] = None,
1764
+ return_dict: Optional[bool] = None,
1765
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1766
+ r"""
1767
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1768
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1769
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1770
+ `input_ids` above)
1771
+ """
1772
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1773
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1774
+
1775
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1776
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1777
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1778
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1779
+ inputs_embeds = (
1780
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1781
+ if inputs_embeds is not None
1782
+ else None
1783
+ )
1784
+
1785
+ outputs = self.bert(
1786
+ input_ids,
1787
+ attention_mask=attention_mask,
1788
+ token_type_ids=token_type_ids,
1789
+ position_ids=position_ids,
1790
+ head_mask=head_mask,
1791
+ inputs_embeds=inputs_embeds,
1792
+ output_attentions=output_attentions,
1793
+ output_hidden_states=output_hidden_states,
1794
+ return_dict=return_dict,
1795
+ )
1796
+
1797
+ pooled_output = outputs[1]
1798
+
1799
+ pooled_output = self.dropout(pooled_output)
1800
+ logits = self.classifier(pooled_output)
1801
+ reshaped_logits = logits.view(-1, num_choices)
1802
+
1803
+ loss = None
1804
+ if labels is not None:
1805
+ loss_fct = CrossEntropyLoss()
1806
+ loss = loss_fct(reshaped_logits, labels)
1807
+
1808
+ if not return_dict:
1809
+ output = (reshaped_logits,) + outputs[2:]
1810
+ return ((loss,) + output) if loss is not None else output
1811
+
1812
+ return MultipleChoiceModelOutput(
1813
+ loss=loss,
1814
+ logits=reshaped_logits,
1815
+ hidden_states=outputs.hidden_states,
1816
+ attentions=outputs.attentions,
1817
+ )
1818
+
1819
+
1820
+ @add_start_docstrings(
1821
+ """
1822
+ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1823
+ Named-Entity-Recognition (NER) tasks.
1824
+ """,
1825
+ BERT_START_DOCSTRING,
1826
+ )
1827
+ class BertForTokenClassification(BertPreTrainedModel):
1828
+ def __init__(self, config):
1829
+ super().__init__(config)
1830
+ self.num_labels = config.num_labels
1831
+
1832
+ self.bert = BertModel(config, add_pooling_layer=False)
1833
+ classifier_dropout = (
1834
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1835
+ )
1836
+ self.dropout = nn.Dropout(classifier_dropout)
1837
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1838
+
1839
+ # Initialize weights and apply final processing
1840
+ self.post_init()
1841
+
1842
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1843
+ @add_code_sample_docstrings(
1844
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1845
+ output_type=TokenClassifierOutput,
1846
+ config_class=_CONFIG_FOR_DOC,
1847
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1848
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1849
+ )
1850
+ def forward(
1851
+ self,
1852
+ input_ids: Optional[torch.Tensor] = None,
1853
+ attention_mask: Optional[torch.Tensor] = None,
1854
+ token_type_ids: Optional[torch.Tensor] = None,
1855
+ position_ids: Optional[torch.Tensor] = None,
1856
+ head_mask: Optional[torch.Tensor] = None,
1857
+ inputs_embeds: Optional[torch.Tensor] = None,
1858
+ labels: Optional[torch.Tensor] = None,
1859
+ output_attentions: Optional[bool] = None,
1860
+ output_hidden_states: Optional[bool] = None,
1861
+ return_dict: Optional[bool] = None,
1862
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1863
+ r"""
1864
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1865
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1866
+ """
1867
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1868
+
1869
+ outputs = self.bert(
1870
+ input_ids,
1871
+ attention_mask=attention_mask,
1872
+ token_type_ids=token_type_ids,
1873
+ position_ids=position_ids,
1874
+ head_mask=head_mask,
1875
+ inputs_embeds=inputs_embeds,
1876
+ output_attentions=output_attentions,
1877
+ output_hidden_states=output_hidden_states,
1878
+ return_dict=return_dict,
1879
+ )
1880
+
1881
+ sequence_output = outputs[0]
1882
+
1883
+ sequence_output = self.dropout(sequence_output)
1884
+ logits = self.classifier(sequence_output)
1885
+
1886
+ loss = None
1887
+ if labels is not None:
1888
+ loss_fct = CrossEntropyLoss()
1889
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1890
+
1891
+ if not return_dict:
1892
+ output = (logits,) + outputs[2:]
1893
+ return ((loss,) + output) if loss is not None else output
1894
+
1895
+ return TokenClassifierOutput(
1896
+ loss=loss,
1897
+ logits=logits,
1898
+ hidden_states=outputs.hidden_states,
1899
+ attentions=outputs.attentions,
1900
+ )
1901
+
1902
+
1903
+ @add_start_docstrings(
1904
+ """
1905
+ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1906
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1907
+ """,
1908
+ BERT_START_DOCSTRING,
1909
+ )
1910
+ class BertForQuestionAnswering(BertPreTrainedModel):
1911
+ def __init__(self, config):
1912
+ super().__init__(config)
1913
+ self.num_labels = config.num_labels
1914
+
1915
+ self.bert = BertModel(config, add_pooling_layer=False)
1916
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1917
+
1918
+ # Initialize weights and apply final processing
1919
+ self.post_init()
1920
+
1921
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1922
+ @add_code_sample_docstrings(
1923
+ checkpoint=_CHECKPOINT_FOR_QA,
1924
+ output_type=QuestionAnsweringModelOutput,
1925
+ config_class=_CONFIG_FOR_DOC,
1926
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1927
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1928
+ expected_output=_QA_EXPECTED_OUTPUT,
1929
+ expected_loss=_QA_EXPECTED_LOSS,
1930
+ )
1931
+ def forward(
1932
+ self,
1933
+ input_ids: Optional[torch.Tensor] = None,
1934
+ attention_mask: Optional[torch.Tensor] = None,
1935
+ token_type_ids: Optional[torch.Tensor] = None,
1936
+ position_ids: Optional[torch.Tensor] = None,
1937
+ head_mask: Optional[torch.Tensor] = None,
1938
+ inputs_embeds: Optional[torch.Tensor] = None,
1939
+ start_positions: Optional[torch.Tensor] = None,
1940
+ end_positions: Optional[torch.Tensor] = None,
1941
+ output_attentions: Optional[bool] = None,
1942
+ output_hidden_states: Optional[bool] = None,
1943
+ return_dict: Optional[bool] = None,
1944
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1945
+ r"""
1946
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1947
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1948
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1949
+ are not taken into account for computing the loss.
1950
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1951
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1952
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1953
+ are not taken into account for computing the loss.
1954
+ """
1955
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1956
+
1957
+ outputs = self.bert(
1958
+ input_ids,
1959
+ attention_mask=attention_mask,
1960
+ token_type_ids=token_type_ids,
1961
+ position_ids=position_ids,
1962
+ head_mask=head_mask,
1963
+ inputs_embeds=inputs_embeds,
1964
+ output_attentions=output_attentions,
1965
+ output_hidden_states=output_hidden_states,
1966
+ return_dict=return_dict,
1967
+ )
1968
+
1969
+ sequence_output = outputs[0]
1970
+
1971
+ logits = self.qa_outputs(sequence_output)
1972
+ start_logits, end_logits = logits.split(1, dim=-1)
1973
+ start_logits = start_logits.squeeze(-1).contiguous()
1974
+ end_logits = end_logits.squeeze(-1).contiguous()
1975
+
1976
+ total_loss = None
1977
+ if start_positions is not None and end_positions is not None:
1978
+ # If we are on multi-GPU, split add a dimension
1979
+ if len(start_positions.size()) > 1:
1980
+ start_positions = start_positions.squeeze(-1)
1981
+ if len(end_positions.size()) > 1:
1982
+ end_positions = end_positions.squeeze(-1)
1983
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1984
+ ignored_index = start_logits.size(1)
1985
+ start_positions = start_positions.clamp(0, ignored_index)
1986
+ end_positions = end_positions.clamp(0, ignored_index)
1987
+
1988
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1989
+ start_loss = loss_fct(start_logits, start_positions)
1990
+ end_loss = loss_fct(end_logits, end_positions)
1991
+ total_loss = (start_loss + end_loss) / 2
1992
+
1993
+ if not return_dict:
1994
+ output = (start_logits, end_logits) + outputs[2:]
1995
+ return ((total_loss,) + output) if total_loss is not None else output
1996
+
1997
+ return QuestionAnsweringModelOutput(
1998
+ loss=total_loss,
1999
+ start_logits=start_logits,
2000
+ end_logits=end_logits,
2001
+ hidden_states=outputs.hidden_states,
2002
+ attentions=outputs.attentions,
2003
+ )
2004
+
2005
+
2006
+ __all__ = [
2007
+ "BertForMaskedLM",
2008
+ "BertForMultipleChoice",
2009
+ "BertForNextSentencePrediction",
2010
+ "BertForPreTraining",
2011
+ "BertForQuestionAnswering",
2012
+ "BertForSequenceClassification",
2013
+ "BertForTokenClassification",
2014
+ "BertLayer",
2015
+ "BertLMHeadModel",
2016
+ "BertModel",
2017
+ "BertPreTrainedModel",
2018
+ "load_tf_weights_in_bert",
2019
+ ]
lib/python3.12/site-packages/transformers/models/bert/modeling_flax_bert.py ADDED
@@ -0,0 +1,1727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Callable, Optional, Tuple
17
+
18
+ import flax
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
24
+ from flax.linen import combine_masks, make_causal_mask
25
+ from flax.linen import partitioning as nn_partitioning
26
+ from flax.linen.attention import dot_product_attention_weights
27
+ from flax.traverse_util import flatten_dict, unflatten_dict
28
+ from jax import lax
29
+
30
+ from ...modeling_flax_outputs import (
31
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
32
+ FlaxBaseModelOutputWithPooling,
33
+ FlaxBaseModelOutputWithPoolingAndCrossAttentions,
34
+ FlaxCausalLMOutputWithCrossAttentions,
35
+ FlaxMaskedLMOutput,
36
+ FlaxMultipleChoiceModelOutput,
37
+ FlaxNextSentencePredictorOutput,
38
+ FlaxQuestionAnsweringModelOutput,
39
+ FlaxSequenceClassifierOutput,
40
+ FlaxTokenClassifierOutput,
41
+ )
42
+ from ...modeling_flax_utils import (
43
+ ACT2FN,
44
+ FlaxPreTrainedModel,
45
+ append_call_sample_docstring,
46
+ append_replace_return_docstrings,
47
+ overwrite_call_docstring,
48
+ )
49
+ from ...utils import ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging
50
+ from .configuration_bert import BertConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
56
+ _CONFIG_FOR_DOC = "BertConfig"
57
+
58
+ remat = nn_partitioning.remat
59
+
60
+
61
+ @flax.struct.dataclass
62
+ class FlaxBertForPreTrainingOutput(ModelOutput):
63
+ """
64
+ Output type of [`BertForPreTraining`].
65
+
66
+ Args:
67
+ prediction_logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
68
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
69
+ seq_relationship_logits (`jnp.ndarray` of shape `(batch_size, 2)`):
70
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
71
+ before SoftMax).
72
+ hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
73
+ Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
74
+ `(batch_size, sequence_length, hidden_size)`.
75
+
76
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
77
+ attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
78
+ Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
79
+ sequence_length)`.
80
+
81
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
82
+ heads.
83
+ """
84
+
85
+ prediction_logits: jnp.ndarray = None
86
+ seq_relationship_logits: jnp.ndarray = None
87
+ hidden_states: Optional[Tuple[jnp.ndarray]] = None
88
+ attentions: Optional[Tuple[jnp.ndarray]] = None
89
+
90
+
91
+ BERT_START_DOCSTRING = r"""
92
+
93
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
94
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
95
+
96
+ This model is also a
97
+ [flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
98
+ a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
99
+ behavior.
100
+
101
+ Finally, this model supports inherent JAX features such as:
102
+
103
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
104
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
105
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
106
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
107
+
108
+ Parameters:
109
+ config ([`BertConfig`]): Model configuration class with all the parameters of the model.
110
+ Initializing with a config file does not load the weights associated with the model, only the
111
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
112
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
113
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
114
+ `jax.numpy.bfloat16` (on TPUs).
115
+
116
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
117
+ specified all the computation will be performed with the given `dtype`.
118
+
119
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
120
+ parameters.**
121
+
122
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
123
+ [`~FlaxPreTrainedModel.to_bf16`].
124
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
125
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
126
+ `jax.numpy.bfloat16` (on TPUs).
127
+
128
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
129
+ specified all the computation will be performed with the given `dtype`.
130
+
131
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
132
+ parameters.**
133
+
134
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
135
+ [`~FlaxPreTrainedModel.to_bf16`].
136
+
137
+ """
138
+
139
+ BERT_INPUTS_DOCSTRING = r"""
140
+ Args:
141
+ input_ids (`numpy.ndarray` of shape `({0})`):
142
+ Indices of input sequence tokens in the vocabulary.
143
+
144
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
145
+ [`PreTrainedTokenizer.__call__`] for details.
146
+
147
+ [What are input IDs?](../glossary#input-ids)
148
+ attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
149
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
150
+
151
+ - 1 for tokens that are **not masked**,
152
+ - 0 for tokens that are **masked**.
153
+
154
+ [What are attention masks?](../glossary#attention-mask)
155
+ token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
156
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
157
+ 1]`:
158
+
159
+ - 0 corresponds to a *sentence A* token,
160
+ - 1 corresponds to a *sentence B* token.
161
+
162
+ [What are token type IDs?](../glossary#token-type-ids)
163
+ position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
164
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
165
+ config.max_position_embeddings - 1]`.
166
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
167
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
168
+
169
+ - 1 indicates the head is **not masked**,
170
+ - 0 indicates the head is **masked**.
171
+
172
+ return_dict (`bool`, *optional*):
173
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
174
+
175
+ """
176
+
177
+
178
+ class FlaxBertEmbeddings(nn.Module):
179
+ """Construct the embeddings from word, position and token_type embeddings."""
180
+
181
+ config: BertConfig
182
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
183
+
184
+ def setup(self):
185
+ self.word_embeddings = nn.Embed(
186
+ self.config.vocab_size,
187
+ self.config.hidden_size,
188
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
189
+ dtype=self.dtype,
190
+ )
191
+ self.position_embeddings = nn.Embed(
192
+ self.config.max_position_embeddings,
193
+ self.config.hidden_size,
194
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
195
+ dtype=self.dtype,
196
+ )
197
+ self.token_type_embeddings = nn.Embed(
198
+ self.config.type_vocab_size,
199
+ self.config.hidden_size,
200
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
201
+ dtype=self.dtype,
202
+ )
203
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
204
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
205
+
206
+ def __call__(self, input_ids, token_type_ids, position_ids, attention_mask, deterministic: bool = True):
207
+ # Embed
208
+ inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
209
+ position_embeds = self.position_embeddings(position_ids.astype("i4"))
210
+ token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
211
+
212
+ # Sum all embeddings
213
+ hidden_states = inputs_embeds + token_type_embeddings + position_embeds
214
+
215
+ # Layer Norm
216
+ hidden_states = self.LayerNorm(hidden_states)
217
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
218
+ return hidden_states
219
+
220
+
221
+ class FlaxBertSelfAttention(nn.Module):
222
+ config: BertConfig
223
+ causal: bool = False
224
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
225
+
226
+ def setup(self):
227
+ self.head_dim = self.config.hidden_size // self.config.num_attention_heads
228
+ if self.config.hidden_size % self.config.num_attention_heads != 0:
229
+ raise ValueError(
230
+ "`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
231
+ " : {self.config.num_attention_heads}"
232
+ )
233
+
234
+ self.query = nn.Dense(
235
+ self.config.hidden_size,
236
+ dtype=self.dtype,
237
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
238
+ )
239
+ self.key = nn.Dense(
240
+ self.config.hidden_size,
241
+ dtype=self.dtype,
242
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
243
+ )
244
+ self.value = nn.Dense(
245
+ self.config.hidden_size,
246
+ dtype=self.dtype,
247
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
248
+ )
249
+
250
+ if self.causal:
251
+ self.causal_mask = make_causal_mask(
252
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
253
+ )
254
+
255
+ def _split_heads(self, hidden_states):
256
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.num_attention_heads, self.head_dim))
257
+
258
+ def _merge_heads(self, hidden_states):
259
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.hidden_size,))
260
+
261
+ @nn.compact
262
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention._concatenate_to_cache
263
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
264
+ """
265
+ This function takes projected key, value states from a single input token and concatenates the states to cached
266
+ states from previous steps. This function is slightly adapted from the official Flax repository:
267
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
268
+ """
269
+ # detect if we're initializing by absence of existing cache data.
270
+ is_initialized = self.has_variable("cache", "cached_key")
271
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
272
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
273
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
274
+
275
+ if is_initialized:
276
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
277
+ # update key, value caches with our new 1d spatial slices
278
+ cur_index = cache_index.value
279
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
280
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
281
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
282
+ cached_key.value = key
283
+ cached_value.value = value
284
+ num_updated_cache_vectors = query.shape[1]
285
+ cache_index.value = cache_index.value + num_updated_cache_vectors
286
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
287
+ pad_mask = jnp.broadcast_to(
288
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
289
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
290
+ )
291
+ attention_mask = combine_masks(pad_mask, attention_mask)
292
+ return key, value, attention_mask
293
+
294
+ def __call__(
295
+ self,
296
+ hidden_states,
297
+ attention_mask,
298
+ layer_head_mask,
299
+ key_value_states: Optional[jnp.ndarray] = None,
300
+ init_cache: bool = False,
301
+ deterministic=True,
302
+ output_attentions: bool = False,
303
+ ):
304
+ # if key_value_states are provided this layer is used as a cross-attention layer
305
+ # for the decoder
306
+ is_cross_attention = key_value_states is not None
307
+ batch_size = hidden_states.shape[0]
308
+
309
+ # get query proj
310
+ query_states = self.query(hidden_states)
311
+ # get key, value proj
312
+ if is_cross_attention:
313
+ # cross_attentions
314
+ key_states = self.key(key_value_states)
315
+ value_states = self.value(key_value_states)
316
+ else:
317
+ # self_attention
318
+ key_states = self.key(hidden_states)
319
+ value_states = self.value(hidden_states)
320
+
321
+ query_states = self._split_heads(query_states)
322
+ key_states = self._split_heads(key_states)
323
+ value_states = self._split_heads(value_states)
324
+
325
+ # handle cache prepare causal attention mask
326
+ if self.causal:
327
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
328
+ if self.has_variable("cache", "cached_key"):
329
+ mask_shift = self.variables["cache"]["cache_index"]
330
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
331
+ causal_mask = lax.dynamic_slice(
332
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
333
+ )
334
+ else:
335
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
336
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
337
+
338
+ # combine masks if needed
339
+ if attention_mask is not None and self.causal:
340
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
341
+ attention_mask = combine_masks(attention_mask, causal_mask)
342
+ elif self.causal:
343
+ attention_mask = causal_mask
344
+ elif attention_mask is not None:
345
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
346
+
347
+ # During fast autoregressive decoding, we feed one position at a time,
348
+ # and cache the keys and values step by step.
349
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
350
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
351
+ key_states, value_states, query_states, attention_mask
352
+ )
353
+
354
+ # Convert the boolean attention mask to an attention bias.
355
+ if attention_mask is not None:
356
+ # attention mask in the form of attention bias
357
+ attention_bias = lax.select(
358
+ attention_mask > 0,
359
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
360
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
361
+ )
362
+ else:
363
+ attention_bias = None
364
+
365
+ dropout_rng = None
366
+ if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
367
+ dropout_rng = self.make_rng("dropout")
368
+
369
+ attn_weights = dot_product_attention_weights(
370
+ query_states,
371
+ key_states,
372
+ bias=attention_bias,
373
+ dropout_rng=dropout_rng,
374
+ dropout_rate=self.config.attention_probs_dropout_prob,
375
+ broadcast_dropout=True,
376
+ deterministic=deterministic,
377
+ dtype=self.dtype,
378
+ precision=None,
379
+ )
380
+
381
+ # Mask heads if we want to
382
+ if layer_head_mask is not None:
383
+ attn_weights = jnp.einsum("...hqk,h->...hqk", attn_weights, layer_head_mask)
384
+
385
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
386
+ attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
387
+
388
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
389
+ return outputs
390
+
391
+
392
+ class FlaxBertSelfOutput(nn.Module):
393
+ config: BertConfig
394
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
395
+
396
+ def setup(self):
397
+ self.dense = nn.Dense(
398
+ self.config.hidden_size,
399
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
400
+ dtype=self.dtype,
401
+ )
402
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
403
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
404
+
405
+ def __call__(self, hidden_states, input_tensor, deterministic: bool = True):
406
+ hidden_states = self.dense(hidden_states)
407
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
408
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
409
+ return hidden_states
410
+
411
+
412
+ class FlaxBertAttention(nn.Module):
413
+ config: BertConfig
414
+ causal: bool = False
415
+ dtype: jnp.dtype = jnp.float32
416
+
417
+ def setup(self):
418
+ self.self = FlaxBertSelfAttention(self.config, causal=self.causal, dtype=self.dtype)
419
+ self.output = FlaxBertSelfOutput(self.config, dtype=self.dtype)
420
+
421
+ def __call__(
422
+ self,
423
+ hidden_states,
424
+ attention_mask,
425
+ layer_head_mask,
426
+ key_value_states=None,
427
+ init_cache=False,
428
+ deterministic=True,
429
+ output_attentions: bool = False,
430
+ ):
431
+ # Attention mask comes in as attention_mask.shape == (*batch_sizes, kv_length)
432
+ # FLAX expects: attention_mask.shape == (*batch_sizes, 1, 1, kv_length) such that it is broadcastable
433
+ # with attn_weights.shape == (*batch_sizes, num_heads, q_length, kv_length)
434
+ attn_outputs = self.self(
435
+ hidden_states,
436
+ attention_mask,
437
+ layer_head_mask=layer_head_mask,
438
+ key_value_states=key_value_states,
439
+ init_cache=init_cache,
440
+ deterministic=deterministic,
441
+ output_attentions=output_attentions,
442
+ )
443
+ attn_output = attn_outputs[0]
444
+ hidden_states = self.output(attn_output, hidden_states, deterministic=deterministic)
445
+
446
+ outputs = (hidden_states,)
447
+
448
+ if output_attentions:
449
+ outputs += (attn_outputs[1],)
450
+
451
+ return outputs
452
+
453
+
454
+ class FlaxBertIntermediate(nn.Module):
455
+ config: BertConfig
456
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
457
+
458
+ def setup(self):
459
+ self.dense = nn.Dense(
460
+ self.config.intermediate_size,
461
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
462
+ dtype=self.dtype,
463
+ )
464
+ self.activation = ACT2FN[self.config.hidden_act]
465
+
466
+ def __call__(self, hidden_states):
467
+ hidden_states = self.dense(hidden_states)
468
+ hidden_states = self.activation(hidden_states)
469
+ return hidden_states
470
+
471
+
472
+ class FlaxBertOutput(nn.Module):
473
+ config: BertConfig
474
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
475
+
476
+ def setup(self):
477
+ self.dense = nn.Dense(
478
+ self.config.hidden_size,
479
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
480
+ dtype=self.dtype,
481
+ )
482
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
483
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
484
+
485
+ def __call__(self, hidden_states, attention_output, deterministic: bool = True):
486
+ hidden_states = self.dense(hidden_states)
487
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
488
+ hidden_states = self.LayerNorm(hidden_states + attention_output)
489
+ return hidden_states
490
+
491
+
492
+ class FlaxBertLayer(nn.Module):
493
+ config: BertConfig
494
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
495
+
496
+ def setup(self):
497
+ self.attention = FlaxBertAttention(self.config, causal=self.config.is_decoder, dtype=self.dtype)
498
+ self.intermediate = FlaxBertIntermediate(self.config, dtype=self.dtype)
499
+ self.output = FlaxBertOutput(self.config, dtype=self.dtype)
500
+ if self.config.add_cross_attention:
501
+ self.crossattention = FlaxBertAttention(self.config, causal=False, dtype=self.dtype)
502
+
503
+ def __call__(
504
+ self,
505
+ hidden_states,
506
+ attention_mask,
507
+ layer_head_mask,
508
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
509
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
510
+ init_cache: bool = False,
511
+ deterministic: bool = True,
512
+ output_attentions: bool = False,
513
+ ):
514
+ # Self Attention
515
+ attention_outputs = self.attention(
516
+ hidden_states,
517
+ attention_mask,
518
+ layer_head_mask=layer_head_mask,
519
+ init_cache=init_cache,
520
+ deterministic=deterministic,
521
+ output_attentions=output_attentions,
522
+ )
523
+ attention_output = attention_outputs[0]
524
+
525
+ # Cross-Attention Block
526
+ if encoder_hidden_states is not None:
527
+ cross_attention_outputs = self.crossattention(
528
+ attention_output,
529
+ attention_mask=encoder_attention_mask,
530
+ layer_head_mask=layer_head_mask,
531
+ key_value_states=encoder_hidden_states,
532
+ deterministic=deterministic,
533
+ output_attentions=output_attentions,
534
+ )
535
+ attention_output = cross_attention_outputs[0]
536
+
537
+ hidden_states = self.intermediate(attention_output)
538
+ hidden_states = self.output(hidden_states, attention_output, deterministic=deterministic)
539
+
540
+ outputs = (hidden_states,)
541
+
542
+ if output_attentions:
543
+ outputs += (attention_outputs[1],)
544
+ if encoder_hidden_states is not None:
545
+ outputs += (cross_attention_outputs[1],)
546
+ return outputs
547
+
548
+
549
+ class FlaxBertLayerCollection(nn.Module):
550
+ config: BertConfig
551
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
552
+ gradient_checkpointing: bool = False
553
+
554
+ def setup(self):
555
+ if self.gradient_checkpointing:
556
+ FlaxBertCheckpointLayer = remat(FlaxBertLayer, static_argnums=(5, 6, 7))
557
+ self.layers = [
558
+ FlaxBertCheckpointLayer(self.config, name=str(i), dtype=self.dtype)
559
+ for i in range(self.config.num_hidden_layers)
560
+ ]
561
+ else:
562
+ self.layers = [
563
+ FlaxBertLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.num_hidden_layers)
564
+ ]
565
+
566
+ def __call__(
567
+ self,
568
+ hidden_states,
569
+ attention_mask,
570
+ head_mask,
571
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
572
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
573
+ init_cache: bool = False,
574
+ deterministic: bool = True,
575
+ output_attentions: bool = False,
576
+ output_hidden_states: bool = False,
577
+ return_dict: bool = True,
578
+ ):
579
+ all_attentions = () if output_attentions else None
580
+ all_hidden_states = () if output_hidden_states else None
581
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
582
+
583
+ # Check if head_mask has a correct number of layers specified if desired
584
+ if head_mask is not None:
585
+ if head_mask.shape[0] != (len(self.layers)):
586
+ raise ValueError(
587
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for "
588
+ f" {head_mask.shape[0]}."
589
+ )
590
+
591
+ for i, layer in enumerate(self.layers):
592
+ if output_hidden_states:
593
+ all_hidden_states += (hidden_states,)
594
+
595
+ layer_outputs = layer(
596
+ hidden_states,
597
+ attention_mask,
598
+ head_mask[i] if head_mask is not None else None,
599
+ encoder_hidden_states,
600
+ encoder_attention_mask,
601
+ init_cache,
602
+ deterministic,
603
+ output_attentions,
604
+ )
605
+
606
+ hidden_states = layer_outputs[0]
607
+
608
+ if output_attentions:
609
+ all_attentions += (layer_outputs[1],)
610
+
611
+ if encoder_hidden_states is not None:
612
+ all_cross_attentions += (layer_outputs[2],)
613
+
614
+ if output_hidden_states:
615
+ all_hidden_states += (hidden_states,)
616
+
617
+ outputs = (hidden_states, all_hidden_states, all_attentions, all_cross_attentions)
618
+
619
+ if not return_dict:
620
+ return tuple(v for v in outputs if v is not None)
621
+
622
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
623
+ last_hidden_state=hidden_states,
624
+ hidden_states=all_hidden_states,
625
+ attentions=all_attentions,
626
+ cross_attentions=all_cross_attentions,
627
+ )
628
+
629
+
630
+ class FlaxBertEncoder(nn.Module):
631
+ config: BertConfig
632
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
633
+ gradient_checkpointing: bool = False
634
+
635
+ def setup(self):
636
+ self.layer = FlaxBertLayerCollection(
637
+ self.config,
638
+ dtype=self.dtype,
639
+ gradient_checkpointing=self.gradient_checkpointing,
640
+ )
641
+
642
+ def __call__(
643
+ self,
644
+ hidden_states,
645
+ attention_mask,
646
+ head_mask,
647
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
648
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
649
+ init_cache: bool = False,
650
+ deterministic: bool = True,
651
+ output_attentions: bool = False,
652
+ output_hidden_states: bool = False,
653
+ return_dict: bool = True,
654
+ ):
655
+ return self.layer(
656
+ hidden_states,
657
+ attention_mask,
658
+ head_mask=head_mask,
659
+ encoder_hidden_states=encoder_hidden_states,
660
+ encoder_attention_mask=encoder_attention_mask,
661
+ init_cache=init_cache,
662
+ deterministic=deterministic,
663
+ output_attentions=output_attentions,
664
+ output_hidden_states=output_hidden_states,
665
+ return_dict=return_dict,
666
+ )
667
+
668
+
669
+ class FlaxBertPooler(nn.Module):
670
+ config: BertConfig
671
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
672
+
673
+ def setup(self):
674
+ self.dense = nn.Dense(
675
+ self.config.hidden_size,
676
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
677
+ dtype=self.dtype,
678
+ )
679
+
680
+ def __call__(self, hidden_states):
681
+ cls_hidden_state = hidden_states[:, 0]
682
+ cls_hidden_state = self.dense(cls_hidden_state)
683
+ return nn.tanh(cls_hidden_state)
684
+
685
+
686
+ class FlaxBertPredictionHeadTransform(nn.Module):
687
+ config: BertConfig
688
+ dtype: jnp.dtype = jnp.float32
689
+
690
+ def setup(self):
691
+ self.dense = nn.Dense(self.config.hidden_size, dtype=self.dtype)
692
+ self.activation = ACT2FN[self.config.hidden_act]
693
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
694
+
695
+ def __call__(self, hidden_states):
696
+ hidden_states = self.dense(hidden_states)
697
+ hidden_states = self.activation(hidden_states)
698
+ return self.LayerNorm(hidden_states)
699
+
700
+
701
+ class FlaxBertLMPredictionHead(nn.Module):
702
+ config: BertConfig
703
+ dtype: jnp.dtype = jnp.float32
704
+ bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
705
+
706
+ def setup(self):
707
+ self.transform = FlaxBertPredictionHeadTransform(self.config, dtype=self.dtype)
708
+ self.decoder = nn.Dense(self.config.vocab_size, dtype=self.dtype, use_bias=False)
709
+ self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
710
+
711
+ def __call__(self, hidden_states, shared_embedding=None):
712
+ hidden_states = self.transform(hidden_states)
713
+
714
+ if shared_embedding is not None:
715
+ hidden_states = self.decoder.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
716
+ else:
717
+ hidden_states = self.decoder(hidden_states)
718
+
719
+ bias = jnp.asarray(self.bias, self.dtype)
720
+ hidden_states += bias
721
+ return hidden_states
722
+
723
+
724
+ class FlaxBertOnlyMLMHead(nn.Module):
725
+ config: BertConfig
726
+ dtype: jnp.dtype = jnp.float32
727
+
728
+ def setup(self):
729
+ self.predictions = FlaxBertLMPredictionHead(self.config, dtype=self.dtype)
730
+
731
+ def __call__(self, hidden_states, shared_embedding=None):
732
+ hidden_states = self.predictions(hidden_states, shared_embedding=shared_embedding)
733
+ return hidden_states
734
+
735
+
736
+ class FlaxBertOnlyNSPHead(nn.Module):
737
+ dtype: jnp.dtype = jnp.float32
738
+
739
+ def setup(self):
740
+ self.seq_relationship = nn.Dense(2, dtype=self.dtype)
741
+
742
+ def __call__(self, pooled_output):
743
+ return self.seq_relationship(pooled_output)
744
+
745
+
746
+ class FlaxBertPreTrainingHeads(nn.Module):
747
+ config: BertConfig
748
+ dtype: jnp.dtype = jnp.float32
749
+
750
+ def setup(self):
751
+ self.predictions = FlaxBertLMPredictionHead(self.config, dtype=self.dtype)
752
+ self.seq_relationship = nn.Dense(2, dtype=self.dtype)
753
+
754
+ def __call__(self, hidden_states, pooled_output, shared_embedding=None):
755
+ prediction_scores = self.predictions(hidden_states, shared_embedding=shared_embedding)
756
+ seq_relationship_score = self.seq_relationship(pooled_output)
757
+ return prediction_scores, seq_relationship_score
758
+
759
+
760
+ class FlaxBertPreTrainedModel(FlaxPreTrainedModel):
761
+ """
762
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
763
+ models.
764
+ """
765
+
766
+ config_class = BertConfig
767
+ base_model_prefix = "bert"
768
+ module_class: nn.Module = None
769
+
770
+ def __init__(
771
+ self,
772
+ config: BertConfig,
773
+ input_shape: Tuple = (1, 1),
774
+ seed: int = 0,
775
+ dtype: jnp.dtype = jnp.float32,
776
+ _do_init: bool = True,
777
+ gradient_checkpointing: bool = False,
778
+ **kwargs,
779
+ ):
780
+ module = self.module_class(
781
+ config=config,
782
+ dtype=dtype,
783
+ gradient_checkpointing=gradient_checkpointing,
784
+ **kwargs,
785
+ )
786
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
787
+
788
+ def enable_gradient_checkpointing(self):
789
+ self._module = self.module_class(
790
+ config=self.config,
791
+ dtype=self.dtype,
792
+ gradient_checkpointing=True,
793
+ )
794
+
795
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
796
+ # init input tensors
797
+ input_ids = jnp.zeros(input_shape, dtype="i4")
798
+ token_type_ids = jnp.zeros_like(input_ids)
799
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
800
+ attention_mask = jnp.ones_like(input_ids)
801
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
802
+
803
+ params_rng, dropout_rng = jax.random.split(rng)
804
+ rngs = {"params": params_rng, "dropout": dropout_rng}
805
+
806
+ if self.config.add_cross_attention:
807
+ encoder_hidden_states = jnp.zeros(input_shape + (self.config.hidden_size,))
808
+ encoder_attention_mask = attention_mask
809
+ module_init_outputs = self.module.init(
810
+ rngs,
811
+ input_ids,
812
+ attention_mask,
813
+ token_type_ids,
814
+ position_ids,
815
+ head_mask,
816
+ encoder_hidden_states,
817
+ encoder_attention_mask,
818
+ return_dict=False,
819
+ )
820
+ else:
821
+ module_init_outputs = self.module.init(
822
+ rngs, input_ids, attention_mask, token_type_ids, position_ids, head_mask, return_dict=False
823
+ )
824
+
825
+ random_params = module_init_outputs["params"]
826
+
827
+ if params is not None:
828
+ random_params = flatten_dict(unfreeze(random_params))
829
+ params = flatten_dict(unfreeze(params))
830
+ for missing_key in self._missing_keys:
831
+ params[missing_key] = random_params[missing_key]
832
+ self._missing_keys = set()
833
+ return freeze(unflatten_dict(params))
834
+ else:
835
+ return random_params
836
+
837
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderPreTrainedModel.init_cache
838
+ def init_cache(self, batch_size, max_length):
839
+ r"""
840
+ Args:
841
+ batch_size (`int`):
842
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
843
+ max_length (`int`):
844
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
845
+ cache.
846
+ """
847
+ # init input variables to retrieve cache
848
+ input_ids = jnp.ones((batch_size, max_length), dtype="i4")
849
+ attention_mask = jnp.ones_like(input_ids, dtype="i4")
850
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
851
+
852
+ init_variables = self.module.init(
853
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
854
+ )
855
+ return unfreeze(init_variables["cache"])
856
+
857
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
858
+ def __call__(
859
+ self,
860
+ input_ids,
861
+ attention_mask=None,
862
+ token_type_ids=None,
863
+ position_ids=None,
864
+ head_mask=None,
865
+ encoder_hidden_states=None,
866
+ encoder_attention_mask=None,
867
+ params: dict = None,
868
+ dropout_rng: jax.random.PRNGKey = None,
869
+ train: bool = False,
870
+ output_attentions: Optional[bool] = None,
871
+ output_hidden_states: Optional[bool] = None,
872
+ return_dict: Optional[bool] = None,
873
+ past_key_values: dict = None,
874
+ ):
875
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
876
+ output_hidden_states = (
877
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
878
+ )
879
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
880
+
881
+ # init input tensors if not passed
882
+ if token_type_ids is None:
883
+ token_type_ids = jnp.zeros_like(input_ids)
884
+
885
+ if position_ids is None:
886
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
887
+
888
+ if attention_mask is None:
889
+ attention_mask = jnp.ones_like(input_ids)
890
+
891
+ if head_mask is None:
892
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
893
+
894
+ # Handle any PRNG if needed
895
+ rngs = {}
896
+ if dropout_rng is not None:
897
+ rngs["dropout"] = dropout_rng
898
+
899
+ inputs = {"params": params or self.params}
900
+
901
+ if self.config.add_cross_attention:
902
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
903
+ # down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
904
+ # changed by FlaxBertAttention module
905
+ if past_key_values:
906
+ inputs["cache"] = past_key_values
907
+ mutable = ["cache"]
908
+ else:
909
+ mutable = False
910
+
911
+ outputs = self.module.apply(
912
+ inputs,
913
+ jnp.array(input_ids, dtype="i4"),
914
+ jnp.array(attention_mask, dtype="i4"),
915
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
916
+ position_ids=jnp.array(position_ids, dtype="i4"),
917
+ head_mask=jnp.array(head_mask, dtype="i4"),
918
+ encoder_hidden_states=encoder_hidden_states,
919
+ encoder_attention_mask=encoder_attention_mask,
920
+ deterministic=not train,
921
+ output_attentions=output_attentions,
922
+ output_hidden_states=output_hidden_states,
923
+ return_dict=return_dict,
924
+ rngs=rngs,
925
+ mutable=mutable,
926
+ )
927
+
928
+ # add updated cache to model output
929
+ if past_key_values is not None and return_dict:
930
+ outputs, past_key_values = outputs
931
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
932
+ return outputs
933
+ elif past_key_values is not None and not return_dict:
934
+ outputs, past_key_values = outputs
935
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
936
+
937
+ else:
938
+ outputs = self.module.apply(
939
+ inputs,
940
+ jnp.array(input_ids, dtype="i4"),
941
+ jnp.array(attention_mask, dtype="i4"),
942
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
943
+ position_ids=jnp.array(position_ids, dtype="i4"),
944
+ head_mask=jnp.array(head_mask, dtype="i4"),
945
+ deterministic=not train,
946
+ output_attentions=output_attentions,
947
+ output_hidden_states=output_hidden_states,
948
+ return_dict=return_dict,
949
+ rngs=rngs,
950
+ )
951
+
952
+ return outputs
953
+
954
+
955
+ class FlaxBertModule(nn.Module):
956
+ config: BertConfig
957
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
958
+ add_pooling_layer: bool = True
959
+ gradient_checkpointing: bool = False
960
+
961
+ def setup(self):
962
+ self.embeddings = FlaxBertEmbeddings(self.config, dtype=self.dtype)
963
+ self.encoder = FlaxBertEncoder(
964
+ self.config,
965
+ dtype=self.dtype,
966
+ gradient_checkpointing=self.gradient_checkpointing,
967
+ )
968
+ self.pooler = FlaxBertPooler(self.config, dtype=self.dtype)
969
+
970
+ def __call__(
971
+ self,
972
+ input_ids,
973
+ attention_mask,
974
+ token_type_ids: Optional[jnp.ndarray] = None,
975
+ position_ids: Optional[jnp.ndarray] = None,
976
+ head_mask: Optional[jnp.ndarray] = None,
977
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
978
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
979
+ init_cache: bool = False,
980
+ deterministic: bool = True,
981
+ output_attentions: bool = False,
982
+ output_hidden_states: bool = False,
983
+ return_dict: bool = True,
984
+ ):
985
+ # make sure `token_type_ids` is correctly initialized when not passed
986
+ if token_type_ids is None:
987
+ token_type_ids = jnp.zeros_like(input_ids)
988
+
989
+ # make sure `position_ids` is correctly initialized when not passed
990
+ if position_ids is None:
991
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
992
+
993
+ hidden_states = self.embeddings(
994
+ input_ids, token_type_ids, position_ids, attention_mask, deterministic=deterministic
995
+ )
996
+ outputs = self.encoder(
997
+ hidden_states,
998
+ attention_mask,
999
+ head_mask=head_mask,
1000
+ deterministic=deterministic,
1001
+ encoder_hidden_states=encoder_hidden_states,
1002
+ encoder_attention_mask=encoder_attention_mask,
1003
+ init_cache=init_cache,
1004
+ output_attentions=output_attentions,
1005
+ output_hidden_states=output_hidden_states,
1006
+ return_dict=return_dict,
1007
+ )
1008
+ hidden_states = outputs[0]
1009
+ pooled = self.pooler(hidden_states) if self.add_pooling_layer else None
1010
+
1011
+ if not return_dict:
1012
+ # if pooled is None, don't return it
1013
+ if pooled is None:
1014
+ return (hidden_states,) + outputs[1:]
1015
+ return (hidden_states, pooled) + outputs[1:]
1016
+
1017
+ return FlaxBaseModelOutputWithPoolingAndCrossAttentions(
1018
+ last_hidden_state=hidden_states,
1019
+ pooler_output=pooled,
1020
+ hidden_states=outputs.hidden_states,
1021
+ attentions=outputs.attentions,
1022
+ cross_attentions=outputs.cross_attentions,
1023
+ )
1024
+
1025
+
1026
+ @add_start_docstrings(
1027
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
1028
+ BERT_START_DOCSTRING,
1029
+ )
1030
+ class FlaxBertModel(FlaxBertPreTrainedModel):
1031
+ module_class = FlaxBertModule
1032
+
1033
+
1034
+ append_call_sample_docstring(FlaxBertModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutputWithPooling, _CONFIG_FOR_DOC)
1035
+
1036
+
1037
+ class FlaxBertForPreTrainingModule(nn.Module):
1038
+ config: BertConfig
1039
+ dtype: jnp.dtype = jnp.float32
1040
+ gradient_checkpointing: bool = False
1041
+
1042
+ def setup(self):
1043
+ self.bert = FlaxBertModule(
1044
+ config=self.config,
1045
+ dtype=self.dtype,
1046
+ gradient_checkpointing=self.gradient_checkpointing,
1047
+ )
1048
+ self.cls = FlaxBertPreTrainingHeads(config=self.config, dtype=self.dtype)
1049
+
1050
+ def __call__(
1051
+ self,
1052
+ input_ids,
1053
+ attention_mask,
1054
+ token_type_ids,
1055
+ position_ids,
1056
+ head_mask,
1057
+ deterministic: bool = True,
1058
+ output_attentions: bool = False,
1059
+ output_hidden_states: bool = False,
1060
+ return_dict: bool = True,
1061
+ ):
1062
+ # Model
1063
+ outputs = self.bert(
1064
+ input_ids,
1065
+ attention_mask,
1066
+ token_type_ids,
1067
+ position_ids,
1068
+ head_mask,
1069
+ deterministic=deterministic,
1070
+ output_attentions=output_attentions,
1071
+ output_hidden_states=output_hidden_states,
1072
+ return_dict=return_dict,
1073
+ )
1074
+
1075
+ if self.config.tie_word_embeddings:
1076
+ shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1077
+ else:
1078
+ shared_embedding = None
1079
+
1080
+ hidden_states = outputs[0]
1081
+ pooled_output = outputs[1]
1082
+
1083
+ prediction_scores, seq_relationship_score = self.cls(
1084
+ hidden_states, pooled_output, shared_embedding=shared_embedding
1085
+ )
1086
+
1087
+ if not return_dict:
1088
+ return (prediction_scores, seq_relationship_score) + outputs[2:]
1089
+
1090
+ return FlaxBertForPreTrainingOutput(
1091
+ prediction_logits=prediction_scores,
1092
+ seq_relationship_logits=seq_relationship_score,
1093
+ hidden_states=outputs.hidden_states,
1094
+ attentions=outputs.attentions,
1095
+ )
1096
+
1097
+
1098
+ @add_start_docstrings(
1099
+ """
1100
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1101
+ sentence prediction (classification)` head.
1102
+ """,
1103
+ BERT_START_DOCSTRING,
1104
+ )
1105
+ class FlaxBertForPreTraining(FlaxBertPreTrainedModel):
1106
+ module_class = FlaxBertForPreTrainingModule
1107
+
1108
+
1109
+ FLAX_BERT_FOR_PRETRAINING_DOCSTRING = """
1110
+ Returns:
1111
+
1112
+ Example:
1113
+
1114
+ ```python
1115
+ >>> from transformers import AutoTokenizer, FlaxBertForPreTraining
1116
+
1117
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1118
+ >>> model = FlaxBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
1119
+
1120
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
1121
+ >>> outputs = model(**inputs)
1122
+
1123
+ >>> prediction_logits = outputs.prediction_logits
1124
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1125
+ ```
1126
+ """
1127
+
1128
+ overwrite_call_docstring(
1129
+ FlaxBertForPreTraining,
1130
+ BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_BERT_FOR_PRETRAINING_DOCSTRING,
1131
+ )
1132
+ append_replace_return_docstrings(
1133
+ FlaxBertForPreTraining, output_type=FlaxBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
1134
+ )
1135
+
1136
+
1137
+ class FlaxBertForMaskedLMModule(nn.Module):
1138
+ config: BertConfig
1139
+ dtype: jnp.dtype = jnp.float32
1140
+ gradient_checkpointing: bool = False
1141
+
1142
+ def setup(self):
1143
+ self.bert = FlaxBertModule(
1144
+ config=self.config,
1145
+ add_pooling_layer=False,
1146
+ dtype=self.dtype,
1147
+ gradient_checkpointing=self.gradient_checkpointing,
1148
+ )
1149
+ self.cls = FlaxBertOnlyMLMHead(config=self.config, dtype=self.dtype)
1150
+
1151
+ def __call__(
1152
+ self,
1153
+ input_ids,
1154
+ attention_mask,
1155
+ token_type_ids,
1156
+ position_ids,
1157
+ head_mask,
1158
+ deterministic: bool = True,
1159
+ output_attentions: bool = False,
1160
+ output_hidden_states: bool = False,
1161
+ return_dict: bool = True,
1162
+ ):
1163
+ # Model
1164
+ outputs = self.bert(
1165
+ input_ids,
1166
+ attention_mask,
1167
+ token_type_ids,
1168
+ position_ids,
1169
+ head_mask,
1170
+ deterministic=deterministic,
1171
+ output_attentions=output_attentions,
1172
+ output_hidden_states=output_hidden_states,
1173
+ return_dict=return_dict,
1174
+ )
1175
+
1176
+ hidden_states = outputs[0]
1177
+ if self.config.tie_word_embeddings:
1178
+ shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1179
+ else:
1180
+ shared_embedding = None
1181
+
1182
+ # Compute the prediction scores
1183
+ logits = self.cls(hidden_states, shared_embedding=shared_embedding)
1184
+
1185
+ if not return_dict:
1186
+ return (logits,) + outputs[1:]
1187
+
1188
+ return FlaxMaskedLMOutput(
1189
+ logits=logits,
1190
+ hidden_states=outputs.hidden_states,
1191
+ attentions=outputs.attentions,
1192
+ )
1193
+
1194
+
1195
+ @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
1196
+ class FlaxBertForMaskedLM(FlaxBertPreTrainedModel):
1197
+ module_class = FlaxBertForMaskedLMModule
1198
+
1199
+
1200
+ append_call_sample_docstring(FlaxBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
1201
+
1202
+
1203
+ class FlaxBertForNextSentencePredictionModule(nn.Module):
1204
+ config: BertConfig
1205
+ dtype: jnp.dtype = jnp.float32
1206
+ gradient_checkpointing: bool = False
1207
+
1208
+ def setup(self):
1209
+ self.bert = FlaxBertModule(
1210
+ config=self.config,
1211
+ dtype=self.dtype,
1212
+ gradient_checkpointing=self.gradient_checkpointing,
1213
+ )
1214
+ self.cls = FlaxBertOnlyNSPHead(dtype=self.dtype)
1215
+
1216
+ def __call__(
1217
+ self,
1218
+ input_ids,
1219
+ attention_mask,
1220
+ token_type_ids,
1221
+ position_ids,
1222
+ head_mask,
1223
+ deterministic: bool = True,
1224
+ output_attentions: bool = False,
1225
+ output_hidden_states: bool = False,
1226
+ return_dict: bool = True,
1227
+ ):
1228
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1229
+
1230
+ # Model
1231
+ outputs = self.bert(
1232
+ input_ids,
1233
+ attention_mask,
1234
+ token_type_ids,
1235
+ position_ids,
1236
+ head_mask,
1237
+ deterministic=deterministic,
1238
+ output_attentions=output_attentions,
1239
+ output_hidden_states=output_hidden_states,
1240
+ return_dict=return_dict,
1241
+ )
1242
+
1243
+ pooled_output = outputs[1]
1244
+ seq_relationship_scores = self.cls(pooled_output)
1245
+
1246
+ if not return_dict:
1247
+ return (seq_relationship_scores,) + outputs[2:]
1248
+
1249
+ return FlaxNextSentencePredictorOutput(
1250
+ logits=seq_relationship_scores,
1251
+ hidden_states=outputs.hidden_states,
1252
+ attentions=outputs.attentions,
1253
+ )
1254
+
1255
+
1256
+ @add_start_docstrings(
1257
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1258
+ BERT_START_DOCSTRING,
1259
+ )
1260
+ class FlaxBertForNextSentencePrediction(FlaxBertPreTrainedModel):
1261
+ module_class = FlaxBertForNextSentencePredictionModule
1262
+
1263
+
1264
+ FLAX_BERT_FOR_NEXT_SENT_PRED_DOCSTRING = """
1265
+ Returns:
1266
+
1267
+ Example:
1268
+
1269
+ ```python
1270
+ >>> from transformers import AutoTokenizer, FlaxBertForNextSentencePrediction
1271
+
1272
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1273
+ >>> model = FlaxBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1274
+
1275
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1276
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1277
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="jax")
1278
+
1279
+ >>> outputs = model(**encoding)
1280
+ >>> logits = outputs.logits
1281
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1282
+ ```
1283
+ """
1284
+
1285
+
1286
+ overwrite_call_docstring(
1287
+ FlaxBertForNextSentencePrediction,
1288
+ BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_BERT_FOR_NEXT_SENT_PRED_DOCSTRING,
1289
+ )
1290
+ append_replace_return_docstrings(
1291
+ FlaxBertForNextSentencePrediction, output_type=FlaxNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC
1292
+ )
1293
+
1294
+
1295
+ class FlaxBertForSequenceClassificationModule(nn.Module):
1296
+ config: BertConfig
1297
+ dtype: jnp.dtype = jnp.float32
1298
+ gradient_checkpointing: bool = False
1299
+
1300
+ def setup(self):
1301
+ self.bert = FlaxBertModule(
1302
+ config=self.config,
1303
+ dtype=self.dtype,
1304
+ gradient_checkpointing=self.gradient_checkpointing,
1305
+ )
1306
+ classifier_dropout = (
1307
+ self.config.classifier_dropout
1308
+ if self.config.classifier_dropout is not None
1309
+ else self.config.hidden_dropout_prob
1310
+ )
1311
+ self.dropout = nn.Dropout(rate=classifier_dropout)
1312
+ self.classifier = nn.Dense(
1313
+ self.config.num_labels,
1314
+ dtype=self.dtype,
1315
+ )
1316
+
1317
+ def __call__(
1318
+ self,
1319
+ input_ids,
1320
+ attention_mask,
1321
+ token_type_ids,
1322
+ position_ids,
1323
+ head_mask,
1324
+ deterministic: bool = True,
1325
+ output_attentions: bool = False,
1326
+ output_hidden_states: bool = False,
1327
+ return_dict: bool = True,
1328
+ ):
1329
+ # Model
1330
+ outputs = self.bert(
1331
+ input_ids,
1332
+ attention_mask,
1333
+ token_type_ids,
1334
+ position_ids,
1335
+ head_mask,
1336
+ deterministic=deterministic,
1337
+ output_attentions=output_attentions,
1338
+ output_hidden_states=output_hidden_states,
1339
+ return_dict=return_dict,
1340
+ )
1341
+
1342
+ pooled_output = outputs[1]
1343
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
1344
+ logits = self.classifier(pooled_output)
1345
+
1346
+ if not return_dict:
1347
+ return (logits,) + outputs[2:]
1348
+
1349
+ return FlaxSequenceClassifierOutput(
1350
+ logits=logits,
1351
+ hidden_states=outputs.hidden_states,
1352
+ attentions=outputs.attentions,
1353
+ )
1354
+
1355
+
1356
+ @add_start_docstrings(
1357
+ """
1358
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1359
+ output) e.g. for GLUE tasks.
1360
+ """,
1361
+ BERT_START_DOCSTRING,
1362
+ )
1363
+ class FlaxBertForSequenceClassification(FlaxBertPreTrainedModel):
1364
+ module_class = FlaxBertForSequenceClassificationModule
1365
+
1366
+
1367
+ append_call_sample_docstring(
1368
+ FlaxBertForSequenceClassification,
1369
+ _CHECKPOINT_FOR_DOC,
1370
+ FlaxSequenceClassifierOutput,
1371
+ _CONFIG_FOR_DOC,
1372
+ )
1373
+
1374
+
1375
+ class FlaxBertForMultipleChoiceModule(nn.Module):
1376
+ config: BertConfig
1377
+ dtype: jnp.dtype = jnp.float32
1378
+ gradient_checkpointing: bool = False
1379
+
1380
+ def setup(self):
1381
+ self.bert = FlaxBertModule(
1382
+ config=self.config,
1383
+ dtype=self.dtype,
1384
+ gradient_checkpointing=self.gradient_checkpointing,
1385
+ )
1386
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
1387
+ self.classifier = nn.Dense(1, dtype=self.dtype)
1388
+
1389
+ def __call__(
1390
+ self,
1391
+ input_ids,
1392
+ attention_mask,
1393
+ token_type_ids,
1394
+ position_ids,
1395
+ head_mask,
1396
+ deterministic: bool = True,
1397
+ output_attentions: bool = False,
1398
+ output_hidden_states: bool = False,
1399
+ return_dict: bool = True,
1400
+ ):
1401
+ num_choices = input_ids.shape[1]
1402
+ input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
1403
+ attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
1404
+ token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
1405
+ position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
1406
+
1407
+ # Model
1408
+ outputs = self.bert(
1409
+ input_ids,
1410
+ attention_mask,
1411
+ token_type_ids,
1412
+ position_ids,
1413
+ head_mask,
1414
+ deterministic=deterministic,
1415
+ output_attentions=output_attentions,
1416
+ output_hidden_states=output_hidden_states,
1417
+ return_dict=return_dict,
1418
+ )
1419
+
1420
+ pooled_output = outputs[1]
1421
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
1422
+ logits = self.classifier(pooled_output)
1423
+
1424
+ reshaped_logits = logits.reshape(-1, num_choices)
1425
+
1426
+ if not return_dict:
1427
+ return (reshaped_logits,) + outputs[2:]
1428
+
1429
+ return FlaxMultipleChoiceModelOutput(
1430
+ logits=reshaped_logits,
1431
+ hidden_states=outputs.hidden_states,
1432
+ attentions=outputs.attentions,
1433
+ )
1434
+
1435
+
1436
+ @add_start_docstrings(
1437
+ """
1438
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1439
+ softmax) e.g. for RocStories/SWAG tasks.
1440
+ """,
1441
+ BERT_START_DOCSTRING,
1442
+ )
1443
+ class FlaxBertForMultipleChoice(FlaxBertPreTrainedModel):
1444
+ module_class = FlaxBertForMultipleChoiceModule
1445
+
1446
+
1447
+ overwrite_call_docstring(
1448
+ FlaxBertForMultipleChoice, BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1449
+ )
1450
+ append_call_sample_docstring(
1451
+ FlaxBertForMultipleChoice, _CHECKPOINT_FOR_DOC, FlaxMultipleChoiceModelOutput, _CONFIG_FOR_DOC
1452
+ )
1453
+
1454
+
1455
+ class FlaxBertForTokenClassificationModule(nn.Module):
1456
+ config: BertConfig
1457
+ dtype: jnp.dtype = jnp.float32
1458
+ gradient_checkpointing: bool = False
1459
+
1460
+ def setup(self):
1461
+ self.bert = FlaxBertModule(
1462
+ config=self.config,
1463
+ dtype=self.dtype,
1464
+ add_pooling_layer=False,
1465
+ gradient_checkpointing=self.gradient_checkpointing,
1466
+ )
1467
+ classifier_dropout = (
1468
+ self.config.classifier_dropout
1469
+ if self.config.classifier_dropout is not None
1470
+ else self.config.hidden_dropout_prob
1471
+ )
1472
+ self.dropout = nn.Dropout(rate=classifier_dropout)
1473
+ self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
1474
+
1475
+ def __call__(
1476
+ self,
1477
+ input_ids,
1478
+ attention_mask,
1479
+ token_type_ids,
1480
+ position_ids,
1481
+ head_mask,
1482
+ deterministic: bool = True,
1483
+ output_attentions: bool = False,
1484
+ output_hidden_states: bool = False,
1485
+ return_dict: bool = True,
1486
+ ):
1487
+ # Model
1488
+ outputs = self.bert(
1489
+ input_ids,
1490
+ attention_mask,
1491
+ token_type_ids,
1492
+ position_ids,
1493
+ head_mask,
1494
+ deterministic=deterministic,
1495
+ output_attentions=output_attentions,
1496
+ output_hidden_states=output_hidden_states,
1497
+ return_dict=return_dict,
1498
+ )
1499
+
1500
+ hidden_states = outputs[0]
1501
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
1502
+ logits = self.classifier(hidden_states)
1503
+
1504
+ if not return_dict:
1505
+ return (logits,) + outputs[1:]
1506
+
1507
+ return FlaxTokenClassifierOutput(
1508
+ logits=logits,
1509
+ hidden_states=outputs.hidden_states,
1510
+ attentions=outputs.attentions,
1511
+ )
1512
+
1513
+
1514
+ @add_start_docstrings(
1515
+ """
1516
+ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1517
+ Named-Entity-Recognition (NER) tasks.
1518
+ """,
1519
+ BERT_START_DOCSTRING,
1520
+ )
1521
+ class FlaxBertForTokenClassification(FlaxBertPreTrainedModel):
1522
+ module_class = FlaxBertForTokenClassificationModule
1523
+
1524
+
1525
+ append_call_sample_docstring(
1526
+ FlaxBertForTokenClassification, _CHECKPOINT_FOR_DOC, FlaxTokenClassifierOutput, _CONFIG_FOR_DOC
1527
+ )
1528
+
1529
+
1530
+ class FlaxBertForQuestionAnsweringModule(nn.Module):
1531
+ config: BertConfig
1532
+ dtype: jnp.dtype = jnp.float32
1533
+ gradient_checkpointing: bool = False
1534
+
1535
+ def setup(self):
1536
+ self.bert = FlaxBertModule(
1537
+ config=self.config,
1538
+ dtype=self.dtype,
1539
+ add_pooling_layer=False,
1540
+ gradient_checkpointing=self.gradient_checkpointing,
1541
+ )
1542
+ self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
1543
+
1544
+ def __call__(
1545
+ self,
1546
+ input_ids,
1547
+ attention_mask,
1548
+ token_type_ids,
1549
+ position_ids,
1550
+ head_mask,
1551
+ deterministic: bool = True,
1552
+ output_attentions: bool = False,
1553
+ output_hidden_states: bool = False,
1554
+ return_dict: bool = True,
1555
+ ):
1556
+ # Model
1557
+ outputs = self.bert(
1558
+ input_ids,
1559
+ attention_mask,
1560
+ token_type_ids,
1561
+ position_ids,
1562
+ head_mask,
1563
+ deterministic=deterministic,
1564
+ output_attentions=output_attentions,
1565
+ output_hidden_states=output_hidden_states,
1566
+ return_dict=return_dict,
1567
+ )
1568
+
1569
+ hidden_states = outputs[0]
1570
+
1571
+ logits = self.qa_outputs(hidden_states)
1572
+ start_logits, end_logits = jnp.split(logits, self.config.num_labels, axis=-1)
1573
+ start_logits = start_logits.squeeze(-1)
1574
+ end_logits = end_logits.squeeze(-1)
1575
+
1576
+ if not return_dict:
1577
+ return (start_logits, end_logits) + outputs[1:]
1578
+
1579
+ return FlaxQuestionAnsweringModelOutput(
1580
+ start_logits=start_logits,
1581
+ end_logits=end_logits,
1582
+ hidden_states=outputs.hidden_states,
1583
+ attentions=outputs.attentions,
1584
+ )
1585
+
1586
+
1587
+ @add_start_docstrings(
1588
+ """
1589
+ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1590
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1591
+ """,
1592
+ BERT_START_DOCSTRING,
1593
+ )
1594
+ class FlaxBertForQuestionAnswering(FlaxBertPreTrainedModel):
1595
+ module_class = FlaxBertForQuestionAnsweringModule
1596
+
1597
+
1598
+ append_call_sample_docstring(
1599
+ FlaxBertForQuestionAnswering,
1600
+ _CHECKPOINT_FOR_DOC,
1601
+ FlaxQuestionAnsweringModelOutput,
1602
+ _CONFIG_FOR_DOC,
1603
+ )
1604
+
1605
+
1606
+ class FlaxBertForCausalLMModule(nn.Module):
1607
+ config: BertConfig
1608
+ dtype: jnp.dtype = jnp.float32
1609
+ gradient_checkpointing: bool = False
1610
+
1611
+ def setup(self):
1612
+ self.bert = FlaxBertModule(
1613
+ config=self.config,
1614
+ add_pooling_layer=False,
1615
+ dtype=self.dtype,
1616
+ gradient_checkpointing=self.gradient_checkpointing,
1617
+ )
1618
+ self.cls = FlaxBertOnlyMLMHead(config=self.config, dtype=self.dtype)
1619
+
1620
+ def __call__(
1621
+ self,
1622
+ input_ids,
1623
+ attention_mask,
1624
+ position_ids,
1625
+ token_type_ids: Optional[jnp.ndarray] = None,
1626
+ head_mask: Optional[jnp.ndarray] = None,
1627
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
1628
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1629
+ init_cache: bool = False,
1630
+ deterministic: bool = True,
1631
+ output_attentions: bool = False,
1632
+ output_hidden_states: bool = False,
1633
+ return_dict: bool = True,
1634
+ ):
1635
+ # Model
1636
+ outputs = self.bert(
1637
+ input_ids,
1638
+ attention_mask,
1639
+ token_type_ids,
1640
+ position_ids,
1641
+ head_mask,
1642
+ encoder_hidden_states=encoder_hidden_states,
1643
+ encoder_attention_mask=encoder_attention_mask,
1644
+ init_cache=init_cache,
1645
+ deterministic=deterministic,
1646
+ output_attentions=output_attentions,
1647
+ output_hidden_states=output_hidden_states,
1648
+ return_dict=return_dict,
1649
+ )
1650
+
1651
+ hidden_states = outputs[0]
1652
+ if self.config.tie_word_embeddings:
1653
+ shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1654
+ else:
1655
+ shared_embedding = None
1656
+
1657
+ # Compute the prediction scores
1658
+ logits = self.cls(hidden_states, shared_embedding=shared_embedding)
1659
+
1660
+ if not return_dict:
1661
+ return (logits,) + outputs[1:]
1662
+
1663
+ return FlaxCausalLMOutputWithCrossAttentions(
1664
+ logits=logits,
1665
+ hidden_states=outputs.hidden_states,
1666
+ attentions=outputs.attentions,
1667
+ cross_attentions=outputs.cross_attentions,
1668
+ )
1669
+
1670
+
1671
+ @add_start_docstrings(
1672
+ """
1673
+ Bert Model with a language modeling head on top (a linear layer on top of the hidden-states output) e.g for
1674
+ autoregressive tasks.
1675
+ """,
1676
+ BERT_START_DOCSTRING,
1677
+ )
1678
+ class FlaxBertForCausalLM(FlaxBertPreTrainedModel):
1679
+ module_class = FlaxBertForCausalLMModule
1680
+
1681
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
1682
+ # initializing the cache
1683
+ batch_size, seq_length = input_ids.shape
1684
+
1685
+ past_key_values = self.init_cache(batch_size, max_length)
1686
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1687
+ # But since the decoder uses a causal mask, those positions are masked anyway.
1688
+ # Thus, we can create a single static attention_mask here, which is more efficient for compilation
1689
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1690
+ if attention_mask is not None:
1691
+ position_ids = attention_mask.cumsum(axis=-1) - 1
1692
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
1693
+ else:
1694
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1695
+
1696
+ return {
1697
+ "past_key_values": past_key_values,
1698
+ "attention_mask": extended_attention_mask,
1699
+ "position_ids": position_ids,
1700
+ }
1701
+
1702
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1703
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1704
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
1705
+ return model_kwargs
1706
+
1707
+
1708
+ append_call_sample_docstring(
1709
+ FlaxBertForCausalLM,
1710
+ _CHECKPOINT_FOR_DOC,
1711
+ FlaxCausalLMOutputWithCrossAttentions,
1712
+ _CONFIG_FOR_DOC,
1713
+ )
1714
+
1715
+
1716
+ __all__ = [
1717
+ "FlaxBertForCausalLM",
1718
+ "FlaxBertForMaskedLM",
1719
+ "FlaxBertForMultipleChoice",
1720
+ "FlaxBertForNextSentencePrediction",
1721
+ "FlaxBertForPreTraining",
1722
+ "FlaxBertForQuestionAnswering",
1723
+ "FlaxBertForSequenceClassification",
1724
+ "FlaxBertForTokenClassification",
1725
+ "FlaxBertModel",
1726
+ "FlaxBertPreTrainedModel",
1727
+ ]
lib/python3.12/site-packages/transformers/models/bert/modeling_tf_bert.py ADDED
@@ -0,0 +1,2126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """TF 2.0 BERT model."""
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Dict, Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import tensorflow as tf
27
+
28
+ from ...activations_tf import get_tf_activation
29
+ from ...modeling_tf_outputs import (
30
+ TFBaseModelOutputWithPastAndCrossAttentions,
31
+ TFBaseModelOutputWithPoolingAndCrossAttentions,
32
+ TFCausalLMOutputWithCrossAttentions,
33
+ TFMaskedLMOutput,
34
+ TFMultipleChoiceModelOutput,
35
+ TFNextSentencePredictorOutput,
36
+ TFQuestionAnsweringModelOutput,
37
+ TFSequenceClassifierOutput,
38
+ TFTokenClassifierOutput,
39
+ )
40
+ from ...modeling_tf_utils import (
41
+ TFCausalLanguageModelingLoss,
42
+ TFMaskedLanguageModelingLoss,
43
+ TFModelInputType,
44
+ TFMultipleChoiceLoss,
45
+ TFNextSentencePredictionLoss,
46
+ TFPreTrainedModel,
47
+ TFQuestionAnsweringLoss,
48
+ TFSequenceClassificationLoss,
49
+ TFTokenClassificationLoss,
50
+ get_initializer,
51
+ keras,
52
+ keras_serializable,
53
+ unpack_inputs,
54
+ )
55
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
56
+ from ...utils import (
57
+ ModelOutput,
58
+ add_code_sample_docstrings,
59
+ add_start_docstrings,
60
+ add_start_docstrings_to_model_forward,
61
+ logging,
62
+ replace_return_docstrings,
63
+ )
64
+ from .configuration_bert import BertConfig
65
+
66
+
67
+ logger = logging.get_logger(__name__)
68
+
69
+ _CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
70
+ _CONFIG_FOR_DOC = "BertConfig"
71
+
72
+ # TokenClassification docstring
73
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
74
+ _TOKEN_CLASS_EXPECTED_OUTPUT = (
75
+ "['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
76
+ )
77
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.01
78
+
79
+ # QuestionAnswering docstring
80
+ _CHECKPOINT_FOR_QA = "ydshieh/bert-base-cased-squad2"
81
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
82
+ _QA_EXPECTED_LOSS = 7.41
83
+ _QA_TARGET_START_INDEX = 14
84
+ _QA_TARGET_END_INDEX = 15
85
+
86
+ # SequenceClassification docstring
87
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ydshieh/bert-base-uncased-yelp-polarity"
88
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
89
+ _SEQ_CLASS_EXPECTED_LOSS = 0.01
90
+
91
+
92
+ class TFBertPreTrainingLoss:
93
+ """
94
+ Loss function suitable for BERT-like pretraining, that is, the task of pretraining a language model by combining
95
+ NSP + MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss
96
+ computation.
97
+ """
98
+
99
+ def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
100
+ loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=keras.losses.Reduction.NONE)
101
+
102
+ # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
103
+ unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
104
+ # make sure only labels that are not equal to -100
105
+ # are taken into account for the loss computation
106
+ lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
107
+ masked_lm_losses = unmasked_lm_losses * lm_loss_mask
108
+ reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
109
+
110
+ # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
111
+ unmasked_ns_loss = loss_fn(y_true=tf.nn.relu(labels["next_sentence_label"]), y_pred=logits[1])
112
+ ns_loss_mask = tf.cast(labels["next_sentence_label"] != -100, dtype=unmasked_ns_loss.dtype)
113
+ masked_ns_loss = unmasked_ns_loss * ns_loss_mask
114
+
115
+ reduced_masked_ns_loss = tf.reduce_sum(masked_ns_loss) / tf.reduce_sum(ns_loss_mask)
116
+
117
+ return tf.reshape(reduced_masked_lm_loss + reduced_masked_ns_loss, (1,))
118
+
119
+
120
+ class TFBertEmbeddings(keras.layers.Layer):
121
+ """Construct the embeddings from word, position and token_type embeddings."""
122
+
123
+ def __init__(self, config: BertConfig, **kwargs):
124
+ super().__init__(**kwargs)
125
+
126
+ self.config = config
127
+ self.hidden_size = config.hidden_size
128
+ self.max_position_embeddings = config.max_position_embeddings
129
+ self.initializer_range = config.initializer_range
130
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
131
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
132
+
133
+ def build(self, input_shape=None):
134
+ with tf.name_scope("word_embeddings"):
135
+ self.weight = self.add_weight(
136
+ name="weight",
137
+ shape=[self.config.vocab_size, self.hidden_size],
138
+ initializer=get_initializer(self.initializer_range),
139
+ )
140
+
141
+ with tf.name_scope("token_type_embeddings"):
142
+ self.token_type_embeddings = self.add_weight(
143
+ name="embeddings",
144
+ shape=[self.config.type_vocab_size, self.hidden_size],
145
+ initializer=get_initializer(self.initializer_range),
146
+ )
147
+
148
+ with tf.name_scope("position_embeddings"):
149
+ self.position_embeddings = self.add_weight(
150
+ name="embeddings",
151
+ shape=[self.max_position_embeddings, self.hidden_size],
152
+ initializer=get_initializer(self.initializer_range),
153
+ )
154
+
155
+ if self.built:
156
+ return
157
+ self.built = True
158
+ if getattr(self, "LayerNorm", None) is not None:
159
+ with tf.name_scope(self.LayerNorm.name):
160
+ self.LayerNorm.build([None, None, self.config.hidden_size])
161
+
162
+ def call(
163
+ self,
164
+ input_ids: Optional[tf.Tensor] = None,
165
+ position_ids: Optional[tf.Tensor] = None,
166
+ token_type_ids: Optional[tf.Tensor] = None,
167
+ inputs_embeds: Optional[tf.Tensor] = None,
168
+ past_key_values_length=0,
169
+ training: bool = False,
170
+ ) -> tf.Tensor:
171
+ """
172
+ Applies embedding based on inputs tensor.
173
+
174
+ Returns:
175
+ final_embeddings (`tf.Tensor`): output embedding tensor.
176
+ """
177
+ if input_ids is None and inputs_embeds is None:
178
+ raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
179
+
180
+ if input_ids is not None:
181
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
182
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
183
+
184
+ input_shape = shape_list(inputs_embeds)[:-1]
185
+
186
+ if token_type_ids is None:
187
+ token_type_ids = tf.fill(dims=input_shape, value=0)
188
+
189
+ if position_ids is None:
190
+ position_ids = tf.expand_dims(
191
+ tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
192
+ )
193
+
194
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
195
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
196
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
197
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
198
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
199
+
200
+ return final_embeddings
201
+
202
+
203
+ class TFBertSelfAttention(keras.layers.Layer):
204
+ def __init__(self, config: BertConfig, **kwargs):
205
+ super().__init__(**kwargs)
206
+
207
+ if config.hidden_size % config.num_attention_heads != 0:
208
+ raise ValueError(
209
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number "
210
+ f"of attention heads ({config.num_attention_heads})"
211
+ )
212
+
213
+ self.num_attention_heads = config.num_attention_heads
214
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
215
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
216
+ self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
217
+
218
+ self.query = keras.layers.Dense(
219
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
220
+ )
221
+ self.key = keras.layers.Dense(
222
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
223
+ )
224
+ self.value = keras.layers.Dense(
225
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
226
+ )
227
+ self.dropout = keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
228
+
229
+ self.is_decoder = config.is_decoder
230
+ self.config = config
231
+
232
+ def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
233
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
234
+ tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
235
+
236
+ # Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
237
+ return tf.transpose(tensor, perm=[0, 2, 1, 3])
238
+
239
+ def call(
240
+ self,
241
+ hidden_states: tf.Tensor,
242
+ attention_mask: tf.Tensor,
243
+ head_mask: tf.Tensor,
244
+ encoder_hidden_states: tf.Tensor,
245
+ encoder_attention_mask: tf.Tensor,
246
+ past_key_value: Tuple[tf.Tensor],
247
+ output_attentions: bool,
248
+ training: bool = False,
249
+ ) -> Tuple[tf.Tensor]:
250
+ batch_size = shape_list(hidden_states)[0]
251
+ mixed_query_layer = self.query(inputs=hidden_states)
252
+
253
+ # If this is instantiated as a cross-attention module, the keys
254
+ # and values come from an encoder; the attention mask needs to be
255
+ # such that the encoder's padding tokens are not attended to.
256
+ is_cross_attention = encoder_hidden_states is not None
257
+
258
+ if is_cross_attention and past_key_value is not None:
259
+ # reuse k,v, cross_attentions
260
+ key_layer = past_key_value[0]
261
+ value_layer = past_key_value[1]
262
+ attention_mask = encoder_attention_mask
263
+ elif is_cross_attention:
264
+ key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
265
+ value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
266
+ attention_mask = encoder_attention_mask
267
+ elif past_key_value is not None:
268
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
269
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
270
+ key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
271
+ value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
272
+ else:
273
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
274
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
275
+
276
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
277
+
278
+ if self.is_decoder:
279
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
280
+ # Further calls to cross_attention layer can then reuse all cross-attention
281
+ # key/value_states (first "if" case)
282
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
283
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
284
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
285
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
286
+ past_key_value = (key_layer, value_layer)
287
+
288
+ # Take the dot product between "query" and "key" to get the raw attention scores.
289
+ # (batch size, num_heads, seq_len_q, seq_len_k)
290
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
291
+ dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
292
+ attention_scores = tf.divide(attention_scores, dk)
293
+
294
+ if attention_mask is not None:
295
+ # Apply the attention mask is (precomputed for all layers in TFBertModel call() function)
296
+ attention_scores = tf.add(attention_scores, attention_mask)
297
+
298
+ # Normalize the attention scores to probabilities.
299
+ attention_probs = stable_softmax(logits=attention_scores, axis=-1)
300
+
301
+ # This is actually dropping out entire tokens to attend to, which might
302
+ # seem a bit unusual, but is taken from the original Transformer paper.
303
+ attention_probs = self.dropout(inputs=attention_probs, training=training)
304
+
305
+ # Mask heads if we want to
306
+ if head_mask is not None:
307
+ attention_probs = tf.multiply(attention_probs, head_mask)
308
+
309
+ attention_output = tf.matmul(attention_probs, value_layer)
310
+ attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
311
+
312
+ # (batch_size, seq_len_q, all_head_size)
313
+ attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
314
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
315
+
316
+ if self.is_decoder:
317
+ outputs = outputs + (past_key_value,)
318
+ return outputs
319
+
320
+ def build(self, input_shape=None):
321
+ if self.built:
322
+ return
323
+ self.built = True
324
+ if getattr(self, "query", None) is not None:
325
+ with tf.name_scope(self.query.name):
326
+ self.query.build([None, None, self.config.hidden_size])
327
+ if getattr(self, "key", None) is not None:
328
+ with tf.name_scope(self.key.name):
329
+ self.key.build([None, None, self.config.hidden_size])
330
+ if getattr(self, "value", None) is not None:
331
+ with tf.name_scope(self.value.name):
332
+ self.value.build([None, None, self.config.hidden_size])
333
+
334
+
335
+ class TFBertSelfOutput(keras.layers.Layer):
336
+ def __init__(self, config: BertConfig, **kwargs):
337
+ super().__init__(**kwargs)
338
+
339
+ self.dense = keras.layers.Dense(
340
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
341
+ )
342
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
343
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
344
+ self.config = config
345
+
346
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
347
+ hidden_states = self.dense(inputs=hidden_states)
348
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
349
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
350
+
351
+ return hidden_states
352
+
353
+ def build(self, input_shape=None):
354
+ if self.built:
355
+ return
356
+ self.built = True
357
+ if getattr(self, "dense", None) is not None:
358
+ with tf.name_scope(self.dense.name):
359
+ self.dense.build([None, None, self.config.hidden_size])
360
+ if getattr(self, "LayerNorm", None) is not None:
361
+ with tf.name_scope(self.LayerNorm.name):
362
+ self.LayerNorm.build([None, None, self.config.hidden_size])
363
+
364
+
365
+ class TFBertAttention(keras.layers.Layer):
366
+ def __init__(self, config: BertConfig, **kwargs):
367
+ super().__init__(**kwargs)
368
+
369
+ self.self_attention = TFBertSelfAttention(config, name="self")
370
+ self.dense_output = TFBertSelfOutput(config, name="output")
371
+
372
+ def prune_heads(self, heads):
373
+ raise NotImplementedError
374
+
375
+ def call(
376
+ self,
377
+ input_tensor: tf.Tensor,
378
+ attention_mask: tf.Tensor,
379
+ head_mask: tf.Tensor,
380
+ encoder_hidden_states: tf.Tensor,
381
+ encoder_attention_mask: tf.Tensor,
382
+ past_key_value: Tuple[tf.Tensor],
383
+ output_attentions: bool,
384
+ training: bool = False,
385
+ ) -> Tuple[tf.Tensor]:
386
+ self_outputs = self.self_attention(
387
+ hidden_states=input_tensor,
388
+ attention_mask=attention_mask,
389
+ head_mask=head_mask,
390
+ encoder_hidden_states=encoder_hidden_states,
391
+ encoder_attention_mask=encoder_attention_mask,
392
+ past_key_value=past_key_value,
393
+ output_attentions=output_attentions,
394
+ training=training,
395
+ )
396
+ attention_output = self.dense_output(
397
+ hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
398
+ )
399
+ # add attentions (possibly with past_key_value) if we output them
400
+ outputs = (attention_output,) + self_outputs[1:]
401
+
402
+ return outputs
403
+
404
+ def build(self, input_shape=None):
405
+ if self.built:
406
+ return
407
+ self.built = True
408
+ if getattr(self, "self_attention", None) is not None:
409
+ with tf.name_scope(self.self_attention.name):
410
+ self.self_attention.build(None)
411
+ if getattr(self, "dense_output", None) is not None:
412
+ with tf.name_scope(self.dense_output.name):
413
+ self.dense_output.build(None)
414
+
415
+
416
+ class TFBertIntermediate(keras.layers.Layer):
417
+ def __init__(self, config: BertConfig, **kwargs):
418
+ super().__init__(**kwargs)
419
+
420
+ self.dense = keras.layers.Dense(
421
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
422
+ )
423
+
424
+ if isinstance(config.hidden_act, str):
425
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
426
+ else:
427
+ self.intermediate_act_fn = config.hidden_act
428
+ self.config = config
429
+
430
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
431
+ hidden_states = self.dense(inputs=hidden_states)
432
+ hidden_states = self.intermediate_act_fn(hidden_states)
433
+
434
+ return hidden_states
435
+
436
+ def build(self, input_shape=None):
437
+ if self.built:
438
+ return
439
+ self.built = True
440
+ if getattr(self, "dense", None) is not None:
441
+ with tf.name_scope(self.dense.name):
442
+ self.dense.build([None, None, self.config.hidden_size])
443
+
444
+
445
+ class TFBertOutput(keras.layers.Layer):
446
+ def __init__(self, config: BertConfig, **kwargs):
447
+ super().__init__(**kwargs)
448
+
449
+ self.dense = keras.layers.Dense(
450
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
451
+ )
452
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
453
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
454
+ self.config = config
455
+
456
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
457
+ hidden_states = self.dense(inputs=hidden_states)
458
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
459
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
460
+
461
+ return hidden_states
462
+
463
+ def build(self, input_shape=None):
464
+ if self.built:
465
+ return
466
+ self.built = True
467
+ if getattr(self, "dense", None) is not None:
468
+ with tf.name_scope(self.dense.name):
469
+ self.dense.build([None, None, self.config.intermediate_size])
470
+ if getattr(self, "LayerNorm", None) is not None:
471
+ with tf.name_scope(self.LayerNorm.name):
472
+ self.LayerNorm.build([None, None, self.config.hidden_size])
473
+
474
+
475
+ class TFBertLayer(keras.layers.Layer):
476
+ def __init__(self, config: BertConfig, **kwargs):
477
+ super().__init__(**kwargs)
478
+
479
+ self.attention = TFBertAttention(config, name="attention")
480
+ self.is_decoder = config.is_decoder
481
+ self.add_cross_attention = config.add_cross_attention
482
+ if self.add_cross_attention:
483
+ if not self.is_decoder:
484
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
485
+ self.crossattention = TFBertAttention(config, name="crossattention")
486
+ self.intermediate = TFBertIntermediate(config, name="intermediate")
487
+ self.bert_output = TFBertOutput(config, name="output")
488
+
489
+ def call(
490
+ self,
491
+ hidden_states: tf.Tensor,
492
+ attention_mask: tf.Tensor,
493
+ head_mask: tf.Tensor,
494
+ encoder_hidden_states: tf.Tensor | None,
495
+ encoder_attention_mask: tf.Tensor | None,
496
+ past_key_value: Tuple[tf.Tensor] | None,
497
+ output_attentions: bool,
498
+ training: bool = False,
499
+ ) -> Tuple[tf.Tensor]:
500
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
501
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
502
+ self_attention_outputs = self.attention(
503
+ input_tensor=hidden_states,
504
+ attention_mask=attention_mask,
505
+ head_mask=head_mask,
506
+ encoder_hidden_states=None,
507
+ encoder_attention_mask=None,
508
+ past_key_value=self_attn_past_key_value,
509
+ output_attentions=output_attentions,
510
+ training=training,
511
+ )
512
+ attention_output = self_attention_outputs[0]
513
+
514
+ # if decoder, the last output is tuple of self-attn cache
515
+ if self.is_decoder:
516
+ outputs = self_attention_outputs[1:-1]
517
+ present_key_value = self_attention_outputs[-1]
518
+ else:
519
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
520
+
521
+ cross_attn_present_key_value = None
522
+ if self.is_decoder and encoder_hidden_states is not None:
523
+ if not hasattr(self, "crossattention"):
524
+ raise ValueError(
525
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
526
+ " by setting `config.add_cross_attention=True`"
527
+ )
528
+
529
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
530
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
531
+ cross_attention_outputs = self.crossattention(
532
+ input_tensor=attention_output,
533
+ attention_mask=attention_mask,
534
+ head_mask=head_mask,
535
+ encoder_hidden_states=encoder_hidden_states,
536
+ encoder_attention_mask=encoder_attention_mask,
537
+ past_key_value=cross_attn_past_key_value,
538
+ output_attentions=output_attentions,
539
+ training=training,
540
+ )
541
+ attention_output = cross_attention_outputs[0]
542
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
543
+
544
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
545
+ cross_attn_present_key_value = cross_attention_outputs[-1]
546
+ present_key_value = present_key_value + cross_attn_present_key_value
547
+
548
+ intermediate_output = self.intermediate(hidden_states=attention_output)
549
+ layer_output = self.bert_output(
550
+ hidden_states=intermediate_output, input_tensor=attention_output, training=training
551
+ )
552
+ outputs = (layer_output,) + outputs # add attentions if we output them
553
+
554
+ # if decoder, return the attn key/values as the last output
555
+ if self.is_decoder:
556
+ outputs = outputs + (present_key_value,)
557
+
558
+ return outputs
559
+
560
+ def build(self, input_shape=None):
561
+ if self.built:
562
+ return
563
+ self.built = True
564
+ if getattr(self, "attention", None) is not None:
565
+ with tf.name_scope(self.attention.name):
566
+ self.attention.build(None)
567
+ if getattr(self, "intermediate", None) is not None:
568
+ with tf.name_scope(self.intermediate.name):
569
+ self.intermediate.build(None)
570
+ if getattr(self, "bert_output", None) is not None:
571
+ with tf.name_scope(self.bert_output.name):
572
+ self.bert_output.build(None)
573
+ if getattr(self, "crossattention", None) is not None:
574
+ with tf.name_scope(self.crossattention.name):
575
+ self.crossattention.build(None)
576
+
577
+
578
+ class TFBertEncoder(keras.layers.Layer):
579
+ def __init__(self, config: BertConfig, **kwargs):
580
+ super().__init__(**kwargs)
581
+ self.config = config
582
+ self.layer = [TFBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
583
+
584
+ def call(
585
+ self,
586
+ hidden_states: tf.Tensor,
587
+ attention_mask: tf.Tensor,
588
+ head_mask: tf.Tensor,
589
+ encoder_hidden_states: tf.Tensor | None,
590
+ encoder_attention_mask: tf.Tensor | None,
591
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None,
592
+ use_cache: Optional[bool],
593
+ output_attentions: bool,
594
+ output_hidden_states: bool,
595
+ return_dict: bool,
596
+ training: bool = False,
597
+ ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
598
+ all_hidden_states = () if output_hidden_states else None
599
+ all_attentions = () if output_attentions else None
600
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
601
+
602
+ next_decoder_cache = () if use_cache else None
603
+ for i, layer_module in enumerate(self.layer):
604
+ if output_hidden_states:
605
+ all_hidden_states = all_hidden_states + (hidden_states,)
606
+
607
+ past_key_value = past_key_values[i] if past_key_values is not None else None
608
+
609
+ layer_outputs = layer_module(
610
+ hidden_states=hidden_states,
611
+ attention_mask=attention_mask,
612
+ head_mask=head_mask[i],
613
+ encoder_hidden_states=encoder_hidden_states,
614
+ encoder_attention_mask=encoder_attention_mask,
615
+ past_key_value=past_key_value,
616
+ output_attentions=output_attentions,
617
+ training=training,
618
+ )
619
+ hidden_states = layer_outputs[0]
620
+
621
+ if use_cache:
622
+ next_decoder_cache += (layer_outputs[-1],)
623
+
624
+ if output_attentions:
625
+ all_attentions = all_attentions + (layer_outputs[1],)
626
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
627
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
628
+
629
+ # Add last layer
630
+ if output_hidden_states:
631
+ all_hidden_states = all_hidden_states + (hidden_states,)
632
+
633
+ if not return_dict:
634
+ return tuple(
635
+ v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
636
+ )
637
+
638
+ return TFBaseModelOutputWithPastAndCrossAttentions(
639
+ last_hidden_state=hidden_states,
640
+ past_key_values=next_decoder_cache,
641
+ hidden_states=all_hidden_states,
642
+ attentions=all_attentions,
643
+ cross_attentions=all_cross_attentions,
644
+ )
645
+
646
+ def build(self, input_shape=None):
647
+ if self.built:
648
+ return
649
+ self.built = True
650
+ if getattr(self, "layer", None) is not None:
651
+ for layer in self.layer:
652
+ with tf.name_scope(layer.name):
653
+ layer.build(None)
654
+
655
+
656
+ class TFBertPooler(keras.layers.Layer):
657
+ def __init__(self, config: BertConfig, **kwargs):
658
+ super().__init__(**kwargs)
659
+
660
+ self.dense = keras.layers.Dense(
661
+ units=config.hidden_size,
662
+ kernel_initializer=get_initializer(config.initializer_range),
663
+ activation="tanh",
664
+ name="dense",
665
+ )
666
+ self.config = config
667
+
668
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
669
+ # We "pool" the model by simply taking the hidden state corresponding
670
+ # to the first token.
671
+ first_token_tensor = hidden_states[:, 0]
672
+ pooled_output = self.dense(inputs=first_token_tensor)
673
+
674
+ return pooled_output
675
+
676
+ def build(self, input_shape=None):
677
+ if self.built:
678
+ return
679
+ self.built = True
680
+ if getattr(self, "dense", None) is not None:
681
+ with tf.name_scope(self.dense.name):
682
+ self.dense.build([None, None, self.config.hidden_size])
683
+
684
+
685
+ class TFBertPredictionHeadTransform(keras.layers.Layer):
686
+ def __init__(self, config: BertConfig, **kwargs):
687
+ super().__init__(**kwargs)
688
+
689
+ self.dense = keras.layers.Dense(
690
+ units=config.hidden_size,
691
+ kernel_initializer=get_initializer(config.initializer_range),
692
+ name="dense",
693
+ )
694
+
695
+ if isinstance(config.hidden_act, str):
696
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
697
+ else:
698
+ self.transform_act_fn = config.hidden_act
699
+
700
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
701
+ self.config = config
702
+
703
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
704
+ hidden_states = self.dense(inputs=hidden_states)
705
+ hidden_states = self.transform_act_fn(hidden_states)
706
+ hidden_states = self.LayerNorm(inputs=hidden_states)
707
+
708
+ return hidden_states
709
+
710
+ def build(self, input_shape=None):
711
+ if self.built:
712
+ return
713
+ self.built = True
714
+ if getattr(self, "dense", None) is not None:
715
+ with tf.name_scope(self.dense.name):
716
+ self.dense.build([None, None, self.config.hidden_size])
717
+ if getattr(self, "LayerNorm", None) is not None:
718
+ with tf.name_scope(self.LayerNorm.name):
719
+ self.LayerNorm.build([None, None, self.config.hidden_size])
720
+
721
+
722
+ class TFBertLMPredictionHead(keras.layers.Layer):
723
+ def __init__(self, config: BertConfig, input_embeddings: keras.layers.Layer, **kwargs):
724
+ super().__init__(**kwargs)
725
+
726
+ self.config = config
727
+ self.hidden_size = config.hidden_size
728
+
729
+ self.transform = TFBertPredictionHeadTransform(config, name="transform")
730
+
731
+ # The output weights are the same as the input embeddings, but there is
732
+ # an output-only bias for each token.
733
+ self.input_embeddings = input_embeddings
734
+
735
+ def build(self, input_shape=None):
736
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
737
+
738
+ if self.built:
739
+ return
740
+ self.built = True
741
+ if getattr(self, "transform", None) is not None:
742
+ with tf.name_scope(self.transform.name):
743
+ self.transform.build(None)
744
+
745
+ def get_output_embeddings(self) -> keras.layers.Layer:
746
+ return self.input_embeddings
747
+
748
+ def set_output_embeddings(self, value: tf.Variable):
749
+ self.input_embeddings.weight = value
750
+ self.input_embeddings.vocab_size = shape_list(value)[0]
751
+
752
+ def get_bias(self) -> Dict[str, tf.Variable]:
753
+ return {"bias": self.bias}
754
+
755
+ def set_bias(self, value: tf.Variable):
756
+ self.bias = value["bias"]
757
+ self.config.vocab_size = shape_list(value["bias"])[0]
758
+
759
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
760
+ hidden_states = self.transform(hidden_states=hidden_states)
761
+ seq_length = shape_list(hidden_states)[1]
762
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
763
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
764
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
765
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
766
+
767
+ return hidden_states
768
+
769
+
770
+ class TFBertMLMHead(keras.layers.Layer):
771
+ def __init__(self, config: BertConfig, input_embeddings: keras.layers.Layer, **kwargs):
772
+ super().__init__(**kwargs)
773
+
774
+ self.predictions = TFBertLMPredictionHead(config, input_embeddings, name="predictions")
775
+
776
+ def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
777
+ prediction_scores = self.predictions(hidden_states=sequence_output)
778
+
779
+ return prediction_scores
780
+
781
+ def build(self, input_shape=None):
782
+ if self.built:
783
+ return
784
+ self.built = True
785
+ if getattr(self, "predictions", None) is not None:
786
+ with tf.name_scope(self.predictions.name):
787
+ self.predictions.build(None)
788
+
789
+
790
+ class TFBertNSPHead(keras.layers.Layer):
791
+ def __init__(self, config: BertConfig, **kwargs):
792
+ super().__init__(**kwargs)
793
+
794
+ self.seq_relationship = keras.layers.Dense(
795
+ units=2,
796
+ kernel_initializer=get_initializer(config.initializer_range),
797
+ name="seq_relationship",
798
+ )
799
+ self.config = config
800
+
801
+ def call(self, pooled_output: tf.Tensor) -> tf.Tensor:
802
+ seq_relationship_score = self.seq_relationship(inputs=pooled_output)
803
+
804
+ return seq_relationship_score
805
+
806
+ def build(self, input_shape=None):
807
+ if self.built:
808
+ return
809
+ self.built = True
810
+ if getattr(self, "seq_relationship", None) is not None:
811
+ with tf.name_scope(self.seq_relationship.name):
812
+ self.seq_relationship.build([None, None, self.config.hidden_size])
813
+
814
+
815
+ @keras_serializable
816
+ class TFBertMainLayer(keras.layers.Layer):
817
+ config_class = BertConfig
818
+
819
+ def __init__(self, config: BertConfig, add_pooling_layer: bool = True, **kwargs):
820
+ super().__init__(**kwargs)
821
+
822
+ self.config = config
823
+ self.is_decoder = config.is_decoder
824
+
825
+ self.embeddings = TFBertEmbeddings(config, name="embeddings")
826
+ self.encoder = TFBertEncoder(config, name="encoder")
827
+ self.pooler = TFBertPooler(config, name="pooler") if add_pooling_layer else None
828
+
829
+ def get_input_embeddings(self) -> keras.layers.Layer:
830
+ return self.embeddings
831
+
832
+ def set_input_embeddings(self, value: tf.Variable):
833
+ self.embeddings.weight = value
834
+ self.embeddings.vocab_size = shape_list(value)[0]
835
+
836
+ def _prune_heads(self, heads_to_prune):
837
+ """
838
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
839
+ class PreTrainedModel
840
+ """
841
+ raise NotImplementedError
842
+
843
+ @unpack_inputs
844
+ def call(
845
+ self,
846
+ input_ids: TFModelInputType | None = None,
847
+ attention_mask: np.ndarray | tf.Tensor | None = None,
848
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
849
+ position_ids: np.ndarray | tf.Tensor | None = None,
850
+ head_mask: np.ndarray | tf.Tensor | None = None,
851
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
852
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
853
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
854
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
855
+ use_cache: Optional[bool] = None,
856
+ output_attentions: Optional[bool] = None,
857
+ output_hidden_states: Optional[bool] = None,
858
+ return_dict: Optional[bool] = None,
859
+ training: bool = False,
860
+ ) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
861
+ if not self.config.is_decoder:
862
+ use_cache = False
863
+
864
+ if input_ids is not None and inputs_embeds is not None:
865
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
866
+ elif input_ids is not None:
867
+ input_shape = shape_list(input_ids)
868
+ elif inputs_embeds is not None:
869
+ input_shape = shape_list(inputs_embeds)[:-1]
870
+ else:
871
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
872
+
873
+ batch_size, seq_length = input_shape
874
+
875
+ if past_key_values is None:
876
+ past_key_values_length = 0
877
+ past_key_values = [None] * len(self.encoder.layer)
878
+ else:
879
+ past_key_values_length = shape_list(past_key_values[0][0])[-2]
880
+
881
+ if attention_mask is None:
882
+ attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
883
+
884
+ if token_type_ids is None:
885
+ token_type_ids = tf.fill(dims=input_shape, value=0)
886
+
887
+ embedding_output = self.embeddings(
888
+ input_ids=input_ids,
889
+ position_ids=position_ids,
890
+ token_type_ids=token_type_ids,
891
+ inputs_embeds=inputs_embeds,
892
+ past_key_values_length=past_key_values_length,
893
+ training=training,
894
+ )
895
+
896
+ # We create a 3D attention mask from a 2D tensor mask.
897
+ # Sizes are [batch_size, 1, 1, to_seq_length]
898
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
899
+ # this attention mask is more simple than the triangular masking of causal attention
900
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
901
+ attention_mask_shape = shape_list(attention_mask)
902
+
903
+ mask_seq_length = seq_length + past_key_values_length
904
+ # Copied from `modeling_tf_t5.py`
905
+ # Provided a padding mask of dimensions [batch_size, mask_seq_length]
906
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
907
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
908
+ if self.is_decoder:
909
+ seq_ids = tf.range(mask_seq_length)
910
+ causal_mask = tf.less_equal(
911
+ tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
912
+ seq_ids[None, :, None],
913
+ )
914
+ causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
915
+ extended_attention_mask = causal_mask * attention_mask[:, None, :]
916
+ attention_mask_shape = shape_list(extended_attention_mask)
917
+ extended_attention_mask = tf.reshape(
918
+ extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
919
+ )
920
+ if past_key_values[0] is not None:
921
+ # attention_mask needs to be sliced to the shape `[batch_size, 1, from_seq_length - cached_seq_length, to_seq_length]
922
+ extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
923
+ else:
924
+ extended_attention_mask = tf.reshape(
925
+ attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
926
+ )
927
+
928
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
929
+ # masked positions, this operation will create a tensor which is 0.0 for
930
+ # positions we want to attend and -10000.0 for masked positions.
931
+ # Since we are adding it to the raw scores before the softmax, this is
932
+ # effectively the same as removing these entirely.
933
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
934
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
935
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
936
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
937
+
938
+ # Copied from `modeling_tf_t5.py` with -1e9 -> -10000
939
+ if self.is_decoder and encoder_attention_mask is not None:
940
+ # If a 2D ou 3D attention mask is provided for the cross-attention
941
+ # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
942
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
943
+ encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
944
+ num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
945
+ if num_dims_encoder_attention_mask == 3:
946
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
947
+ if num_dims_encoder_attention_mask == 2:
948
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
949
+
950
+ # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
951
+ # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
952
+ # encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
953
+ # tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
954
+
955
+ encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
956
+ else:
957
+ encoder_extended_attention_mask = None
958
+
959
+ # Prepare head mask if needed
960
+ # 1.0 in head_mask indicate we keep the head
961
+ # attention_probs has shape bsz x n_heads x N x N
962
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
963
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
964
+ if head_mask is not None:
965
+ raise NotImplementedError
966
+ else:
967
+ head_mask = [None] * self.config.num_hidden_layers
968
+
969
+ encoder_outputs = self.encoder(
970
+ hidden_states=embedding_output,
971
+ attention_mask=extended_attention_mask,
972
+ head_mask=head_mask,
973
+ encoder_hidden_states=encoder_hidden_states,
974
+ encoder_attention_mask=encoder_extended_attention_mask,
975
+ past_key_values=past_key_values,
976
+ use_cache=use_cache,
977
+ output_attentions=output_attentions,
978
+ output_hidden_states=output_hidden_states,
979
+ return_dict=return_dict,
980
+ training=training,
981
+ )
982
+
983
+ sequence_output = encoder_outputs[0]
984
+ pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
985
+
986
+ if not return_dict:
987
+ return (
988
+ sequence_output,
989
+ pooled_output,
990
+ ) + encoder_outputs[1:]
991
+
992
+ return TFBaseModelOutputWithPoolingAndCrossAttentions(
993
+ last_hidden_state=sequence_output,
994
+ pooler_output=pooled_output,
995
+ past_key_values=encoder_outputs.past_key_values,
996
+ hidden_states=encoder_outputs.hidden_states,
997
+ attentions=encoder_outputs.attentions,
998
+ cross_attentions=encoder_outputs.cross_attentions,
999
+ )
1000
+
1001
+ def build(self, input_shape=None):
1002
+ if self.built:
1003
+ return
1004
+ self.built = True
1005
+ if getattr(self, "embeddings", None) is not None:
1006
+ with tf.name_scope(self.embeddings.name):
1007
+ self.embeddings.build(None)
1008
+ if getattr(self, "encoder", None) is not None:
1009
+ with tf.name_scope(self.encoder.name):
1010
+ self.encoder.build(None)
1011
+ if getattr(self, "pooler", None) is not None:
1012
+ with tf.name_scope(self.pooler.name):
1013
+ self.pooler.build(None)
1014
+
1015
+
1016
+ class TFBertPreTrainedModel(TFPreTrainedModel):
1017
+ """
1018
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1019
+ models.
1020
+ """
1021
+
1022
+ config_class = BertConfig
1023
+ base_model_prefix = "bert"
1024
+
1025
+
1026
+ @dataclass
1027
+ class TFBertForPreTrainingOutput(ModelOutput):
1028
+ """
1029
+ Output type of [`TFBertForPreTraining`].
1030
+
1031
+ Args:
1032
+ prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1033
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1034
+ seq_relationship_logits (`tf.Tensor` of shape `(batch_size, 2)`):
1035
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
1036
+ before SoftMax).
1037
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1038
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
1039
+ `(batch_size, sequence_length, hidden_size)`.
1040
+
1041
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
1042
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1043
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1044
+ sequence_length)`.
1045
+
1046
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1047
+ heads.
1048
+ """
1049
+
1050
+ loss: tf.Tensor | None = None
1051
+ prediction_logits: Optional[tf.Tensor] = None
1052
+ seq_relationship_logits: Optional[tf.Tensor] = None
1053
+ hidden_states: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None
1054
+ attentions: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None
1055
+
1056
+
1057
+ BERT_START_DOCSTRING = r"""
1058
+
1059
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
1060
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1061
+ etc.)
1062
+
1063
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
1064
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
1065
+ behavior.
1066
+
1067
+ <Tip>
1068
+
1069
+ TensorFlow models and layers in `transformers` accept two formats as input:
1070
+
1071
+ - having all inputs as keyword arguments (like PyTorch models), or
1072
+ - having all inputs as a list, tuple or dict in the first positional argument.
1073
+
1074
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
1075
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
1076
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
1077
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
1078
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
1079
+ positional argument:
1080
+
1081
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
1082
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
1083
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
1084
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
1085
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
1086
+
1087
+ Note that when creating models and layers with
1088
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
1089
+ about any of this, as you can just pass inputs like you would to any other Python function!
1090
+
1091
+ </Tip>
1092
+
1093
+ Args:
1094
+ config ([`BertConfig`]): Model configuration class with all the parameters of the model.
1095
+ Initializing with a config file does not load the weights associated with the model, only the
1096
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
1097
+ """
1098
+
1099
+ BERT_INPUTS_DOCSTRING = r"""
1100
+ Args:
1101
+ input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
1102
+ Indices of input sequence tokens in the vocabulary.
1103
+
1104
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1105
+ [`PreTrainedTokenizer.encode`] for details.
1106
+
1107
+ [What are input IDs?](../glossary#input-ids)
1108
+ attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
1109
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1110
+
1111
+ - 1 for tokens that are **not masked**,
1112
+ - 0 for tokens that are **masked**.
1113
+
1114
+ [What are attention masks?](../glossary#attention-mask)
1115
+ token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
1116
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1117
+ 1]`:
1118
+
1119
+ - 0 corresponds to a *sentence A* token,
1120
+ - 1 corresponds to a *sentence B* token.
1121
+
1122
+ [What are token type IDs?](../glossary#token-type-ids)
1123
+ position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
1124
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1125
+ config.max_position_embeddings - 1]`.
1126
+
1127
+ [What are position IDs?](../glossary#position-ids)
1128
+ head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1129
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1130
+
1131
+ - 1 indicates the head is **not masked**,
1132
+ - 0 indicates the head is **masked**.
1133
+
1134
+ inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
1135
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1136
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1137
+ model's internal embedding lookup matrix.
1138
+ output_attentions (`bool`, *optional*):
1139
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1140
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1141
+ config will be used instead.
1142
+ output_hidden_states (`bool`, *optional*):
1143
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1144
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1145
+ used instead.
1146
+ return_dict (`bool`, *optional*):
1147
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1148
+ eager mode, in graph mode the value will always be set to True.
1149
+ training (`bool`, *optional*, defaults to `False``):
1150
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1151
+ behaviors between training and evaluation).
1152
+ """
1153
+
1154
+
1155
+ @add_start_docstrings(
1156
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
1157
+ BERT_START_DOCSTRING,
1158
+ )
1159
+ class TFBertModel(TFBertPreTrainedModel):
1160
+ def __init__(self, config: BertConfig, add_pooling_layer: bool = True, *inputs, **kwargs):
1161
+ super().__init__(config, *inputs, **kwargs)
1162
+
1163
+ self.bert = TFBertMainLayer(config, add_pooling_layer, name="bert")
1164
+
1165
+ @unpack_inputs
1166
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1167
+ @add_code_sample_docstrings(
1168
+ checkpoint=_CHECKPOINT_FOR_DOC,
1169
+ output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,
1170
+ config_class=_CONFIG_FOR_DOC,
1171
+ )
1172
+ def call(
1173
+ self,
1174
+ input_ids: TFModelInputType | None = None,
1175
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1176
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1177
+ position_ids: np.ndarray | tf.Tensor | None = None,
1178
+ head_mask: np.ndarray | tf.Tensor | None = None,
1179
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1180
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
1181
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1182
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1183
+ use_cache: Optional[bool] = None,
1184
+ output_attentions: Optional[bool] = None,
1185
+ output_hidden_states: Optional[bool] = None,
1186
+ return_dict: Optional[bool] = None,
1187
+ training: Optional[bool] = False,
1188
+ ) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
1189
+ r"""
1190
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1191
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1192
+ the model is configured as a decoder.
1193
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1194
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1195
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1196
+
1197
+ - 1 for tokens that are **not masked**,
1198
+ - 0 for tokens that are **masked**.
1199
+
1200
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
1201
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1202
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1203
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1204
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1205
+ use_cache (`bool`, *optional*, defaults to `True`):
1206
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1207
+ `past_key_values`). Set to `False` during training, `True` during generation
1208
+ """
1209
+ outputs = self.bert(
1210
+ input_ids=input_ids,
1211
+ attention_mask=attention_mask,
1212
+ token_type_ids=token_type_ids,
1213
+ position_ids=position_ids,
1214
+ head_mask=head_mask,
1215
+ inputs_embeds=inputs_embeds,
1216
+ encoder_hidden_states=encoder_hidden_states,
1217
+ encoder_attention_mask=encoder_attention_mask,
1218
+ past_key_values=past_key_values,
1219
+ use_cache=use_cache,
1220
+ output_attentions=output_attentions,
1221
+ output_hidden_states=output_hidden_states,
1222
+ return_dict=return_dict,
1223
+ training=training,
1224
+ )
1225
+ return outputs
1226
+
1227
+ def build(self, input_shape=None):
1228
+ if self.built:
1229
+ return
1230
+ self.built = True
1231
+ if getattr(self, "bert", None) is not None:
1232
+ with tf.name_scope(self.bert.name):
1233
+ self.bert.build(None)
1234
+
1235
+
1236
+ @add_start_docstrings(
1237
+ """
1238
+ Bert Model with two heads on top as done during the pretraining:
1239
+ a `masked language modeling` head and a `next sentence prediction (classification)` head.
1240
+ """,
1241
+ BERT_START_DOCSTRING,
1242
+ )
1243
+ class TFBertForPreTraining(TFBertPreTrainedModel, TFBertPreTrainingLoss):
1244
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1245
+ _keys_to_ignore_on_load_unexpected = [
1246
+ r"position_ids",
1247
+ r"cls.predictions.decoder.weight",
1248
+ r"cls.predictions.decoder.bias",
1249
+ ]
1250
+
1251
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1252
+ super().__init__(config, *inputs, **kwargs)
1253
+
1254
+ self.bert = TFBertMainLayer(config, name="bert")
1255
+ self.nsp = TFBertNSPHead(config, name="nsp___cls")
1256
+ self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
1257
+
1258
+ def get_lm_head(self) -> keras.layers.Layer:
1259
+ return self.mlm.predictions
1260
+
1261
+ def get_prefix_bias_name(self) -> str:
1262
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1263
+ return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
1264
+
1265
+ @unpack_inputs
1266
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1267
+ @replace_return_docstrings(output_type=TFBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1268
+ def call(
1269
+ self,
1270
+ input_ids: TFModelInputType | None = None,
1271
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1272
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1273
+ position_ids: np.ndarray | tf.Tensor | None = None,
1274
+ head_mask: np.ndarray | tf.Tensor | None = None,
1275
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1276
+ output_attentions: Optional[bool] = None,
1277
+ output_hidden_states: Optional[bool] = None,
1278
+ return_dict: Optional[bool] = None,
1279
+ labels: np.ndarray | tf.Tensor | None = None,
1280
+ next_sentence_label: np.ndarray | tf.Tensor | None = None,
1281
+ training: Optional[bool] = False,
1282
+ ) -> Union[TFBertForPreTrainingOutput, Tuple[tf.Tensor]]:
1283
+ r"""
1284
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1285
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1286
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1287
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1288
+ next_sentence_label (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1289
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1290
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
1291
+
1292
+ - 0 indicates sequence B is a continuation of sequence A,
1293
+ - 1 indicates sequence B is a random sequence.
1294
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
1295
+ Used to hide legacy arguments that have been deprecated.
1296
+
1297
+ Return:
1298
+
1299
+ Examples:
1300
+
1301
+ ```python
1302
+ >>> import tensorflow as tf
1303
+ >>> from transformers import AutoTokenizer, TFBertForPreTraining
1304
+
1305
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1306
+ >>> model = TFBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
1307
+ >>> input_ids = tokenizer("Hello, my dog is cute", add_special_tokens=True, return_tensors="tf")
1308
+ >>> # Batch size 1
1309
+
1310
+ >>> outputs = model(input_ids)
1311
+ >>> prediction_logits, seq_relationship_logits = outputs[:2]
1312
+ ```"""
1313
+ outputs = self.bert(
1314
+ input_ids=input_ids,
1315
+ attention_mask=attention_mask,
1316
+ token_type_ids=token_type_ids,
1317
+ position_ids=position_ids,
1318
+ head_mask=head_mask,
1319
+ inputs_embeds=inputs_embeds,
1320
+ output_attentions=output_attentions,
1321
+ output_hidden_states=output_hidden_states,
1322
+ return_dict=return_dict,
1323
+ training=training,
1324
+ )
1325
+ sequence_output, pooled_output = outputs[:2]
1326
+ prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
1327
+ seq_relationship_score = self.nsp(pooled_output=pooled_output)
1328
+ total_loss = None
1329
+
1330
+ if labels is not None and next_sentence_label is not None:
1331
+ d_labels = {"labels": labels}
1332
+ d_labels["next_sentence_label"] = next_sentence_label
1333
+ total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, seq_relationship_score))
1334
+
1335
+ if not return_dict:
1336
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1337
+ return ((total_loss,) + output) if total_loss is not None else output
1338
+
1339
+ return TFBertForPreTrainingOutput(
1340
+ loss=total_loss,
1341
+ prediction_logits=prediction_scores,
1342
+ seq_relationship_logits=seq_relationship_score,
1343
+ hidden_states=outputs.hidden_states,
1344
+ attentions=outputs.attentions,
1345
+ )
1346
+
1347
+ def build(self, input_shape=None):
1348
+ if self.built:
1349
+ return
1350
+ self.built = True
1351
+ if getattr(self, "bert", None) is not None:
1352
+ with tf.name_scope(self.bert.name):
1353
+ self.bert.build(None)
1354
+ if getattr(self, "nsp", None) is not None:
1355
+ with tf.name_scope(self.nsp.name):
1356
+ self.nsp.build(None)
1357
+ if getattr(self, "mlm", None) is not None:
1358
+ with tf.name_scope(self.mlm.name):
1359
+ self.mlm.build(None)
1360
+
1361
+
1362
+ @add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
1363
+ class TFBertForMaskedLM(TFBertPreTrainedModel, TFMaskedLanguageModelingLoss):
1364
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1365
+ _keys_to_ignore_on_load_unexpected = [
1366
+ r"pooler",
1367
+ r"cls.seq_relationship",
1368
+ r"cls.predictions.decoder.weight",
1369
+ r"nsp___cls",
1370
+ ]
1371
+
1372
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1373
+ super().__init__(config, *inputs, **kwargs)
1374
+
1375
+ if config.is_decoder:
1376
+ logger.warning(
1377
+ "If you want to use `TFBertForMaskedLM` make sure `config.is_decoder=False` for "
1378
+ "bi-directional self-attention."
1379
+ )
1380
+
1381
+ self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
1382
+ self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
1383
+
1384
+ def get_lm_head(self) -> keras.layers.Layer:
1385
+ return self.mlm.predictions
1386
+
1387
+ def get_prefix_bias_name(self) -> str:
1388
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1389
+ return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
1390
+
1391
+ @unpack_inputs
1392
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1393
+ @add_code_sample_docstrings(
1394
+ checkpoint=_CHECKPOINT_FOR_DOC,
1395
+ output_type=TFMaskedLMOutput,
1396
+ config_class=_CONFIG_FOR_DOC,
1397
+ expected_output="'paris'",
1398
+ expected_loss=0.88,
1399
+ )
1400
+ def call(
1401
+ self,
1402
+ input_ids: TFModelInputType | None = None,
1403
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1404
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1405
+ position_ids: np.ndarray | tf.Tensor | None = None,
1406
+ head_mask: np.ndarray | tf.Tensor | None = None,
1407
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1408
+ output_attentions: Optional[bool] = None,
1409
+ output_hidden_states: Optional[bool] = None,
1410
+ return_dict: Optional[bool] = None,
1411
+ labels: np.ndarray | tf.Tensor | None = None,
1412
+ training: Optional[bool] = False,
1413
+ ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
1414
+ r"""
1415
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
1416
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1417
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1418
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1419
+ """
1420
+ outputs = self.bert(
1421
+ input_ids=input_ids,
1422
+ attention_mask=attention_mask,
1423
+ token_type_ids=token_type_ids,
1424
+ position_ids=position_ids,
1425
+ head_mask=head_mask,
1426
+ inputs_embeds=inputs_embeds,
1427
+ output_attentions=output_attentions,
1428
+ output_hidden_states=output_hidden_states,
1429
+ return_dict=return_dict,
1430
+ training=training,
1431
+ )
1432
+ sequence_output = outputs[0]
1433
+ prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
1434
+ loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
1435
+
1436
+ if not return_dict:
1437
+ output = (prediction_scores,) + outputs[2:]
1438
+ return ((loss,) + output) if loss is not None else output
1439
+
1440
+ return TFMaskedLMOutput(
1441
+ loss=loss,
1442
+ logits=prediction_scores,
1443
+ hidden_states=outputs.hidden_states,
1444
+ attentions=outputs.attentions,
1445
+ )
1446
+
1447
+ def build(self, input_shape=None):
1448
+ if self.built:
1449
+ return
1450
+ self.built = True
1451
+ if getattr(self, "bert", None) is not None:
1452
+ with tf.name_scope(self.bert.name):
1453
+ self.bert.build(None)
1454
+ if getattr(self, "mlm", None) is not None:
1455
+ with tf.name_scope(self.mlm.name):
1456
+ self.mlm.build(None)
1457
+
1458
+
1459
+ class TFBertLMHeadModel(TFBertPreTrainedModel, TFCausalLanguageModelingLoss):
1460
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1461
+ _keys_to_ignore_on_load_unexpected = [
1462
+ r"pooler",
1463
+ r"cls.seq_relationship",
1464
+ r"cls.predictions.decoder.weight",
1465
+ r"nsp___cls",
1466
+ ]
1467
+
1468
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1469
+ super().__init__(config, *inputs, **kwargs)
1470
+
1471
+ if not config.is_decoder:
1472
+ logger.warning("If you want to use `TFBertLMHeadModel` as a standalone, add `is_decoder=True.`")
1473
+
1474
+ self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
1475
+ self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
1476
+
1477
+ def get_lm_head(self) -> keras.layers.Layer:
1478
+ return self.mlm.predictions
1479
+
1480
+ def get_prefix_bias_name(self) -> str:
1481
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1482
+ return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
1483
+
1484
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
1485
+ input_shape = input_ids.shape
1486
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1487
+ if attention_mask is None:
1488
+ attention_mask = tf.ones(input_shape)
1489
+
1490
+ # cut decoder_input_ids if past is used
1491
+ if past_key_values is not None:
1492
+ input_ids = input_ids[:, -1:]
1493
+
1494
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
1495
+
1496
+ @unpack_inputs
1497
+ @add_code_sample_docstrings(
1498
+ checkpoint=_CHECKPOINT_FOR_DOC,
1499
+ output_type=TFCausalLMOutputWithCrossAttentions,
1500
+ config_class=_CONFIG_FOR_DOC,
1501
+ )
1502
+ def call(
1503
+ self,
1504
+ input_ids: TFModelInputType | None = None,
1505
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1506
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1507
+ position_ids: np.ndarray | tf.Tensor | None = None,
1508
+ head_mask: np.ndarray | tf.Tensor | None = None,
1509
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1510
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
1511
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1512
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1513
+ use_cache: Optional[bool] = None,
1514
+ output_attentions: Optional[bool] = None,
1515
+ output_hidden_states: Optional[bool] = None,
1516
+ return_dict: Optional[bool] = None,
1517
+ labels: np.ndarray | tf.Tensor | None = None,
1518
+ training: Optional[bool] = False,
1519
+ **kwargs,
1520
+ ) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:
1521
+ r"""
1522
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1523
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1524
+ the model is configured as a decoder.
1525
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1526
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1527
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1528
+
1529
+ - 1 for tokens that are **not masked**,
1530
+ - 0 for tokens that are **masked**.
1531
+
1532
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
1533
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1534
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1535
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1536
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1537
+ use_cache (`bool`, *optional*, defaults to `True`):
1538
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1539
+ `past_key_values`). Set to `False` during training, `True` during generation
1540
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
1541
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
1542
+ config.vocab_size - 1]`.
1543
+ """
1544
+ outputs = self.bert(
1545
+ input_ids=input_ids,
1546
+ attention_mask=attention_mask,
1547
+ token_type_ids=token_type_ids,
1548
+ position_ids=position_ids,
1549
+ head_mask=head_mask,
1550
+ inputs_embeds=inputs_embeds,
1551
+ encoder_hidden_states=encoder_hidden_states,
1552
+ encoder_attention_mask=encoder_attention_mask,
1553
+ past_key_values=past_key_values,
1554
+ use_cache=use_cache,
1555
+ output_attentions=output_attentions,
1556
+ output_hidden_states=output_hidden_states,
1557
+ return_dict=return_dict,
1558
+ training=training,
1559
+ )
1560
+ sequence_output = outputs[0]
1561
+ logits = self.mlm(sequence_output=sequence_output, training=training)
1562
+ loss = None
1563
+
1564
+ if labels is not None:
1565
+ # shift labels to the left and cut last logit token
1566
+ shifted_logits = logits[:, :-1]
1567
+ labels = labels[:, 1:]
1568
+ loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)
1569
+
1570
+ if not return_dict:
1571
+ output = (logits,) + outputs[2:]
1572
+ return ((loss,) + output) if loss is not None else output
1573
+
1574
+ return TFCausalLMOutputWithCrossAttentions(
1575
+ loss=loss,
1576
+ logits=logits,
1577
+ past_key_values=outputs.past_key_values,
1578
+ hidden_states=outputs.hidden_states,
1579
+ attentions=outputs.attentions,
1580
+ cross_attentions=outputs.cross_attentions,
1581
+ )
1582
+
1583
+ def build(self, input_shape=None):
1584
+ if self.built:
1585
+ return
1586
+ self.built = True
1587
+ if getattr(self, "bert", None) is not None:
1588
+ with tf.name_scope(self.bert.name):
1589
+ self.bert.build(None)
1590
+ if getattr(self, "mlm", None) is not None:
1591
+ with tf.name_scope(self.mlm.name):
1592
+ self.mlm.build(None)
1593
+
1594
+
1595
+ @add_start_docstrings(
1596
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1597
+ BERT_START_DOCSTRING,
1598
+ )
1599
+ class TFBertForNextSentencePrediction(TFBertPreTrainedModel, TFNextSentencePredictionLoss):
1600
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1601
+ _keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"cls.predictions"]
1602
+
1603
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1604
+ super().__init__(config, *inputs, **kwargs)
1605
+
1606
+ self.bert = TFBertMainLayer(config, name="bert")
1607
+ self.nsp = TFBertNSPHead(config, name="nsp___cls")
1608
+
1609
+ @unpack_inputs
1610
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1611
+ @replace_return_docstrings(output_type=TFNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1612
+ def call(
1613
+ self,
1614
+ input_ids: TFModelInputType | None = None,
1615
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1616
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1617
+ position_ids: np.ndarray | tf.Tensor | None = None,
1618
+ head_mask: np.ndarray | tf.Tensor | None = None,
1619
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1620
+ output_attentions: Optional[bool] = None,
1621
+ output_hidden_states: Optional[bool] = None,
1622
+ return_dict: Optional[bool] = None,
1623
+ next_sentence_label: np.ndarray | tf.Tensor | None = None,
1624
+ training: Optional[bool] = False,
1625
+ ) -> Union[TFNextSentencePredictorOutput, Tuple[tf.Tensor]]:
1626
+ r"""
1627
+ Return:
1628
+
1629
+ Examples:
1630
+
1631
+ ```python
1632
+ >>> import tensorflow as tf
1633
+ >>> from transformers import AutoTokenizer, TFBertForNextSentencePrediction
1634
+
1635
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1636
+ >>> model = TFBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1637
+
1638
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1639
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1640
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="tf")
1641
+
1642
+ >>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
1643
+ >>> assert logits[0][0] < logits[0][1] # the next sentence was random
1644
+ ```"""
1645
+ outputs = self.bert(
1646
+ input_ids=input_ids,
1647
+ attention_mask=attention_mask,
1648
+ token_type_ids=token_type_ids,
1649
+ position_ids=position_ids,
1650
+ head_mask=head_mask,
1651
+ inputs_embeds=inputs_embeds,
1652
+ output_attentions=output_attentions,
1653
+ output_hidden_states=output_hidden_states,
1654
+ return_dict=return_dict,
1655
+ training=training,
1656
+ )
1657
+ pooled_output = outputs[1]
1658
+ seq_relationship_scores = self.nsp(pooled_output=pooled_output)
1659
+ next_sentence_loss = (
1660
+ None
1661
+ if next_sentence_label is None
1662
+ else self.hf_compute_loss(labels=next_sentence_label, logits=seq_relationship_scores)
1663
+ )
1664
+
1665
+ if not return_dict:
1666
+ output = (seq_relationship_scores,) + outputs[2:]
1667
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1668
+
1669
+ return TFNextSentencePredictorOutput(
1670
+ loss=next_sentence_loss,
1671
+ logits=seq_relationship_scores,
1672
+ hidden_states=outputs.hidden_states,
1673
+ attentions=outputs.attentions,
1674
+ )
1675
+
1676
+ def build(self, input_shape=None):
1677
+ if self.built:
1678
+ return
1679
+ self.built = True
1680
+ if getattr(self, "bert", None) is not None:
1681
+ with tf.name_scope(self.bert.name):
1682
+ self.bert.build(None)
1683
+ if getattr(self, "nsp", None) is not None:
1684
+ with tf.name_scope(self.nsp.name):
1685
+ self.nsp.build(None)
1686
+
1687
+
1688
+ @add_start_docstrings(
1689
+ """
1690
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1691
+ output) e.g. for GLUE tasks.
1692
+ """,
1693
+ BERT_START_DOCSTRING,
1694
+ )
1695
+ class TFBertForSequenceClassification(TFBertPreTrainedModel, TFSequenceClassificationLoss):
1696
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1697
+ _keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
1698
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1699
+
1700
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1701
+ super().__init__(config, *inputs, **kwargs)
1702
+
1703
+ self.num_labels = config.num_labels
1704
+
1705
+ self.bert = TFBertMainLayer(config, name="bert")
1706
+ classifier_dropout = (
1707
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1708
+ )
1709
+ self.dropout = keras.layers.Dropout(rate=classifier_dropout)
1710
+ self.classifier = keras.layers.Dense(
1711
+ units=config.num_labels,
1712
+ kernel_initializer=get_initializer(config.initializer_range),
1713
+ name="classifier",
1714
+ )
1715
+ self.config = config
1716
+
1717
+ @unpack_inputs
1718
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1719
+ @add_code_sample_docstrings(
1720
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1721
+ output_type=TFSequenceClassifierOutput,
1722
+ config_class=_CONFIG_FOR_DOC,
1723
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1724
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1725
+ )
1726
+ def call(
1727
+ self,
1728
+ input_ids: TFModelInputType | None = None,
1729
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1730
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1731
+ position_ids: np.ndarray | tf.Tensor | None = None,
1732
+ head_mask: np.ndarray | tf.Tensor | None = None,
1733
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1734
+ output_attentions: Optional[bool] = None,
1735
+ output_hidden_states: Optional[bool] = None,
1736
+ return_dict: Optional[bool] = None,
1737
+ labels: np.ndarray | tf.Tensor | None = None,
1738
+ training: Optional[bool] = False,
1739
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
1740
+ r"""
1741
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
1742
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1743
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1744
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1745
+ """
1746
+ outputs = self.bert(
1747
+ input_ids=input_ids,
1748
+ attention_mask=attention_mask,
1749
+ token_type_ids=token_type_ids,
1750
+ position_ids=position_ids,
1751
+ head_mask=head_mask,
1752
+ inputs_embeds=inputs_embeds,
1753
+ output_attentions=output_attentions,
1754
+ output_hidden_states=output_hidden_states,
1755
+ return_dict=return_dict,
1756
+ training=training,
1757
+ )
1758
+ pooled_output = outputs[1]
1759
+ pooled_output = self.dropout(inputs=pooled_output, training=training)
1760
+ logits = self.classifier(inputs=pooled_output)
1761
+ loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
1762
+
1763
+ if not return_dict:
1764
+ output = (logits,) + outputs[2:]
1765
+ return ((loss,) + output) if loss is not None else output
1766
+
1767
+ return TFSequenceClassifierOutput(
1768
+ loss=loss,
1769
+ logits=logits,
1770
+ hidden_states=outputs.hidden_states,
1771
+ attentions=outputs.attentions,
1772
+ )
1773
+
1774
+ def build(self, input_shape=None):
1775
+ if self.built:
1776
+ return
1777
+ self.built = True
1778
+ if getattr(self, "bert", None) is not None:
1779
+ with tf.name_scope(self.bert.name):
1780
+ self.bert.build(None)
1781
+ if getattr(self, "classifier", None) is not None:
1782
+ with tf.name_scope(self.classifier.name):
1783
+ self.classifier.build([None, None, self.config.hidden_size])
1784
+
1785
+
1786
+ @add_start_docstrings(
1787
+ """
1788
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1789
+ softmax) e.g. for RocStories/SWAG tasks.
1790
+ """,
1791
+ BERT_START_DOCSTRING,
1792
+ )
1793
+ class TFBertForMultipleChoice(TFBertPreTrainedModel, TFMultipleChoiceLoss):
1794
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1795
+ _keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
1796
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1797
+
1798
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1799
+ super().__init__(config, *inputs, **kwargs)
1800
+
1801
+ self.bert = TFBertMainLayer(config, name="bert")
1802
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
1803
+ self.classifier = keras.layers.Dense(
1804
+ units=1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1805
+ )
1806
+ self.config = config
1807
+
1808
+ @unpack_inputs
1809
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1810
+ @add_code_sample_docstrings(
1811
+ checkpoint=_CHECKPOINT_FOR_DOC,
1812
+ output_type=TFMultipleChoiceModelOutput,
1813
+ config_class=_CONFIG_FOR_DOC,
1814
+ )
1815
+ def call(
1816
+ self,
1817
+ input_ids: TFModelInputType | None = None,
1818
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1819
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1820
+ position_ids: np.ndarray | tf.Tensor | None = None,
1821
+ head_mask: np.ndarray | tf.Tensor | None = None,
1822
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1823
+ output_attentions: Optional[bool] = None,
1824
+ output_hidden_states: Optional[bool] = None,
1825
+ return_dict: Optional[bool] = None,
1826
+ labels: np.ndarray | tf.Tensor | None = None,
1827
+ training: Optional[bool] = False,
1828
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
1829
+ r"""
1830
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
1831
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1832
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1833
+ """
1834
+ if input_ids is not None:
1835
+ num_choices = shape_list(input_ids)[1]
1836
+ seq_length = shape_list(input_ids)[2]
1837
+ else:
1838
+ num_choices = shape_list(inputs_embeds)[1]
1839
+ seq_length = shape_list(inputs_embeds)[2]
1840
+
1841
+ flat_input_ids = tf.reshape(tensor=input_ids, shape=(-1, seq_length)) if input_ids is not None else None
1842
+ flat_attention_mask = (
1843
+ tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None
1844
+ )
1845
+ flat_token_type_ids = (
1846
+ tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None
1847
+ )
1848
+ flat_position_ids = (
1849
+ tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None
1850
+ )
1851
+ flat_inputs_embeds = (
1852
+ tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3]))
1853
+ if inputs_embeds is not None
1854
+ else None
1855
+ )
1856
+ outputs = self.bert(
1857
+ input_ids=flat_input_ids,
1858
+ attention_mask=flat_attention_mask,
1859
+ token_type_ids=flat_token_type_ids,
1860
+ position_ids=flat_position_ids,
1861
+ head_mask=head_mask,
1862
+ inputs_embeds=flat_inputs_embeds,
1863
+ output_attentions=output_attentions,
1864
+ output_hidden_states=output_hidden_states,
1865
+ return_dict=return_dict,
1866
+ training=training,
1867
+ )
1868
+ pooled_output = outputs[1]
1869
+ pooled_output = self.dropout(inputs=pooled_output, training=training)
1870
+ logits = self.classifier(inputs=pooled_output)
1871
+ reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices))
1872
+ loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits)
1873
+
1874
+ if not return_dict:
1875
+ output = (reshaped_logits,) + outputs[2:]
1876
+ return ((loss,) + output) if loss is not None else output
1877
+
1878
+ return TFMultipleChoiceModelOutput(
1879
+ loss=loss,
1880
+ logits=reshaped_logits,
1881
+ hidden_states=outputs.hidden_states,
1882
+ attentions=outputs.attentions,
1883
+ )
1884
+
1885
+ def build(self, input_shape=None):
1886
+ if self.built:
1887
+ return
1888
+ self.built = True
1889
+ if getattr(self, "bert", None) is not None:
1890
+ with tf.name_scope(self.bert.name):
1891
+ self.bert.build(None)
1892
+ if getattr(self, "classifier", None) is not None:
1893
+ with tf.name_scope(self.classifier.name):
1894
+ self.classifier.build([None, None, self.config.hidden_size])
1895
+
1896
+
1897
+ @add_start_docstrings(
1898
+ """
1899
+ Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1900
+ Named-Entity-Recognition (NER) tasks.
1901
+ """,
1902
+ BERT_START_DOCSTRING,
1903
+ )
1904
+ class TFBertForTokenClassification(TFBertPreTrainedModel, TFTokenClassificationLoss):
1905
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1906
+ _keys_to_ignore_on_load_unexpected = [
1907
+ r"pooler",
1908
+ r"mlm___cls",
1909
+ r"nsp___cls",
1910
+ r"cls.predictions",
1911
+ r"cls.seq_relationship",
1912
+ ]
1913
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1914
+
1915
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
1916
+ super().__init__(config, *inputs, **kwargs)
1917
+
1918
+ self.num_labels = config.num_labels
1919
+
1920
+ self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
1921
+ classifier_dropout = (
1922
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1923
+ )
1924
+ self.dropout = keras.layers.Dropout(rate=classifier_dropout)
1925
+ self.classifier = keras.layers.Dense(
1926
+ units=config.num_labels,
1927
+ kernel_initializer=get_initializer(config.initializer_range),
1928
+ name="classifier",
1929
+ )
1930
+ self.config = config
1931
+
1932
+ @unpack_inputs
1933
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1934
+ @add_code_sample_docstrings(
1935
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1936
+ output_type=TFTokenClassifierOutput,
1937
+ config_class=_CONFIG_FOR_DOC,
1938
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1939
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1940
+ )
1941
+ def call(
1942
+ self,
1943
+ input_ids: TFModelInputType | None = None,
1944
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1945
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1946
+ position_ids: np.ndarray | tf.Tensor | None = None,
1947
+ head_mask: np.ndarray | tf.Tensor | None = None,
1948
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1949
+ output_attentions: Optional[bool] = None,
1950
+ output_hidden_states: Optional[bool] = None,
1951
+ return_dict: Optional[bool] = None,
1952
+ labels: np.ndarray | tf.Tensor | None = None,
1953
+ training: Optional[bool] = False,
1954
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
1955
+ r"""
1956
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
1957
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1958
+ """
1959
+ outputs = self.bert(
1960
+ input_ids=input_ids,
1961
+ attention_mask=attention_mask,
1962
+ token_type_ids=token_type_ids,
1963
+ position_ids=position_ids,
1964
+ head_mask=head_mask,
1965
+ inputs_embeds=inputs_embeds,
1966
+ output_attentions=output_attentions,
1967
+ output_hidden_states=output_hidden_states,
1968
+ return_dict=return_dict,
1969
+ training=training,
1970
+ )
1971
+ sequence_output = outputs[0]
1972
+ sequence_output = self.dropout(inputs=sequence_output, training=training)
1973
+ logits = self.classifier(inputs=sequence_output)
1974
+ loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
1975
+
1976
+ if not return_dict:
1977
+ output = (logits,) + outputs[2:]
1978
+ return ((loss,) + output) if loss is not None else output
1979
+
1980
+ return TFTokenClassifierOutput(
1981
+ loss=loss,
1982
+ logits=logits,
1983
+ hidden_states=outputs.hidden_states,
1984
+ attentions=outputs.attentions,
1985
+ )
1986
+
1987
+ def build(self, input_shape=None):
1988
+ if self.built:
1989
+ return
1990
+ self.built = True
1991
+ if getattr(self, "bert", None) is not None:
1992
+ with tf.name_scope(self.bert.name):
1993
+ self.bert.build(None)
1994
+ if getattr(self, "classifier", None) is not None:
1995
+ with tf.name_scope(self.classifier.name):
1996
+ self.classifier.build([None, None, self.config.hidden_size])
1997
+
1998
+
1999
+ @add_start_docstrings(
2000
+ """
2001
+ Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
2002
+ layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
2003
+ """,
2004
+ BERT_START_DOCSTRING,
2005
+ )
2006
+ class TFBertForQuestionAnswering(TFBertPreTrainedModel, TFQuestionAnsweringLoss):
2007
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
2008
+ _keys_to_ignore_on_load_unexpected = [
2009
+ r"pooler",
2010
+ r"mlm___cls",
2011
+ r"nsp___cls",
2012
+ r"cls.predictions",
2013
+ r"cls.seq_relationship",
2014
+ ]
2015
+
2016
+ def __init__(self, config: BertConfig, *inputs, **kwargs):
2017
+ super().__init__(config, *inputs, **kwargs)
2018
+
2019
+ self.num_labels = config.num_labels
2020
+
2021
+ self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
2022
+ self.qa_outputs = keras.layers.Dense(
2023
+ units=config.num_labels,
2024
+ kernel_initializer=get_initializer(config.initializer_range),
2025
+ name="qa_outputs",
2026
+ )
2027
+ self.config = config
2028
+
2029
+ @unpack_inputs
2030
+ @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
2031
+ @add_code_sample_docstrings(
2032
+ checkpoint=_CHECKPOINT_FOR_QA,
2033
+ output_type=TFQuestionAnsweringModelOutput,
2034
+ config_class=_CONFIG_FOR_DOC,
2035
+ qa_target_start_index=_QA_TARGET_START_INDEX,
2036
+ qa_target_end_index=_QA_TARGET_END_INDEX,
2037
+ expected_output=_QA_EXPECTED_OUTPUT,
2038
+ expected_loss=_QA_EXPECTED_LOSS,
2039
+ )
2040
+ def call(
2041
+ self,
2042
+ input_ids: TFModelInputType | None = None,
2043
+ attention_mask: np.ndarray | tf.Tensor | None = None,
2044
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
2045
+ position_ids: np.ndarray | tf.Tensor | None = None,
2046
+ head_mask: np.ndarray | tf.Tensor | None = None,
2047
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
2048
+ output_attentions: Optional[bool] = None,
2049
+ output_hidden_states: Optional[bool] = None,
2050
+ return_dict: Optional[bool] = None,
2051
+ start_positions: np.ndarray | tf.Tensor | None = None,
2052
+ end_positions: np.ndarray | tf.Tensor | None = None,
2053
+ training: Optional[bool] = False,
2054
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
2055
+ r"""
2056
+ start_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
2057
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
2058
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
2059
+ are not taken into account for computing the loss.
2060
+ end_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
2061
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
2062
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
2063
+ are not taken into account for computing the loss.
2064
+ """
2065
+ outputs = self.bert(
2066
+ input_ids=input_ids,
2067
+ attention_mask=attention_mask,
2068
+ token_type_ids=token_type_ids,
2069
+ position_ids=position_ids,
2070
+ head_mask=head_mask,
2071
+ inputs_embeds=inputs_embeds,
2072
+ output_attentions=output_attentions,
2073
+ output_hidden_states=output_hidden_states,
2074
+ return_dict=return_dict,
2075
+ training=training,
2076
+ )
2077
+ sequence_output = outputs[0]
2078
+ logits = self.qa_outputs(inputs=sequence_output)
2079
+ start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)
2080
+ start_logits = tf.squeeze(input=start_logits, axis=-1)
2081
+ end_logits = tf.squeeze(input=end_logits, axis=-1)
2082
+ loss = None
2083
+
2084
+ if start_positions is not None and end_positions is not None:
2085
+ labels = {"start_position": start_positions}
2086
+ labels["end_position"] = end_positions
2087
+ loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits))
2088
+
2089
+ if not return_dict:
2090
+ output = (start_logits, end_logits) + outputs[2:]
2091
+ return ((loss,) + output) if loss is not None else output
2092
+
2093
+ return TFQuestionAnsweringModelOutput(
2094
+ loss=loss,
2095
+ start_logits=start_logits,
2096
+ end_logits=end_logits,
2097
+ hidden_states=outputs.hidden_states,
2098
+ attentions=outputs.attentions,
2099
+ )
2100
+
2101
+ def build(self, input_shape=None):
2102
+ if self.built:
2103
+ return
2104
+ self.built = True
2105
+ if getattr(self, "bert", None) is not None:
2106
+ with tf.name_scope(self.bert.name):
2107
+ self.bert.build(None)
2108
+ if getattr(self, "qa_outputs", None) is not None:
2109
+ with tf.name_scope(self.qa_outputs.name):
2110
+ self.qa_outputs.build([None, None, self.config.hidden_size])
2111
+
2112
+
2113
+ __all__ = [
2114
+ "TFBertEmbeddings",
2115
+ "TFBertForMaskedLM",
2116
+ "TFBertForMultipleChoice",
2117
+ "TFBertForNextSentencePrediction",
2118
+ "TFBertForPreTraining",
2119
+ "TFBertForQuestionAnswering",
2120
+ "TFBertForSequenceClassification",
2121
+ "TFBertForTokenClassification",
2122
+ "TFBertLMHeadModel",
2123
+ "TFBertMainLayer",
2124
+ "TFBertModel",
2125
+ "TFBertPreTrainedModel",
2126
+ ]
lib/python3.12/site-packages/transformers/models/bert/tokenization_bert.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Bert."""
16
+
17
+ import collections
18
+ import os
19
+ import unicodedata
20
+ from typing import List, Optional, Tuple
21
+
22
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
29
+
30
+
31
+ def load_vocab(vocab_file):
32
+ """Loads a vocabulary file into a dictionary."""
33
+ vocab = collections.OrderedDict()
34
+ with open(vocab_file, "r", encoding="utf-8") as reader:
35
+ tokens = reader.readlines()
36
+ for index, token in enumerate(tokens):
37
+ token = token.rstrip("\n")
38
+ vocab[token] = index
39
+ return vocab
40
+
41
+
42
+ def whitespace_tokenize(text):
43
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
44
+ text = text.strip()
45
+ if not text:
46
+ return []
47
+ tokens = text.split()
48
+ return tokens
49
+
50
+
51
+ class BertTokenizer(PreTrainedTokenizer):
52
+ r"""
53
+ Construct a BERT tokenizer. Based on WordPiece.
54
+
55
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
56
+ this superclass for more information regarding those methods.
57
+
58
+ Args:
59
+ vocab_file (`str`):
60
+ File containing the vocabulary.
61
+ do_lower_case (`bool`, *optional*, defaults to `True`):
62
+ Whether or not to lowercase the input when tokenizing.
63
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to do basic tokenization before WordPiece.
65
+ never_split (`Iterable`, *optional*):
66
+ Collection of tokens which will never be split during tokenization. Only has an effect when
67
+ `do_basic_tokenize=True`
68
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
69
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
70
+ token instead.
71
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
72
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
73
+ sequence classification or for a text and a question for question answering. It is also used as the last
74
+ token of a sequence built with special tokens.
75
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
76
+ The token used for padding, for example when batching sequences of different lengths.
77
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
78
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
79
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
80
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
81
+ The token used for masking values. This is the token used when training this model with masked language
82
+ modeling. This is the token which the model will try to predict.
83
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
84
+ Whether or not to tokenize Chinese characters.
85
+
86
+ This should likely be deactivated for Japanese (see this
87
+ [issue](https://github.com/huggingface/transformers/issues/328)).
88
+ strip_accents (`bool`, *optional*):
89
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
90
+ value for `lowercase` (as in the original BERT).
91
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
92
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
93
+ extra spaces.
94
+ """
95
+
96
+ vocab_files_names = VOCAB_FILES_NAMES
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_file,
101
+ do_lower_case=True,
102
+ do_basic_tokenize=True,
103
+ never_split=None,
104
+ unk_token="[UNK]",
105
+ sep_token="[SEP]",
106
+ pad_token="[PAD]",
107
+ cls_token="[CLS]",
108
+ mask_token="[MASK]",
109
+ tokenize_chinese_chars=True,
110
+ strip_accents=None,
111
+ clean_up_tokenization_spaces=True,
112
+ **kwargs,
113
+ ):
114
+ if not os.path.isfile(vocab_file):
115
+ raise ValueError(
116
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
117
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
118
+ )
119
+ self.vocab = load_vocab(vocab_file)
120
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
121
+ self.do_basic_tokenize = do_basic_tokenize
122
+ if do_basic_tokenize:
123
+ self.basic_tokenizer = BasicTokenizer(
124
+ do_lower_case=do_lower_case,
125
+ never_split=never_split,
126
+ tokenize_chinese_chars=tokenize_chinese_chars,
127
+ strip_accents=strip_accents,
128
+ )
129
+
130
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
131
+
132
+ super().__init__(
133
+ do_lower_case=do_lower_case,
134
+ do_basic_tokenize=do_basic_tokenize,
135
+ never_split=never_split,
136
+ unk_token=unk_token,
137
+ sep_token=sep_token,
138
+ pad_token=pad_token,
139
+ cls_token=cls_token,
140
+ mask_token=mask_token,
141
+ tokenize_chinese_chars=tokenize_chinese_chars,
142
+ strip_accents=strip_accents,
143
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
144
+ **kwargs,
145
+ )
146
+
147
+ @property
148
+ def do_lower_case(self):
149
+ return self.basic_tokenizer.do_lower_case
150
+
151
+ @property
152
+ def vocab_size(self):
153
+ return len(self.vocab)
154
+
155
+ def get_vocab(self):
156
+ return dict(self.vocab, **self.added_tokens_encoder)
157
+
158
+ def _tokenize(self, text, split_special_tokens=False):
159
+ split_tokens = []
160
+ if self.do_basic_tokenize:
161
+ for token in self.basic_tokenizer.tokenize(
162
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
163
+ ):
164
+ # If the token is part of the never_split set
165
+ if token in self.basic_tokenizer.never_split:
166
+ split_tokens.append(token)
167
+ else:
168
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
169
+ else:
170
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
171
+ return split_tokens
172
+
173
+ def _convert_token_to_id(self, token):
174
+ """Converts a token (str) in an id using the vocab."""
175
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
176
+
177
+ def _convert_id_to_token(self, index):
178
+ """Converts an index (integer) in a token (str) using the vocab."""
179
+ return self.ids_to_tokens.get(index, self.unk_token)
180
+
181
+ def convert_tokens_to_string(self, tokens):
182
+ """Converts a sequence of tokens (string) in a single string."""
183
+ out_string = " ".join(tokens).replace(" ##", "").strip()
184
+ return out_string
185
+
186
+ def build_inputs_with_special_tokens(
187
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
188
+ ) -> List[int]:
189
+ """
190
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
191
+ adding special tokens. A BERT sequence has the following format:
192
+
193
+ - single sequence: `[CLS] X [SEP]`
194
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
195
+
196
+ Args:
197
+ token_ids_0 (`List[int]`):
198
+ List of IDs to which the special tokens will be added.
199
+ token_ids_1 (`List[int]`, *optional*):
200
+ Optional second list of IDs for sequence pairs.
201
+
202
+ Returns:
203
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
204
+ """
205
+ if token_ids_1 is None:
206
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
207
+ cls = [self.cls_token_id]
208
+ sep = [self.sep_token_id]
209
+ return cls + token_ids_0 + sep + token_ids_1 + sep
210
+
211
+ def get_special_tokens_mask(
212
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
213
+ ) -> List[int]:
214
+ """
215
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
216
+ special tokens using the tokenizer `prepare_for_model` method.
217
+
218
+ Args:
219
+ token_ids_0 (`List[int]`):
220
+ List of IDs.
221
+ token_ids_1 (`List[int]`, *optional*):
222
+ Optional second list of IDs for sequence pairs.
223
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
224
+ Whether or not the token list is already formatted with special tokens for the model.
225
+
226
+ Returns:
227
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
228
+ """
229
+
230
+ if already_has_special_tokens:
231
+ return super().get_special_tokens_mask(
232
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
233
+ )
234
+
235
+ if token_ids_1 is not None:
236
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
237
+ return [1] + ([0] * len(token_ids_0)) + [1]
238
+
239
+ def create_token_type_ids_from_sequences(
240
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
241
+ ) -> List[int]:
242
+ """
243
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
244
+ pair mask has the following format:
245
+
246
+ ```
247
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
248
+ | first sequence | second sequence |
249
+ ```
250
+
251
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
252
+
253
+ Args:
254
+ token_ids_0 (`List[int]`):
255
+ List of IDs.
256
+ token_ids_1 (`List[int]`, *optional*):
257
+ Optional second list of IDs for sequence pairs.
258
+
259
+ Returns:
260
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
261
+ """
262
+ sep = [self.sep_token_id]
263
+ cls = [self.cls_token_id]
264
+ if token_ids_1 is None:
265
+ return len(cls + token_ids_0 + sep) * [0]
266
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
267
+
268
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
269
+ index = 0
270
+ if os.path.isdir(save_directory):
271
+ vocab_file = os.path.join(
272
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
273
+ )
274
+ else:
275
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
276
+ with open(vocab_file, "w", encoding="utf-8") as writer:
277
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
278
+ if index != token_index:
279
+ logger.warning(
280
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
281
+ " Please check that the vocabulary is not corrupted!"
282
+ )
283
+ index = token_index
284
+ writer.write(token + "\n")
285
+ index += 1
286
+ return (vocab_file,)
287
+
288
+
289
+ class BasicTokenizer:
290
+ """
291
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
292
+
293
+ Args:
294
+ do_lower_case (`bool`, *optional*, defaults to `True`):
295
+ Whether or not to lowercase the input when tokenizing.
296
+ never_split (`Iterable`, *optional*):
297
+ Collection of tokens which will never be split during tokenization. Only has an effect when
298
+ `do_basic_tokenize=True`
299
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
300
+ Whether or not to tokenize Chinese characters.
301
+
302
+ This should likely be deactivated for Japanese (see this
303
+ [issue](https://github.com/huggingface/transformers/issues/328)).
304
+ strip_accents (`bool`, *optional*):
305
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
306
+ value for `lowercase` (as in the original BERT).
307
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
308
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
309
+ the full context of the words, such as contractions.
310
+ """
311
+
312
+ def __init__(
313
+ self,
314
+ do_lower_case=True,
315
+ never_split=None,
316
+ tokenize_chinese_chars=True,
317
+ strip_accents=None,
318
+ do_split_on_punc=True,
319
+ ):
320
+ if never_split is None:
321
+ never_split = []
322
+ self.do_lower_case = do_lower_case
323
+ self.never_split = set(never_split)
324
+ self.tokenize_chinese_chars = tokenize_chinese_chars
325
+ self.strip_accents = strip_accents
326
+ self.do_split_on_punc = do_split_on_punc
327
+
328
+ def tokenize(self, text, never_split=None):
329
+ """
330
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
331
+
332
+ Args:
333
+ never_split (`List[str]`, *optional*)
334
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
335
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
336
+ """
337
+ # union() returns a new set by concatenating the two sets.
338
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
339
+ text = self._clean_text(text)
340
+
341
+ # This was added on November 1st, 2018 for the multilingual and Chinese
342
+ # models. This is also applied to the English models now, but it doesn't
343
+ # matter since the English models were not trained on any Chinese data
344
+ # and generally don't have any Chinese data in them (there are Chinese
345
+ # characters in the vocabulary because Wikipedia does have some Chinese
346
+ # words in the English Wikipedia.).
347
+ if self.tokenize_chinese_chars:
348
+ text = self._tokenize_chinese_chars(text)
349
+ # prevents treating the same character with different unicode codepoints as different characters
350
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
351
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
352
+ split_tokens = []
353
+ for token in orig_tokens:
354
+ if token not in never_split:
355
+ if self.do_lower_case:
356
+ token = token.lower()
357
+ if self.strip_accents is not False:
358
+ token = self._run_strip_accents(token)
359
+ elif self.strip_accents:
360
+ token = self._run_strip_accents(token)
361
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
362
+
363
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
364
+ return output_tokens
365
+
366
+ def _run_strip_accents(self, text):
367
+ """Strips accents from a piece of text."""
368
+ text = unicodedata.normalize("NFD", text)
369
+ output = []
370
+ for char in text:
371
+ cat = unicodedata.category(char)
372
+ if cat == "Mn":
373
+ continue
374
+ output.append(char)
375
+ return "".join(output)
376
+
377
+ def _run_split_on_punc(self, text, never_split=None):
378
+ """Splits punctuation on a piece of text."""
379
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
380
+ return [text]
381
+ chars = list(text)
382
+ i = 0
383
+ start_new_word = True
384
+ output = []
385
+ while i < len(chars):
386
+ char = chars[i]
387
+ if _is_punctuation(char):
388
+ output.append([char])
389
+ start_new_word = True
390
+ else:
391
+ if start_new_word:
392
+ output.append([])
393
+ start_new_word = False
394
+ output[-1].append(char)
395
+ i += 1
396
+
397
+ return ["".join(x) for x in output]
398
+
399
+ def _tokenize_chinese_chars(self, text):
400
+ """Adds whitespace around any CJK character."""
401
+ output = []
402
+ for char in text:
403
+ cp = ord(char)
404
+ if self._is_chinese_char(cp):
405
+ output.append(" ")
406
+ output.append(char)
407
+ output.append(" ")
408
+ else:
409
+ output.append(char)
410
+ return "".join(output)
411
+
412
+ def _is_chinese_char(self, cp):
413
+ """Checks whether CP is the codepoint of a CJK character."""
414
+ # This defines a "chinese character" as anything in the CJK Unicode block:
415
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
416
+ #
417
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
418
+ # despite its name. The modern Korean Hangul alphabet is a different block,
419
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
420
+ # space-separated words, so they are not treated specially and handled
421
+ # like the all of the other languages.
422
+ if (
423
+ (cp >= 0x4E00 and cp <= 0x9FFF)
424
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
425
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
426
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
427
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
428
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
429
+ or (cp >= 0xF900 and cp <= 0xFAFF)
430
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
431
+ ): #
432
+ return True
433
+
434
+ return False
435
+
436
+ def _clean_text(self, text):
437
+ """Performs invalid character removal and whitespace cleanup on text."""
438
+ output = []
439
+ for char in text:
440
+ cp = ord(char)
441
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
442
+ continue
443
+ if _is_whitespace(char):
444
+ output.append(" ")
445
+ else:
446
+ output.append(char)
447
+ return "".join(output)
448
+
449
+
450
+ class WordpieceTokenizer:
451
+ """Runs WordPiece tokenization."""
452
+
453
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
454
+ self.vocab = vocab
455
+ self.unk_token = unk_token
456
+ self.max_input_chars_per_word = max_input_chars_per_word
457
+
458
+ def tokenize(self, text):
459
+ """
460
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
461
+ tokenization using the given vocabulary.
462
+
463
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
464
+
465
+ Args:
466
+ text: A single token or whitespace separated tokens. This should have
467
+ already been passed through *BasicTokenizer*.
468
+
469
+ Returns:
470
+ A list of wordpiece tokens.
471
+ """
472
+
473
+ output_tokens = []
474
+ for token in whitespace_tokenize(text):
475
+ chars = list(token)
476
+ if len(chars) > self.max_input_chars_per_word:
477
+ output_tokens.append(self.unk_token)
478
+ continue
479
+
480
+ is_bad = False
481
+ start = 0
482
+ sub_tokens = []
483
+ while start < len(chars):
484
+ end = len(chars)
485
+ cur_substr = None
486
+ while start < end:
487
+ substr = "".join(chars[start:end])
488
+ if start > 0:
489
+ substr = "##" + substr
490
+ if substr in self.vocab:
491
+ cur_substr = substr
492
+ break
493
+ end -= 1
494
+ if cur_substr is None:
495
+ is_bad = True
496
+ break
497
+ sub_tokens.append(cur_substr)
498
+ start = end
499
+
500
+ if is_bad:
501
+ output_tokens.append(self.unk_token)
502
+ else:
503
+ output_tokens.extend(sub_tokens)
504
+ return output_tokens
505
+
506
+
507
+ __all__ = ["BasicTokenizer", "BertTokenizer", "WordpieceTokenizer"]
lib/python3.12/site-packages/transformers/models/bert/tokenization_bert_fast.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast Tokenization classes for Bert."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import normalizers
21
+
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_bert import BertTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+
32
+ class BertTokenizerFast(PreTrainedTokenizerFast):
33
+ r"""
34
+ Construct a "fast" BERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
35
+
36
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
37
+ refer to this superclass for more information regarding those methods.
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ File containing the vocabulary.
42
+ do_lower_case (`bool`, *optional*, defaults to `True`):
43
+ Whether or not to lowercase the input when tokenizing.
44
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
45
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
46
+ token instead.
47
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
48
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
49
+ sequence classification or for a text and a question for question answering. It is also used as the last
50
+ token of a sequence built with special tokens.
51
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
52
+ The token used for padding, for example when batching sequences of different lengths.
53
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
54
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
55
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
56
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
57
+ The token used for masking values. This is the token used when training this model with masked language
58
+ modeling. This is the token which the model will try to predict.
59
+ clean_text (`bool`, *optional*, defaults to `True`):
60
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
61
+ whitespaces by the classic one.
62
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
63
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
64
+ issue](https://github.com/huggingface/transformers/issues/328)).
65
+ strip_accents (`bool`, *optional*):
66
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
67
+ value for `lowercase` (as in the original BERT).
68
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
69
+ The prefix for subwords.
70
+ """
71
+
72
+ vocab_files_names = VOCAB_FILES_NAMES
73
+ slow_tokenizer_class = BertTokenizer
74
+
75
+ def __init__(
76
+ self,
77
+ vocab_file=None,
78
+ tokenizer_file=None,
79
+ do_lower_case=True,
80
+ unk_token="[UNK]",
81
+ sep_token="[SEP]",
82
+ pad_token="[PAD]",
83
+ cls_token="[CLS]",
84
+ mask_token="[MASK]",
85
+ tokenize_chinese_chars=True,
86
+ strip_accents=None,
87
+ **kwargs,
88
+ ):
89
+ super().__init__(
90
+ vocab_file,
91
+ tokenizer_file=tokenizer_file,
92
+ do_lower_case=do_lower_case,
93
+ unk_token=unk_token,
94
+ sep_token=sep_token,
95
+ pad_token=pad_token,
96
+ cls_token=cls_token,
97
+ mask_token=mask_token,
98
+ tokenize_chinese_chars=tokenize_chinese_chars,
99
+ strip_accents=strip_accents,
100
+ **kwargs,
101
+ )
102
+
103
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
104
+ if (
105
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
106
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
107
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
108
+ ):
109
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
110
+ normalizer_state["lowercase"] = do_lower_case
111
+ normalizer_state["strip_accents"] = strip_accents
112
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
113
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
114
+
115
+ self.do_lower_case = do_lower_case
116
+
117
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
118
+ """
119
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
120
+ adding special tokens. A BERT sequence has the following format:
121
+
122
+ - single sequence: `[CLS] X [SEP]`
123
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
124
+
125
+ Args:
126
+ token_ids_0 (`List[int]`):
127
+ List of IDs to which the special tokens will be added.
128
+ token_ids_1 (`List[int]`, *optional*):
129
+ Optional second list of IDs for sequence pairs.
130
+
131
+ Returns:
132
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
133
+ """
134
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
135
+
136
+ if token_ids_1 is not None:
137
+ output += token_ids_1 + [self.sep_token_id]
138
+
139
+ return output
140
+
141
+ def create_token_type_ids_from_sequences(
142
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
143
+ ) -> List[int]:
144
+ """
145
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
146
+ pair mask has the following format:
147
+
148
+ ```
149
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
150
+ | first sequence | second sequence |
151
+ ```
152
+
153
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
154
+
155
+ Args:
156
+ token_ids_0 (`List[int]`):
157
+ List of IDs.
158
+ token_ids_1 (`List[int]`, *optional*):
159
+ Optional second list of IDs for sequence pairs.
160
+
161
+ Returns:
162
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
163
+ """
164
+ sep = [self.sep_token_id]
165
+ cls = [self.cls_token_id]
166
+ if token_ids_1 is None:
167
+ return len(cls + token_ids_0 + sep) * [0]
168
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
169
+
170
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
171
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
172
+ return tuple(files)
173
+
174
+
175
+ __all__ = ["BertTokenizerFast"]
lib/python3.12/site-packages/transformers/models/bert/tokenization_bert_tf.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Optional, Union
3
+
4
+ import tensorflow as tf
5
+ from tensorflow_text import BertTokenizer as BertTokenizerLayer
6
+ from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utf8, combine_segments, pad_model_inputs
7
+
8
+ from ...modeling_tf_utils import keras
9
+ from .tokenization_bert import BertTokenizer
10
+
11
+
12
+ class TFBertTokenizer(keras.layers.Layer):
13
+ """
14
+ This is an in-graph tokenizer for BERT. It should be initialized similarly to other tokenizers, using the
15
+ `from_pretrained()` method. It can also be initialized with the `from_tokenizer()` method, which imports settings
16
+ from an existing standard tokenizer object.
17
+
18
+ In-graph tokenizers, unlike other Hugging Face tokenizers, are actually Keras layers and are designed to be run
19
+ when the model is called, rather than during preprocessing. As a result, they have somewhat more limited options
20
+ than standard tokenizer classes. They are most useful when you want to create an end-to-end model that goes
21
+ straight from `tf.string` inputs to outputs.
22
+
23
+ Args:
24
+ vocab_list (`list`):
25
+ List containing the vocabulary.
26
+ do_lower_case (`bool`, *optional*, defaults to `True`):
27
+ Whether or not to lowercase the input when tokenizing.
28
+ cls_token_id (`str`, *optional*, defaults to `"[CLS]"`):
29
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
30
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
31
+ sep_token_id (`str`, *optional*, defaults to `"[SEP]"`):
32
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
33
+ sequence classification or for a text and a question for question answering. It is also used as the last
34
+ token of a sequence built with special tokens.
35
+ pad_token_id (`str`, *optional*, defaults to `"[PAD]"`):
36
+ The token used for padding, for example when batching sequences of different lengths.
37
+ padding (`str`, defaults to `"longest"`):
38
+ The type of padding to use. Can be either `"longest"`, to pad only up to the longest sample in the batch,
39
+ or `"max_length", to pad all inputs to the maximum length supported by the tokenizer.
40
+ truncation (`bool`, *optional*, defaults to `True`):
41
+ Whether to truncate the sequence to the maximum length.
42
+ max_length (`int`, *optional*, defaults to `512`):
43
+ The maximum length of the sequence, used for padding (if `padding` is "max_length") and/or truncation (if
44
+ `truncation` is `True`).
45
+ pad_to_multiple_of (`int`, *optional*, defaults to `None`):
46
+ If set, the sequence will be padded to a multiple of this value.
47
+ return_token_type_ids (`bool`, *optional*, defaults to `True`):
48
+ Whether to return token_type_ids.
49
+ return_attention_mask (`bool`, *optional*, defaults to `True`):
50
+ Whether to return the attention_mask.
51
+ use_fast_bert_tokenizer (`bool`, *optional*, defaults to `True`):
52
+ If True, will use the FastBertTokenizer class from Tensorflow Text. If False, will use the BertTokenizer
53
+ class instead. BertTokenizer supports some additional options, but is slower and cannot be exported to
54
+ TFLite.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ vocab_list: List,
60
+ do_lower_case: bool,
61
+ cls_token_id: Optional[int] = None,
62
+ sep_token_id: Optional[int] = None,
63
+ pad_token_id: Optional[int] = None,
64
+ padding: str = "longest",
65
+ truncation: bool = True,
66
+ max_length: int = 512,
67
+ pad_to_multiple_of: Optional[int] = None,
68
+ return_token_type_ids: bool = True,
69
+ return_attention_mask: bool = True,
70
+ use_fast_bert_tokenizer: bool = True,
71
+ **tokenizer_kwargs,
72
+ ):
73
+ super().__init__()
74
+ if use_fast_bert_tokenizer:
75
+ self.tf_tokenizer = FastBertTokenizer(
76
+ vocab_list, token_out_type=tf.int64, lower_case_nfd_strip_accents=do_lower_case, **tokenizer_kwargs
77
+ )
78
+ else:
79
+ lookup_table = tf.lookup.StaticVocabularyTable(
80
+ tf.lookup.KeyValueTensorInitializer(
81
+ keys=vocab_list,
82
+ key_dtype=tf.string,
83
+ values=tf.range(tf.size(vocab_list, out_type=tf.int64), dtype=tf.int64),
84
+ value_dtype=tf.int64,
85
+ ),
86
+ num_oov_buckets=1,
87
+ )
88
+ self.tf_tokenizer = BertTokenizerLayer(
89
+ lookup_table, token_out_type=tf.int64, lower_case=do_lower_case, **tokenizer_kwargs
90
+ )
91
+
92
+ self.vocab_list = vocab_list
93
+ self.do_lower_case = do_lower_case
94
+ self.cls_token_id = vocab_list.index("[CLS]") if cls_token_id is None else cls_token_id
95
+ self.sep_token_id = vocab_list.index("[SEP]") if sep_token_id is None else sep_token_id
96
+ self.pad_token_id = vocab_list.index("[PAD]") if pad_token_id is None else pad_token_id
97
+ self.paired_trimmer = ShrinkLongestTrimmer(max_length - 3, axis=1) # Allow room for special tokens
98
+ self.max_length = max_length
99
+ self.padding = padding
100
+ self.truncation = truncation
101
+ self.pad_to_multiple_of = pad_to_multiple_of
102
+ self.return_token_type_ids = return_token_type_ids
103
+ self.return_attention_mask = return_attention_mask
104
+
105
+ @classmethod
106
+ def from_tokenizer(cls, tokenizer: "PreTrainedTokenizerBase", **kwargs): # noqa: F821
107
+ """
108
+ Initialize a `TFBertTokenizer` from an existing `Tokenizer`.
109
+
110
+ Args:
111
+ tokenizer (`PreTrainedTokenizerBase`):
112
+ The tokenizer to use to initialize the `TFBertTokenizer`.
113
+
114
+ Examples:
115
+
116
+ ```python
117
+ from transformers import AutoTokenizer, TFBertTokenizer
118
+
119
+ tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
120
+ tf_tokenizer = TFBertTokenizer.from_tokenizer(tokenizer)
121
+ ```
122
+ """
123
+ do_lower_case = kwargs.pop("do_lower_case", None)
124
+ do_lower_case = tokenizer.do_lower_case if do_lower_case is None else do_lower_case
125
+ cls_token_id = kwargs.pop("cls_token_id", None)
126
+ cls_token_id = tokenizer.cls_token_id if cls_token_id is None else cls_token_id
127
+ sep_token_id = kwargs.pop("sep_token_id", None)
128
+ sep_token_id = tokenizer.sep_token_id if sep_token_id is None else sep_token_id
129
+ pad_token_id = kwargs.pop("pad_token_id", None)
130
+ pad_token_id = tokenizer.pad_token_id if pad_token_id is None else pad_token_id
131
+
132
+ vocab = tokenizer.get_vocab()
133
+ vocab = sorted(vocab.items(), key=lambda x: x[1])
134
+ vocab_list = [entry[0] for entry in vocab]
135
+ return cls(
136
+ vocab_list=vocab_list,
137
+ do_lower_case=do_lower_case,
138
+ cls_token_id=cls_token_id,
139
+ sep_token_id=sep_token_id,
140
+ pad_token_id=pad_token_id,
141
+ **kwargs,
142
+ )
143
+
144
+ @classmethod
145
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], *init_inputs, **kwargs):
146
+ """
147
+ Instantiate a `TFBertTokenizer` from a pre-trained tokenizer.
148
+
149
+ Args:
150
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
151
+ The name or path to the pre-trained tokenizer.
152
+
153
+ Examples:
154
+
155
+ ```python
156
+ from transformers import TFBertTokenizer
157
+
158
+ tf_tokenizer = TFBertTokenizer.from_pretrained("google-bert/bert-base-uncased")
159
+ ```
160
+ """
161
+ try:
162
+ tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
163
+ except: # noqa: E722
164
+ from .tokenization_bert_fast import BertTokenizerFast
165
+
166
+ tokenizer = BertTokenizerFast.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
167
+ return cls.from_tokenizer(tokenizer, **kwargs)
168
+
169
+ def unpaired_tokenize(self, texts):
170
+ if self.do_lower_case:
171
+ texts = case_fold_utf8(texts)
172
+ tokens = self.tf_tokenizer.tokenize(texts)
173
+ return tokens.merge_dims(1, -1)
174
+
175
+ def call(
176
+ self,
177
+ text,
178
+ text_pair=None,
179
+ padding=None,
180
+ truncation=None,
181
+ max_length=None,
182
+ pad_to_multiple_of=None,
183
+ return_token_type_ids=None,
184
+ return_attention_mask=None,
185
+ ):
186
+ if padding is None:
187
+ padding = self.padding
188
+ if padding not in ("longest", "max_length"):
189
+ raise ValueError("Padding must be either 'longest' or 'max_length'!")
190
+ if max_length is not None and text_pair is not None:
191
+ # Because we have to instantiate a Trimmer to do it properly
192
+ raise ValueError("max_length cannot be overridden at call time when truncating paired texts!")
193
+ if max_length is None:
194
+ max_length = self.max_length
195
+ if truncation is None:
196
+ truncation = self.truncation
197
+ if pad_to_multiple_of is None:
198
+ pad_to_multiple_of = self.pad_to_multiple_of
199
+ if return_token_type_ids is None:
200
+ return_token_type_ids = self.return_token_type_ids
201
+ if return_attention_mask is None:
202
+ return_attention_mask = self.return_attention_mask
203
+ if not isinstance(text, tf.Tensor):
204
+ text = tf.convert_to_tensor(text)
205
+ if text_pair is not None and not isinstance(text_pair, tf.Tensor):
206
+ text_pair = tf.convert_to_tensor(text_pair)
207
+ if text_pair is not None:
208
+ if text.shape.rank > 1:
209
+ raise ValueError("text argument should not be multidimensional when a text pair is supplied!")
210
+ if text_pair.shape.rank > 1:
211
+ raise ValueError("text_pair should not be multidimensional!")
212
+ if text.shape.rank == 2:
213
+ text, text_pair = text[:, 0], text[:, 1]
214
+ text = self.unpaired_tokenize(text)
215
+ if text_pair is None: # Unpaired text
216
+ if truncation:
217
+ text = text[:, : max_length - 2] # Allow room for special tokens
218
+ input_ids, token_type_ids = combine_segments(
219
+ (text,), start_of_sequence_id=self.cls_token_id, end_of_segment_id=self.sep_token_id
220
+ )
221
+ else: # Paired text
222
+ text_pair = self.unpaired_tokenize(text_pair)
223
+ if truncation:
224
+ text, text_pair = self.paired_trimmer.trim([text, text_pair])
225
+ input_ids, token_type_ids = combine_segments(
226
+ (text, text_pair), start_of_sequence_id=self.cls_token_id, end_of_segment_id=self.sep_token_id
227
+ )
228
+ if padding == "longest":
229
+ pad_length = input_ids.bounding_shape(axis=1)
230
+ if pad_to_multiple_of is not None:
231
+ # No ceiling division in tensorflow, so we negate floordiv instead
232
+ pad_length = pad_to_multiple_of * (-tf.math.floordiv(-pad_length, pad_to_multiple_of))
233
+ else:
234
+ pad_length = max_length
235
+
236
+ input_ids, attention_mask = pad_model_inputs(input_ids, max_seq_length=pad_length, pad_value=self.pad_token_id)
237
+ output = {"input_ids": input_ids}
238
+ if return_attention_mask:
239
+ output["attention_mask"] = attention_mask
240
+ if return_token_type_ids:
241
+ token_type_ids, _ = pad_model_inputs(
242
+ token_type_ids, max_seq_length=pad_length, pad_value=self.pad_token_id
243
+ )
244
+ output["token_type_ids"] = token_type_ids
245
+ return output
246
+
247
+ def get_config(self):
248
+ return {
249
+ "vocab_list": self.vocab_list,
250
+ "do_lower_case": self.do_lower_case,
251
+ "cls_token_id": self.cls_token_id,
252
+ "sep_token_id": self.sep_token_id,
253
+ "pad_token_id": self.pad_token_id,
254
+ }
255
+
256
+
257
+ __all__ = ["TFBertTokenizer"]
lib/python3.12/site-packages/transformers/models/clap/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_clap import *
22
+ from .feature_extraction_clap import *
23
+ from .modeling_clap import *
24
+ from .processing_clap import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/clap/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (729 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-312.pyc ADDED
Binary file (18 kB). View file
 
lib/python3.12/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-312.pyc ADDED
Binary file (19.1 kB). View file