configuration_auto.py 42.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Sylvain Gugger's avatar
Sylvain Gugger committed
15
""" Auto Config class."""
16
import importlib
17
import re
18
import warnings
19
from collections import OrderedDict
20
from typing import List, Union
21

Sylvain Gugger's avatar
Sylvain Gugger committed
22
from ...configuration_utils import PretrainedConfig
23
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
24
from ...utils import CONFIG_NAME, logging
Aymeric Augustin's avatar
Aymeric Augustin committed
25

26

27
28
logger = logging.get_logger(__name__)

29
30
31
CONFIG_MAPPING_NAMES = OrderedDict(
    [
        # Add configs here
32
        ("albert", "AlbertConfig"),
33
        ("align", "AlignConfig"),
Jongjyh's avatar
Jongjyh committed
34
        ("altclip", "AltCLIPConfig"),
35
        ("audio-spectrogram-transformer", "ASTConfig"),
36
        ("autoformer", "AutoformerConfig"),
37
        ("bart", "BartConfig"),
38
        ("beit", "BeitConfig"),
39
40
41
42
        ("bert", "BertConfig"),
        ("bert-generation", "BertGenerationConfig"),
        ("big_bird", "BigBirdConfig"),
        ("bigbird_pegasus", "BigBirdPegasusConfig"),
Kamal Raj Kanakarajan's avatar
Kamal Raj Kanakarajan committed
43
        ("biogpt", "BioGptConfig"),
NielsRogge's avatar
NielsRogge committed
44
        ("bit", "BitConfig"),
45
46
        ("blenderbot", "BlenderbotConfig"),
        ("blenderbot-small", "BlenderbotSmallConfig"),
Younes Belkada's avatar
Younes Belkada committed
47
        ("blip", "BlipConfig"),
NielsRogge's avatar
NielsRogge committed
48
        ("blip-2", "Blip2Config"),
Younes Belkada's avatar
Younes Belkada committed
49
        ("bloom", "BloomConfig"),
50
        ("bridgetower", "BridgeTowerConfig"),
51
        ("camembert", "CamembertConfig"),
52
        ("canine", "CanineConfig"),
53
        ("chinese_clip", "ChineseCLIPConfig"),
54
        ("clap", "ClapConfig"),
55
        ("clip", "CLIPConfig"),
NielsRogge's avatar
NielsRogge committed
56
        ("clipseg", "CLIPSegConfig"),
rooa's avatar
rooa committed
57
        ("codegen", "CodeGenConfig"),
58
        ("conditional_detr", "ConditionalDetrConfig"),
59
60
        ("convbert", "ConvBertConfig"),
        ("convnext", "ConvNextConfig"),
Alara Dirik's avatar
Alara Dirik committed
61
        ("convnextv2", "ConvNextV2Config"),
62
        ("cpmant", "CpmAntConfig"),
63
        ("ctrl", "CTRLConfig"),
NielsRogge's avatar
NielsRogge committed
64
        ("cvt", "CvtConfig"),
65
66
67
68
69
70
        ("data2vec-audio", "Data2VecAudioConfig"),
        ("data2vec-text", "Data2VecTextConfig"),
        ("data2vec-vision", "Data2VecVisionConfig"),
        ("deberta", "DebertaConfig"),
        ("deberta-v2", "DebertaV2Config"),
        ("decision_transformer", "DecisionTransformerConfig"),
NielsRogge's avatar
NielsRogge committed
71
        ("deformable_detr", "DeformableDetrConfig"),
72
        ("deit", "DeiTConfig"),
NielsRogge's avatar
NielsRogge committed
73
        ("deta", "DetaConfig"),
74
        ("detr", "DetrConfig"),
75
        ("dinat", "DinatConfig"),
76
        ("distilbert", "DistilBertConfig"),
NielsRogge's avatar
NielsRogge committed
77
        ("donut-swin", "DonutSwinConfig"),
78
79
        ("dpr", "DPRConfig"),
        ("dpt", "DPTConfig"),
80
        ("efficientformer", "EfficientFormerConfig"),
Alara Dirik's avatar
Alara Dirik committed
81
        ("efficientnet", "EfficientNetConfig"),
82
        ("electra", "ElectraConfig"),
83
        ("encodec", "EncodecConfig"),
84
        ("encoder-decoder", "EncoderDecoderConfig"),
85
        ("ernie", "ErnieConfig"),
86
        ("ernie_m", "ErnieMConfig"),
87
        ("esm", "EsmConfig"),
88
89
90
        ("flaubert", "FlaubertConfig"),
        ("flava", "FlavaConfig"),
        ("fnet", "FNetConfig"),
NielsRogge's avatar
NielsRogge committed
91
        ("focalnet", "FocalNetConfig"),
92
93
        ("fsmt", "FSMTConfig"),
        ("funnel", "FunnelConfig"),
94
        ("git", "GitConfig"),
95
        ("glpn", "GLPNConfig"),
96
        ("gpt-sw3", "GPT2Config"),
97
        ("gpt2", "GPT2Config"),
98
        ("gpt_bigcode", "GPTBigCodeConfig"),
99
        ("gpt_neo", "GPTNeoConfig"),
100
        ("gpt_neox", "GPTNeoXConfig"),
101
        ("gpt_neox_japanese", "GPTNeoXJapaneseConfig"),
102
        ("gptj", "GPTJConfig"),
103
        ("gptsan-japanese", "GPTSanJapaneseConfig"),
104
        ("graphormer", "GraphormerConfig"),
105
        ("groupvit", "GroupViTConfig"),
106
        ("hubert", "HubertConfig"),
107
        ("ibert", "IBertConfig"),
108
        ("imagegpt", "ImageGPTConfig"),
109
        ("informer", "InformerConfig"),
NielsRogge's avatar
NielsRogge committed
110
        ("instructblip", "InstructBlipConfig"),
111
        ("jukebox", "JukeboxConfig"),
112
113
        ("layoutlm", "LayoutLMConfig"),
        ("layoutlmv2", "LayoutLMv2Config"),
NielsRogge's avatar
NielsRogge committed
114
        ("layoutlmv3", "LayoutLMv3Config"),
115
        ("led", "LEDConfig"),
116
        ("levit", "LevitConfig"),
NielsRogge's avatar
NielsRogge committed
117
        ("lilt", "LiltConfig"),
Jason Phang's avatar
Jason Phang committed
118
        ("llama", "LlamaConfig"),
119
        ("longformer", "LongformerConfig"),
Daniel Stancl's avatar
Daniel Stancl committed
120
        ("longt5", "LongT5Config"),
121
122
123
        ("luke", "LukeConfig"),
        ("lxmert", "LxmertConfig"),
        ("m2m_100", "M2M100Config"),
124
        ("marian", "MarianConfig"),
NielsRogge's avatar
NielsRogge committed
125
        ("markuplm", "MarkupLMConfig"),
Alara Dirik's avatar
Alara Dirik committed
126
        ("mask2former", "Mask2FormerConfig"),
127
        ("maskformer", "MaskFormerConfig"),
128
        ("maskformer-swin", "MaskFormerSwinConfig"),
129
        ("mbart", "MBartConfig"),
Chan Woo Kim's avatar
Chan Woo Kim committed
130
        ("mctct", "MCTCTConfig"),
131
        ("mega", "MegaConfig"),
132
        ("megatron-bert", "MegatronBertConfig"),
wangpeng's avatar
wangpeng committed
133
        ("mgp-str", "MgpstrConfig"),
134
        ("mobilebert", "MobileBertConfig"),
135
        ("mobilenet_v1", "MobileNetV1Config"),
136
        ("mobilenet_v2", "MobileNetV2Config"),
137
        ("mobilevit", "MobileViTConfig"),
Shehan Munasinghe's avatar
Shehan Munasinghe committed
138
        ("mobilevitv2", "MobileViTV2Config"),
139
        ("mpnet", "MPNetConfig"),
140
        ("mt5", "MT5Config"),
Sanchit Gandhi's avatar
Sanchit Gandhi committed
141
        ("musicgen", "MusicgenConfig"),
StevenTang1998's avatar
StevenTang1998 committed
142
        ("mvp", "MvpConfig"),
143
        ("nat", "NatConfig"),
144
        ("nezha", "NezhaConfig"),
145
        ("nllb-moe", "NllbMoeConfig"),
146
        ("nystromformer", "NystromformerConfig"),
Jitesh Jain's avatar
Jitesh Jain committed
147
        ("oneformer", "OneFormerConfig"),
148
        ("open-llama", "OpenLlamaConfig"),
149
        ("openai-gpt", "OpenAIGPTConfig"),
Younes Belkada's avatar
Younes Belkada committed
150
        ("opt", "OPTConfig"),
151
        ("owlvit", "OwlViTConfig"),
152
        ("pegasus", "PegasusConfig"),
Jason Phang's avatar
Jason Phang committed
153
        ("pegasus_x", "PegasusXConfig"),
154
        ("perceiver", "PerceiverConfig"),
Younes Belkada's avatar
Younes Belkada committed
155
        ("pix2struct", "Pix2StructConfig"),
156
157
158
159
160
161
        ("plbart", "PLBartConfig"),
        ("poolformer", "PoolFormerConfig"),
        ("prophetnet", "ProphetNetConfig"),
        ("qdqbert", "QDQBertConfig"),
        ("rag", "RagConfig"),
        ("realm", "RealmConfig"),
162
        ("reformer", "ReformerConfig"),
163
164
165
166
        ("regnet", "RegNetConfig"),
        ("rembert", "RemBertConfig"),
        ("resnet", "ResNetConfig"),
        ("retribert", "RetriBertConfig"),
167
        ("roberta", "RobertaConfig"),
168
        ("roberta-prelayernorm", "RobertaPreLayerNormConfig"),
Weiwe Shi's avatar
Weiwe Shi committed
169
        ("roc_bert", "RoCBertConfig"),
170
        ("roformer", "RoFormerConfig"),
Sylvain Gugger's avatar
Sylvain Gugger committed
171
        ("rwkv", "RwkvConfig"),
172
        ("sam", "SamConfig"),
173
174
175
        ("segformer", "SegformerConfig"),
        ("sew", "SEWConfig"),
        ("sew-d", "SEWDConfig"),
176
        ("speech-encoder-decoder", "SpeechEncoderDecoderConfig"),
177
178
        ("speech_to_text", "Speech2TextConfig"),
        ("speech_to_text_2", "Speech2Text2Config"),
179
        ("speecht5", "SpeechT5Config"),
Ori Ram's avatar
Ori Ram committed
180
        ("splinter", "SplinterConfig"),
181
        ("squeezebert", "SqueezeBertConfig"),
Shehan Munasinghe's avatar
Shehan Munasinghe committed
182
        ("swiftformer", "SwiftFormerConfig"),
183
        ("swin", "SwinConfig"),
NielsRogge's avatar
NielsRogge committed
184
        ("swin2sr", "Swin2SRConfig"),
185
        ("swinv2", "Swinv2Config"),
186
        ("switch_transformers", "SwitchTransformersConfig"),
187
        ("t5", "T5Config"),
188
        ("table-transformer", "TableTransformerConfig"),
189
        ("tapas", "TapasConfig"),
190
        ("time_series_transformer", "TimeSeriesTransformerConfig"),
191
        ("timesformer", "TimesformerConfig"),
amyeroberts's avatar
amyeroberts committed
192
        ("timm_backbone", "TimmBackboneConfig"),
Carl's avatar
Carl committed
193
        ("trajectory_transformer", "TrajectoryTransformerConfig"),
194
195
        ("transfo-xl", "TransfoXLConfig"),
        ("trocr", "TrOCRConfig"),
Zineng Tang's avatar
Zineng Tang committed
196
        ("tvlt", "TvltConfig"),
197
        ("unispeech", "UniSpeechConfig"),
198
        ("unispeech-sat", "UniSpeechSatConfig"),
NielsRogge's avatar
NielsRogge committed
199
        ("upernet", "UperNetConfig"),
200
        ("van", "VanConfig"),
NielsRogge's avatar
NielsRogge committed
201
        ("videomae", "VideoMAEConfig"),
202
203
204
205
206
        ("vilt", "ViltConfig"),
        ("vision-encoder-decoder", "VisionEncoderDecoderConfig"),
        ("vision-text-dual-encoder", "VisionTextDualEncoderConfig"),
        ("visual_bert", "VisualBertConfig"),
        ("vit", "ViTConfig"),
NielsRogge's avatar
NielsRogge committed
207
        ("vit_hybrid", "ViTHybridConfig"),
208
        ("vit_mae", "ViTMAEConfig"),
209
        ("vit_msn", "ViTMSNConfig"),
210
        ("wav2vec2", "Wav2Vec2Config"),
211
        ("wav2vec2-conformer", "Wav2Vec2ConformerConfig"),
Patrick von Platen's avatar
Patrick von Platen committed
212
        ("wavlm", "WavLMConfig"),
213
        ("whisper", "WhisperConfig"),
NielsRogge's avatar
NielsRogge committed
214
        ("xclip", "XCLIPConfig"),
215
216
217
218
219
220
        ("xglm", "XGLMConfig"),
        ("xlm", "XLMConfig"),
        ("xlm-prophetnet", "XLMProphetNetConfig"),
        ("xlm-roberta", "XLMRobertaConfig"),
        ("xlm-roberta-xl", "XLMRobertaXLConfig"),
        ("xlnet", "XLNetConfig"),
Jannis Vamvas's avatar
Jannis Vamvas committed
221
        ("xmod", "XmodConfig"),
222
223
        ("yolos", "YolosConfig"),
        ("yoso", "YosoConfig"),
224
225
    ]
)
226

227
CONFIG_ARCHIVE_MAP_MAPPING_NAMES = OrderedDict(
228
    [
NielsRogge's avatar
NielsRogge committed
229
        # Add archive maps here)
230
        ("albert", "ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
231
        ("align", "ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jongjyh's avatar
Jongjyh committed
232
        ("altclip", "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
233
        ("audio-spectrogram-transformer", "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
234
        ("autoformer", "AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
235
        ("bart", "BART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
236
        ("beit", "BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
237
238
239
        ("bert", "BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("big_bird", "BIG_BIRD_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("bigbird_pegasus", "BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Kamal Raj Kanakarajan's avatar
Kamal Raj Kanakarajan committed
240
        ("biogpt", "BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
241
        ("bit", "BIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
242
243
        ("blenderbot", "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("blenderbot-small", "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Younes Belkada's avatar
Younes Belkada committed
244
        ("blip", "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
245
        ("blip-2", "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Younes Belkada's avatar
Younes Belkada committed
246
        ("bloom", "BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
247
        ("bridgetower", "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
248
        ("camembert", "CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
249
        ("canine", "CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
250
        ("chinese_clip", "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
251
        ("clap", "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST"),
252
        ("clip", "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
253
        ("clipseg", "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP"),
rooa's avatar
rooa committed
254
        ("codegen", "CODEGEN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
255
        ("conditional_detr", "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
256
        ("convbert", "CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
257
        ("convnext", "CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Alara Dirik's avatar
Alara Dirik committed
258
        ("convnextv2", "CONVNEXTV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
259
        ("cpmant", "CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
260
        ("ctrl", "CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
261
        ("cvt", "CVT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
262
        ("data2vec-audio", "DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
263
264
265
266
        ("data2vec-text", "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("data2vec-vision", "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("deberta", "DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("deberta-v2", "DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
267
        ("deformable_detr", "DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
268
        ("deit", "DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
269
        ("deta", "DETA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
270
        ("detr", "DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
271
        ("dinat", "DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
272
        ("distilbert", "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
273
        ("donut-swin", "DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
274
275
        ("dpr", "DPR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("dpt", "DPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
276
        ("efficientformer", "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Alara Dirik's avatar
Alara Dirik committed
277
        ("efficientnet", "EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
278
        ("electra", "ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
279
        ("encodec", "ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP"),
280
        ("ernie", "ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
281
        ("ernie_m", "ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP"),
282
        ("esm", "ESM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
283
        ("flaubert", "FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
284
285
        ("flava", "FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("fnet", "FNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
286
        ("focalnet", "FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
287
288
        ("fsmt", "FSMT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("funnel", "FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
289
        ("git", "GIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
290
291
        ("glpn", "GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("gpt2", "GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
292
        ("gpt_bigcode", "GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
293
        ("gpt_neo", "GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
294
        ("gpt_neox", "GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP"),
295
        ("gpt_neox_japanese", "GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
296
        ("gptj", "GPTJ_PRETRAINED_CONFIG_ARCHIVE_MAP"),
297
        ("gptsan-japanese", "GPTSAN_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
298
        ("graphormer", "GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
299
        ("groupvit", "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
300
301
302
        ("hubert", "HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("ibert", "IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("imagegpt", "IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
303
        ("informer", "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
304
        ("instructblip", "INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
305
        ("jukebox", "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP"),
306
        ("layoutlm", "LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
307
        ("layoutlmv2", "LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
308
        ("layoutlmv3", "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP"),
309
        ("led", "LED_PRETRAINED_CONFIG_ARCHIVE_MAP"),
310
        ("levit", "LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
311
        ("lilt", "LILT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jason Phang's avatar
Jason Phang committed
312
        ("llama", "LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
313
        ("longformer", "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Daniel Stancl's avatar
Daniel Stancl committed
314
        ("longt5", "LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
315
316
317
        ("luke", "LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("lxmert", "LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("m2m_100", "M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
318
        ("markuplm", "MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Alara Dirik's avatar
Alara Dirik committed
319
        ("mask2former", "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
320
321
        ("maskformer", "MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("mbart", "MBART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Chan Woo Kim's avatar
Chan Woo Kim committed
322
        ("mctct", "MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
323
        ("mega", "MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
324
        ("megatron-bert", "MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
wangpeng's avatar
wangpeng committed
325
        ("mgp-str", "MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
326
        ("mobilenet_v1", "MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP"),
327
        ("mobilenet_v2", "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
328
        ("mobilevit", "MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Shehan Munasinghe's avatar
Shehan Munasinghe committed
329
        ("mobilevitv2", "MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
330
        ("mpnet", "MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Sanchit Gandhi's avatar
Sanchit Gandhi committed
331
        ("musicgen", "MUSICGEN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
StevenTang1998's avatar
StevenTang1998 committed
332
        ("mvp", "MVP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
333
        ("nat", "NAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
334
        ("nezha", "NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
335
        ("nllb-moe", "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
336
        ("nystromformer", "NYSTROMFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jitesh Jain's avatar
Jitesh Jain committed
337
        ("oneformer", "ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
338
        ("open-llama", "OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
339
340
        ("openai-gpt", "OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("opt", "OPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
341
        ("owlvit", "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
342
        ("pegasus", "PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jason Phang's avatar
Jason Phang committed
343
        ("pegasus_x", "PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP"),
344
        ("perceiver", "PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Younes Belkada's avatar
Younes Belkada committed
345
        ("pix2struct", "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
346
347
348
349
350
351
352
353
354
355
        ("plbart", "PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("poolformer", "POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("prophetnet", "PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("qdqbert", "QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("realm", "REALM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("regnet", "REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("rembert", "REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("resnet", "RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("retribert", "RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("roberta", "ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
356
        ("roberta-prelayernorm", "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Weiwe Shi's avatar
Weiwe Shi committed
357
        ("roc_bert", "ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
358
        ("roformer", "ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Sylvain Gugger's avatar
Sylvain Gugger committed
359
        ("rwkv", "RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP"),
360
        ("sam", "SAM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
361
        ("segformer", "SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
362
        ("sew", "SEW_PRETRAINED_CONFIG_ARCHIVE_MAP"),
363
364
365
        ("sew-d", "SEW_D_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("speech_to_text", "SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("speech_to_text_2", "SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
366
        ("speecht5", "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
367
368
        ("splinter", "SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("squeezebert", "SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Shehan Munasinghe's avatar
Shehan Munasinghe committed
369
        ("swiftformer", "SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
370
        ("swin", "SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
371
        ("swin2sr", "SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
372
        ("swinv2", "SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
373
        ("switch_transformers", "SWITCH_TRANSFORMERS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
374
        ("t5", "T5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
375
        ("table-transformer", "TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
376
        ("tapas", "TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
377
        ("time_series_transformer", "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
378
        ("timesformer", "TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
379
        ("transfo-xl", "TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Zineng Tang's avatar
Zineng Tang committed
380
        ("tvlt", "TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
381
        ("unispeech", "UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP"),
382
383
        ("unispeech-sat", "UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("van", "VAN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
384
        ("videomae", "VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
385
386
387
        ("vilt", "VILT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("visual_bert", "VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("vit", "VIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
388
        ("vit_hybrid", "VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP"),
389
        ("vit_mae", "VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
390
        ("vit_msn", "VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
391
        ("wav2vec2", "WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
392
        ("wav2vec2-conformer", "WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
393
        ("whisper", "WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
394
        ("xclip", "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
395
396
397
398
399
        ("xglm", "XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("xlm", "XLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("xlm-prophetnet", "XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("xlm-roberta", "XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("xlnet", "XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jannis Vamvas's avatar
Jannis Vamvas committed
400
        ("xmod", "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP"),
401
402
        ("yolos", "YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("yoso", "YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
403
404
405
406
407
    ]
)

MODEL_NAMES_MAPPING = OrderedDict(
    [
408
        # Add full (and cased) model names here
409
        ("albert", "ALBERT"),
410
        ("align", "ALIGN"),
Jongjyh's avatar
Jongjyh committed
411
        ("altclip", "AltCLIP"),
412
        ("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
413
        ("autoformer", "Autoformer"),
414
415
416
        ("bart", "BART"),
        ("barthez", "BARThez"),
        ("bartpho", "BARTpho"),
NielsRogge's avatar
NielsRogge committed
417
        ("beit", "BEiT"),
418
419
420
        ("bert", "BERT"),
        ("bert-generation", "Bert Generation"),
        ("bert-japanese", "BertJapanese"),
421
        ("bertweet", "BERTweet"),
422
        ("big_bird", "BigBird"),
423
        ("bigbird_pegasus", "BigBird-Pegasus"),
Kamal Raj Kanakarajan's avatar
Kamal Raj Kanakarajan committed
424
        ("biogpt", "BioGpt"),
NielsRogge's avatar
NielsRogge committed
425
        ("bit", "BiT"),
426
427
        ("blenderbot", "Blenderbot"),
        ("blenderbot-small", "BlenderbotSmall"),
Younes Belkada's avatar
Younes Belkada committed
428
        ("blip", "BLIP"),
NielsRogge's avatar
NielsRogge committed
429
        ("blip-2", "BLIP-2"),
Younes Belkada's avatar
Younes Belkada committed
430
        ("bloom", "BLOOM"),
431
        ("bort", "BORT"),
432
        ("bridgetower", "BridgeTower"),
433
434
        ("byt5", "ByT5"),
        ("camembert", "CamemBERT"),
435
        ("canine", "CANINE"),
436
        ("chinese_clip", "Chinese-CLIP"),
437
        ("clap", "CLAP"),
Suraj Patil's avatar
Suraj Patil committed
438
        ("clip", "CLIP"),
NielsRogge's avatar
NielsRogge committed
439
        ("clipseg", "CLIPSeg"),
rooa's avatar
rooa committed
440
        ("codegen", "CodeGen"),
441
        ("conditional_detr", "Conditional DETR"),
442
        ("convbert", "ConvBERT"),
443
        ("convnext", "ConvNeXT"),
Alara Dirik's avatar
Alara Dirik committed
444
        ("convnextv2", "ConvNeXTV2"),
445
        ("cpm", "CPM"),
446
        ("cpmant", "CPM-Ant"),
447
        ("ctrl", "CTRL"),
NielsRogge's avatar
NielsRogge committed
448
        ("cvt", "CvT"),
449
450
451
452
453
454
        ("data2vec-audio", "Data2VecAudio"),
        ("data2vec-text", "Data2VecText"),
        ("data2vec-vision", "Data2VecVision"),
        ("deberta", "DeBERTa"),
        ("deberta-v2", "DeBERTa-v2"),
        ("decision_transformer", "Decision Transformer"),
NielsRogge's avatar
NielsRogge committed
455
        ("deformable_detr", "Deformable DETR"),
NielsRogge's avatar
NielsRogge committed
456
        ("deit", "DeiT"),
457
        ("deplot", "DePlot"),
NielsRogge's avatar
NielsRogge committed
458
        ("deta", "DETA"),
NielsRogge's avatar
NielsRogge committed
459
        ("detr", "DETR"),
460
        ("dialogpt", "DialoGPT"),
461
        ("dinat", "DiNAT"),
462
463
        ("distilbert", "DistilBERT"),
        ("dit", "DiT"),
NielsRogge's avatar
NielsRogge committed
464
        ("donut-swin", "DonutSwin"),
465
466
        ("dpr", "DPR"),
        ("dpt", "DPT"),
467
        ("efficientformer", "EfficientFormer"),
Alara Dirik's avatar
Alara Dirik committed
468
        ("efficientnet", "EfficientNet"),
469
        ("electra", "ELECTRA"),
470
        ("encodec", "EnCodec"),
471
        ("encoder-decoder", "Encoder decoder"),
472
        ("ernie", "ERNIE"),
473
        ("ernie_m", "ErnieM"),
474
        ("esm", "ESM"),
475
        ("flan-t5", "FLAN-T5"),
Arthur's avatar
Arthur committed
476
        ("flan-ul2", "FLAN-UL2"),
477
        ("flaubert", "FlauBERT"),
478
        ("flava", "FLAVA"),
479
        ("fnet", "FNet"),
NielsRogge's avatar
NielsRogge committed
480
        ("focalnet", "FocalNet"),
481
482
        ("fsmt", "FairSeq Machine-Translation"),
        ("funnel", "Funnel Transformer"),
483
        ("git", "GIT"),
484
        ("glpn", "GLPN"),
485
        ("gpt-sw3", "GPT-Sw3"),
486
        ("gpt2", "OpenAI GPT-2"),
487
        ("gpt_bigcode", "GPTBigCode"),
Suraj Patil's avatar
Suraj Patil committed
488
        ("gpt_neo", "GPT Neo"),
489
        ("gpt_neox", "GPT NeoX"),
490
        ("gpt_neox_japanese", "GPT NeoX Japanese"),
491
        ("gptj", "GPT-J"),
492
        ("gptsan-japanese", "GPTSAN-japanese"),
493
        ("graphormer", "Graphormer"),
494
        ("groupvit", "GroupViT"),
495
496
        ("herbert", "HerBERT"),
        ("hubert", "Hubert"),
Sehoon Kim's avatar
Sehoon Kim committed
497
        ("ibert", "I-BERT"),
498
        ("imagegpt", "ImageGPT"),
499
        ("informer", "Informer"),
NielsRogge's avatar
NielsRogge committed
500
        ("instructblip", "InstructBLIP"),
501
        ("jukebox", "Jukebox"),
502
503
        ("layoutlm", "LayoutLM"),
        ("layoutlmv2", "LayoutLMv2"),
NielsRogge's avatar
NielsRogge committed
504
        ("layoutlmv3", "LayoutLMv3"),
505
506
        ("layoutxlm", "LayoutXLM"),
        ("led", "LED"),
507
        ("levit", "LeViT"),
NielsRogge's avatar
NielsRogge committed
508
        ("lilt", "LiLT"),
Jason Phang's avatar
Jason Phang committed
509
        ("llama", "LLaMA"),
510
        ("longformer", "Longformer"),
Daniel Stancl's avatar
Daniel Stancl committed
511
        ("longt5", "LongT5"),
512
513
514
        ("luke", "LUKE"),
        ("lxmert", "LXMERT"),
        ("m2m_100", "M2M100"),
515
        ("marian", "Marian"),
NielsRogge's avatar
NielsRogge committed
516
        ("markuplm", "MarkupLM"),
Alara Dirik's avatar
Alara Dirik committed
517
        ("mask2former", "Mask2Former"),
518
        ("maskformer", "MaskFormer"),
519
        ("maskformer-swin", "MaskFormerSwin"),
520
        ("matcha", "MatCha"),
521
        ("mbart", "mBART"),
522
        ("mbart50", "mBART-50"),
Chan Woo Kim's avatar
Chan Woo Kim committed
523
        ("mctct", "M-CTC-T"),
524
        ("mega", "MEGA"),
525
526
        ("megatron-bert", "Megatron-BERT"),
        ("megatron_gpt2", "Megatron-GPT2"),
wangpeng's avatar
wangpeng committed
527
        ("mgp-str", "MGP-STR"),
528
        ("mluke", "mLUKE"),
529
        ("mms", "MMS"),
530
        ("mobilebert", "MobileBERT"),
531
        ("mobilenet_v1", "MobileNetV1"),
532
        ("mobilenet_v2", "MobileNetV2"),
533
        ("mobilevit", "MobileViT"),
Shehan Munasinghe's avatar
Shehan Munasinghe committed
534
        ("mobilevitv2", "MobileViTV2"),
535
        ("mpnet", "MPNet"),
536
        ("mt5", "MT5"),
Sanchit Gandhi's avatar
Sanchit Gandhi committed
537
        ("musicgen", "MusicGen"),
StevenTang1998's avatar
StevenTang1998 committed
538
        ("mvp", "MVP"),
539
        ("nat", "NAT"),
540
        ("nezha", "Nezha"),
Lysandre Debut's avatar
Lysandre Debut committed
541
        ("nllb", "NLLB"),
542
        ("nllb-moe", "NLLB-MOE"),
543
        ("nystromformer", "Nystr枚mformer"),
Jitesh Jain's avatar
Jitesh Jain committed
544
        ("oneformer", "OneFormer"),
545
        ("open-llama", "OpenLlama"),
546
        ("openai-gpt", "OpenAI GPT"),
Younes Belkada's avatar
Younes Belkada committed
547
        ("opt", "OPT"),
548
        ("owlvit", "OWL-ViT"),
549
        ("pegasus", "Pegasus"),
Jason Phang's avatar
Jason Phang committed
550
        ("pegasus_x", "PEGASUS-X"),
551
552
        ("perceiver", "Perceiver"),
        ("phobert", "PhoBERT"),
Younes Belkada's avatar
Younes Belkada committed
553
        ("pix2struct", "Pix2Struct"),
554
555
556
557
558
        ("plbart", "PLBart"),
        ("poolformer", "PoolFormer"),
        ("prophetnet", "ProphetNet"),
        ("qdqbert", "QDQBert"),
        ("rag", "RAG"),
559
        ("realm", "REALM"),
560
        ("reformer", "Reformer"),
561
562
563
564
        ("regnet", "RegNet"),
        ("rembert", "RemBERT"),
        ("resnet", "ResNet"),
        ("retribert", "RetriBERT"),
565
        ("roberta", "RoBERTa"),
566
        ("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
Weiwe Shi's avatar
Weiwe Shi committed
567
        ("roc_bert", "RoCBert"),
568
        ("roformer", "RoFormer"),
Sylvain Gugger's avatar
Sylvain Gugger committed
569
        ("rwkv", "RWKV"),
570
        ("sam", "SAM"),
571
572
573
        ("segformer", "SegFormer"),
        ("sew", "SEW"),
        ("sew-d", "SEW-D"),
574
        ("speech-encoder-decoder", "Speech Encoder decoder"),
575
576
        ("speech_to_text", "Speech2Text"),
        ("speech_to_text_2", "Speech2Text2"),
577
        ("speecht5", "SpeechT5"),
Ori Ram's avatar
Ori Ram committed
578
        ("splinter", "Splinter"),
579
        ("squeezebert", "SqueezeBERT"),
Shehan Munasinghe's avatar
Shehan Munasinghe committed
580
        ("swiftformer", "SwiftFormer"),
581
        ("swin", "Swin Transformer"),
NielsRogge's avatar
NielsRogge committed
582
        ("swin2sr", "Swin2SR"),
583
        ("swinv2", "Swin Transformer V2"),
584
        ("switch_transformers", "SwitchTransformers"),
585
586
        ("t5", "T5"),
        ("t5v1.1", "T5v1.1"),
587
        ("table-transformer", "Table Transformer"),
588
589
        ("tapas", "TAPAS"),
        ("tapex", "TAPEX"),
590
        ("time_series_transformer", "Time Series Transformer"),
591
        ("timesformer", "TimeSformer"),
amyeroberts's avatar
amyeroberts committed
592
        ("timm_backbone", "TimmBackbone"),
Carl's avatar
Carl committed
593
        ("trajectory_transformer", "Trajectory Transformer"),
594
595
        ("transfo-xl", "Transformer-XL"),
        ("trocr", "TrOCR"),
Zineng Tang's avatar
Zineng Tang committed
596
        ("tvlt", "TVLT"),
597
        ("ul2", "UL2"),
598
        ("unispeech", "UniSpeech"),
599
        ("unispeech-sat", "UniSpeechSat"),
NielsRogge's avatar
NielsRogge committed
600
        ("upernet", "UPerNet"),
601
        ("van", "VAN"),
NielsRogge's avatar
NielsRogge committed
602
        ("videomae", "VideoMAE"),
603
604
605
        ("vilt", "ViLT"),
        ("vision-encoder-decoder", "Vision Encoder decoder"),
        ("vision-text-dual-encoder", "VisionTextDualEncoder"),
606
        ("visual_bert", "VisualBERT"),
607
        ("vit", "ViT"),
NielsRogge's avatar
NielsRogge committed
608
        ("vit_hybrid", "ViT Hybrid"),
609
        ("vit_mae", "ViTMAE"),
610
        ("vit_msn", "ViTMSN"),
611
        ("wav2vec2", "Wav2Vec2"),
612
        ("wav2vec2-conformer", "Wav2Vec2-Conformer"),
613
        ("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
Patrick von Platen's avatar
Patrick von Platen committed
614
        ("wavlm", "WavLM"),
615
        ("whisper", "Whisper"),
NielsRogge's avatar
NielsRogge committed
616
        ("xclip", "X-CLIP"),
617
618
        ("xglm", "XGLM"),
        ("xlm", "XLM"),
619
        ("xlm-prophetnet", "XLM-ProphetNet"),
620
621
        ("xlm-roberta", "XLM-RoBERTa"),
        ("xlm-roberta-xl", "XLM-RoBERTa-XL"),
622
        ("xlm-v", "XLM-V"),
623
        ("xlnet", "XLNet"),
624
625
        ("xls_r", "XLS-R"),
        ("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
Jannis Vamvas's avatar
Jannis Vamvas committed
626
        ("xmod", "X-MOD"),
627
628
        ("yolos", "YOLOS"),
        ("yoso", "YOSO"),
629
630
631
    ]
)

632
SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
633
634
635
636
637
    [
        ("openai-gpt", "openai"),
        ("data2vec-audio", "data2vec"),
        ("data2vec-text", "data2vec"),
        ("data2vec-vision", "data2vec"),
NielsRogge's avatar
NielsRogge committed
638
        ("donut-swin", "donut"),
639
        ("maskformer-swin", "maskformer"),
NielsRogge's avatar
NielsRogge committed
640
        ("xclip", "x_clip"),
641
    ]
642
)
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658


def model_type_to_module_name(key):
    """Converts a config key to the corresponding module."""
    # Special treatment
    if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME:
        return SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key]

    return key.replace("-", "_")


def config_class_to_model_type(config):
    """Converts a config class name to the corresponding model type"""
    for key, cls in CONFIG_MAPPING_NAMES.items():
        if cls == config:
            return key
659
660
661
662
    # if key not found check in extra content
    for key, cls in CONFIG_MAPPING._extra_content.items():
        if cls.__name__ == config:
            return key
663
664
665
666
667
668
669
670
671
672
    return None


class _LazyConfigMapping(OrderedDict):
    """
    A dictionary that lazily load its values when they are requested.
    """

    def __init__(self, mapping):
        self._mapping = mapping
673
        self._extra_content = {}
674
675
676
        self._modules = {}

    def __getitem__(self, key):
677
678
        if key in self._extra_content:
            return self._extra_content[key]
679
680
681
682
683
684
        if key not in self._mapping:
            raise KeyError(key)
        value = self._mapping[key]
        module_name = model_type_to_module_name(key)
        if module_name not in self._modules:
            self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
685
686
687
688
689
690
691
        if hasattr(self._modules[module_name], value):
            return getattr(self._modules[module_name], value)

        # Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the
        # object at the top level.
        transformers_module = importlib.import_module("transformers")
        return getattr(transformers_module, value)
692
693

    def keys(self):
694
        return list(self._mapping.keys()) + list(self._extra_content.keys())
695
696

    def values(self):
697
        return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values())
698

699
    def items(self):
700
        return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
701
702

    def __iter__(self):
703
        return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
704
705

    def __contains__(self, item):
706
707
708
709
710
711
712
713
714
        return item in self._mapping or item in self._extra_content

    def register(self, key, value):
        """
        Register a new configuration in this mapping.
        """
        if key in self._mapping.keys():
            raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.")
        self._extra_content[key] = value
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779


CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES)


class _LazyLoadAllMappings(OrderedDict):
    """
    A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values,
    etc.)

    Args:
        mapping: The mapping to load.
    """

    def __init__(self, mapping):
        self._mapping = mapping
        self._initialized = False
        self._data = {}

    def _initialize(self):
        if self._initialized:
            return
        warnings.warn(
            "ALL_PRETRAINED_CONFIG_ARCHIVE_MAP is deprecated and will be removed in v5 of Transformers. "
            "It does not contain all available model checkpoints, far from it. Checkout hf.co/models for that.",
            FutureWarning,
        )

        for model_type, map_name in self._mapping.items():
            module_name = model_type_to_module_name(model_type)
            module = importlib.import_module(f".{module_name}", "transformers.models")
            mapping = getattr(module, map_name)
            self._data.update(mapping)

        self._initialized = True

    def __getitem__(self, key):
        self._initialize()
        return self._data[key]

    def keys(self):
        self._initialize()
        return self._data.keys()

    def values(self):
        self._initialize()
        return self._data.values()

    def items(self):
        self._initialize()
        return self._data.keys()

    def __iter__(self):
        self._initialize()
        return iter(self._data)

    def __contains__(self, item):
        self._initialize()
        return item in self._data


ALL_PRETRAINED_CONFIG_ARCHIVE_MAP = _LazyLoadAllMappings(CONFIG_ARCHIVE_MAP_MAPPING_NAMES)


def _get_class_name(model_class: Union[str, List[str]]):
780
    if isinstance(model_class, (list, tuple)):
Stas Bekman's avatar
Stas Bekman committed
781
782
        return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
    return f"[`{model_class}`]"
783
784


785
786
787
788
789
def _list_model_options(indent, config_to_class=None, use_model_types=True):
    if config_to_class is None and not use_model_types:
        raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.")
    if use_model_types:
        if config_to_class is None:
Stas Bekman's avatar
Stas Bekman committed
790
            model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
791
792
        else:
            model_type_to_name = {
793
794
795
                model_type: _get_class_name(model_class)
                for model_type, model_class in config_to_class.items()
                if model_type in MODEL_NAMES_MAPPING
796
797
            }
        lines = [
798
            f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
799
            for model_type in sorted(model_type_to_name.keys())
800
801
        ]
    else:
802
803
804
805
806
        config_to_name = {
            CONFIG_MAPPING_NAMES[config]: _get_class_name(clas)
            for config, clas in config_to_class.items()
            if config in CONFIG_MAPPING_NAMES
        }
807
        config_to_model_name = {
808
            config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
809
810
        }
        lines = [
Sylvain Gugger's avatar
Sylvain Gugger committed
811
812
            f"{indent}- [`{config_name}`] configuration class:"
            f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
813
            for config_name in sorted(config_to_name.keys())
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        ]
    return "\n".join(lines)


def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True):
    def docstring_decorator(fn):
        docstrings = fn.__doc__
        lines = docstrings.split("\n")
        i = 0
        while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None:
            i += 1
        if i < len(lines):
            indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
            if use_model_types:
                indent = f"{indent}    "
            lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
            docstrings = "\n".join(lines)
        else:
            raise ValueError(
Sylvain Gugger's avatar
Sylvain Gugger committed
833
834
                f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
                f" docstring is:\n{docstrings}"
835
836
837
838
839
840
841
            )
        fn.__doc__ = docstrings
        return fn

    return docstring_decorator


Julien Chaumond's avatar
Julien Chaumond committed
842
class AutoConfig:
Lysandre Debut's avatar
Lysandre Debut committed
843
    r"""
844
    This is a generic configuration class that will be instantiated as one of the configuration classes of the library
845
    when created with the [`~AutoConfig.from_pretrained`] class method.
846

847
    This class cannot be instantiated directly using `__init__()` (throws an error).
848
    """
849

850
    def __init__(self):
851
852
853
854
        raise EnvironmentError(
            "AutoConfig is designed to be instantiated "
            "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
        )
855

856
    @classmethod
857
858
859
860
    def for_model(cls, model_type: str, *args, **kwargs):
        if model_type in CONFIG_MAPPING:
            config_class = CONFIG_MAPPING[model_type]
            return config_class(*args, **kwargs)
861
        raise ValueError(
862
            f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
863
        )
864

865
    @classmethod
866
    @replace_list_option_in_docstrings()
867
    def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
868
869
        r"""
        Instantiate one of the configuration classes of the library from a pretrained model configuration.
870

Sylvain Gugger's avatar
Sylvain Gugger committed
871
872
        The configuration class to instantiate is selected based on the `model_type` property of the config object that
        is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
873

874
        List options
Lysandre Debut's avatar
Lysandre Debut committed
875
876

        Args:
877
            pretrained_model_name_or_path (`str` or `os.PathLike`):
878
879
                Can be either:

880
881
882
883
                    - A string, the *model id* of a pretrained model configuration hosted inside a model repo on
                      huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
                      namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
                    - A path to a *directory* containing a configuration file saved using the
Sylvain Gugger's avatar
Sylvain Gugger committed
884
885
                      [`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
                      e.g., `./my_model_directory/`.
886
887
888
                    - A path or url to a saved configuration JSON *file*, e.g.,
                      `./my_model_directory/configuration.json`.
            cache_dir (`str` or `os.PathLike`, *optional*):
889
890
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
891
            force_download (`bool`, *optional*, defaults to `False`):
892
893
                Whether or not to force the (re-)download the model weights and configuration files and override the
                cached versions if they exist.
894
            resume_download (`bool`, *optional*, defaults to `False`):
895
896
                Whether or not to delete incompletely received files. Will attempt to resume the download if such a
                file exists.
897
            proxies (`Dict[str, str]`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
898
899
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
900
            revision (`str`, *optional*, defaults to `"main"`):
Julien Chaumond's avatar
Julien Chaumond committed
901
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
902
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
Julien Chaumond's avatar
Julien Chaumond committed
903
                identifier allowed by git.
904
905
            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                If `False`, then this function returns just the final configuration object.
906

Sylvain Gugger's avatar
Sylvain Gugger committed
907
908
909
                If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
                dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
                part of `kwargs` which has not been used to update `config` and is otherwise ignored.
910
            trust_remote_code (`bool`, *optional*, defaults to `False`):
911
                Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
Sylvain Gugger's avatar
Sylvain Gugger committed
912
913
                should only be set to `True` for repositories you trust and in which you have read the code, as it will
                execute code present on the Hub on your local machine.
914
            kwargs(additional keyword arguments, *optional*):
915
                The values in kwargs of any keys which are configuration attributes will be used to override the loaded
Sylvain Gugger's avatar
Sylvain Gugger committed
916
                values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
917
                by the `return_unused_kwargs` keyword parameter.
Lysandre Debut's avatar
Lysandre Debut committed
918

919
        Examples:
920

921
922
        ```python
        >>> from transformers import AutoConfig
923

924
        >>> # Download configuration from huggingface.co and cache.
Sylvain Gugger's avatar
Sylvain Gugger committed
925
        >>> config = AutoConfig.from_pretrained("bert-base-uncased")
Lysandre Debut's avatar
Lysandre Debut committed
926

927
        >>> # Download configuration from huggingface.co (user-uploaded) and cache.
Sylvain Gugger's avatar
Sylvain Gugger committed
928
        >>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
Lysandre Debut's avatar
Lysandre Debut committed
929

930
        >>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
Sylvain Gugger's avatar
Sylvain Gugger committed
931
        >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
932

933
        >>> # Load a specific configuration file.
Sylvain Gugger's avatar
Sylvain Gugger committed
934
        >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
935

936
        >>> # Change some config attributes when loading a pretrained config.
Sylvain Gugger's avatar
Sylvain Gugger committed
937
        >>> config = AutoConfig.from_pretrained("bert-base-uncased", output_attentions=True, foo=False)
938
939
        >>> config.output_attentions
        True
Sylvain Gugger's avatar
Sylvain Gugger committed
940
941
942
943

        >>> config, unused_kwargs = AutoConfig.from_pretrained(
        ...     "bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
        ... )
944
945
        >>> config.output_attentions
        True
Sylvain Gugger's avatar
Sylvain Gugger committed
946

947
        >>> unused_kwargs
948
949
        {'foo': False}
        ```"""
950
        kwargs["_from_auto"] = True
951
        kwargs["name_or_path"] = pretrained_model_name_or_path
952
        trust_remote_code = kwargs.pop("trust_remote_code", None)
953
        config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
954
955
956
957
958
959
960
        has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]
        has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING
        trust_remote_code = resolve_trust_remote_code(
            trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
        )

        if has_remote_code and trust_remote_code:
961
            class_ref = config_dict["auto_map"]["AutoConfig"]
962
            config_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
963
            _ = kwargs.pop("code_revision", None)
964
965
            return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
        elif "model_type" in config_dict:
966
            config_class = CONFIG_MAPPING[config_dict["model_type"]]
967
            return config_class.from_dict(config_dict, **unused_kwargs)
968
969
        else:
            # Fallback: use pattern matching on the string.
970
971
            # We go from longer names to shorter names to catch roberta before bert (for instance)
            for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True):
972
                if pattern in str(pretrained_model_name_or_path):
973
                    return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
974

975
        raise ValueError(
976
            f"Unrecognized model in {pretrained_model_name_or_path}. "
977
            f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
978
            f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
979
        )
980
981
982
983
984
985
986

    @staticmethod
    def register(model_type, config):
        """
        Register a new configuration for this class.

        Args:
987
988
            model_type (`str`): The model type like "bert" or "gpt".
            config ([`PretrainedConfig`]): The config to register.
989
990
991
992
993
994
995
996
        """
        if issubclass(config, PretrainedConfig) and config.model_type != model_type:
            raise ValueError(
                "The config you are passing has a `model_type` attribute that is not consistent with the model type "
                f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they "
                "match!"
            )
        CONFIG_MAPPING.register(model_type, config)