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

203
CONFIG_ARCHIVE_MAP_MAPPING_NAMES = OrderedDict(
204
    [
NielsRogge's avatar
NielsRogge committed
205
        # Add archive maps here)
206
        ("albert", "ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jongjyh's avatar
Jongjyh committed
207
        ("altclip", "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
208
        ("audio-spectrogram-transformer", "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
209
        ("bart", "BART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
210
        ("beit", "BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
211
212
213
        ("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
214
        ("biogpt", "BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
215
        ("bit", "BIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
216
217
        ("blenderbot", "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("blenderbot-small", "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Younes Belkada's avatar
Younes Belkada committed
218
        ("blip", "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
219
        ("blip-2", "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Younes Belkada's avatar
Younes Belkada committed
220
        ("bloom", "BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
221
        ("bridgetower", "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
222
        ("camembert", "CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
223
        ("canine", "CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
224
        ("chinese_clip", "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
225
        ("clip", "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
226
        ("clipseg", "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP"),
rooa's avatar
rooa committed
227
        ("codegen", "CODEGEN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
228
        ("conditional_detr", "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
229
        ("convbert", "CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
230
        ("convnext", "CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
231
        ("ctrl", "CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
232
        ("cvt", "CVT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
233
        ("data2vec-audio", "DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
234
235
236
237
        ("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
238
        ("deformable_detr", "DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
239
        ("deit", "DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
240
        ("deta", "DETA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
241
        ("detr", "DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
242
        ("dinat", "DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
243
        ("distilbert", "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
244
        ("donut-swin", "DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
245
246
        ("dpr", "DPR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("dpt", "DPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
247
        ("efficientformer", "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
248
        ("electra", "ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
249
        ("ernie", "ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
250
        ("ernie_m", "ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP"),
251
        ("esm", "ESM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
252
        ("flaubert", "FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
253
254
        ("flava", "FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("fnet", "FNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
255
256
        ("fsmt", "FSMT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("funnel", "FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
257
        ("git", "GIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
258
259
260
        ("glpn", "GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("gpt2", "GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("gpt_neo", "GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
261
        ("gpt_neox", "GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP"),
262
        ("gpt_neox_japanese", "GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
263
        ("gptj", "GPTJ_PRETRAINED_CONFIG_ARCHIVE_MAP"),
264
        ("graphormer", "GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
265
        ("groupvit", "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
266
267
268
        ("hubert", "HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("ibert", "IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("imagegpt", "IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
269
        ("jukebox", "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP"),
270
        ("layoutlm", "LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
271
        ("layoutlmv2", "LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
272
        ("layoutlmv3", "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP"),
273
        ("led", "LED_PRETRAINED_CONFIG_ARCHIVE_MAP"),
274
        ("levit", "LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
275
        ("lilt", "LILT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
276
        ("longformer", "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Daniel Stancl's avatar
Daniel Stancl committed
277
        ("longt5", "LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
278
279
280
        ("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
281
        ("markuplm", "MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Alara Dirik's avatar
Alara Dirik committed
282
        ("mask2former", "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
283
284
        ("maskformer", "MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("mbart", "MBART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Chan Woo Kim's avatar
Chan Woo Kim committed
285
        ("mctct", "MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
286
        ("megatron-bert", "MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
287
        ("mobilenet_v1", "MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP"),
288
        ("mobilenet_v2", "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
289
        ("mobilevit", "MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
290
        ("mpnet", "MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
StevenTang1998's avatar
StevenTang1998 committed
291
        ("mvp", "MVP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
292
        ("nat", "NAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
293
        ("nezha", "NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
294
        ("nystromformer", "NYSTROMFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jitesh Jain's avatar
Jitesh Jain committed
295
        ("oneformer", "ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
296
297
        ("openai-gpt", "OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("opt", "OPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
298
        ("owlvit", "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
299
        ("pegasus", "PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Jason Phang's avatar
Jason Phang committed
300
        ("pegasus_x", "PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP"),
301
302
303
304
305
306
307
308
309
310
311
        ("perceiver", "PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("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"),
312
        ("roberta-prelayernorm", "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Weiwe Shi's avatar
Weiwe Shi committed
313
        ("roc_bert", "ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
314
315
        ("roformer", "ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("segformer", "SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
316
        ("sew", "SEW_PRETRAINED_CONFIG_ARCHIVE_MAP"),
317
318
319
        ("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"),
320
        ("speecht5", "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
321
322
323
        ("splinter", "SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("squeezebert", "SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("swin", "SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
324
        ("swin2sr", "SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
325
        ("swinv2", "SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
326
        ("switch_transformers", "SWITCH_TRANSFORMERS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
327
        ("t5", "T5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
328
        ("table-transformer", "TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
329
        ("tapas", "TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
330
        ("time_series_transformer", "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
331
        ("timesformer", "TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
332
        ("transfo-xl", "TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
Zineng Tang's avatar
Zineng Tang committed
333
        ("tvlt", "TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
334
        ("unispeech", "UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP"),
335
336
        ("unispeech-sat", "UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("van", "VAN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
NielsRogge's avatar
NielsRogge committed
337
        ("videomae", "VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
338
339
340
        ("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
341
        ("vit_hybrid", "VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP"),
342
        ("vit_mae", "VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
343
        ("vit_msn", "VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
344
        ("wav2vec2", "WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
345
        ("wav2vec2-conformer", "WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
346
        ("whisper", "WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
347
        ("xclip", "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
348
349
350
351
352
        ("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
353
        ("xmod", "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP"),
354
355
        ("yolos", "YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
        ("yoso", "YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
356
357
358
359
360
    ]
)

MODEL_NAMES_MAPPING = OrderedDict(
    [
361
        # Add full (and cased) model names here
362
        ("albert", "ALBERT"),
Jongjyh's avatar
Jongjyh committed
363
        ("altclip", "AltCLIP"),
364
        ("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
365
366
367
        ("bart", "BART"),
        ("barthez", "BARThez"),
        ("bartpho", "BARTpho"),
NielsRogge's avatar
NielsRogge committed
368
        ("beit", "BEiT"),
369
370
371
        ("bert", "BERT"),
        ("bert-generation", "Bert Generation"),
        ("bert-japanese", "BertJapanese"),
372
        ("bertweet", "BERTweet"),
373
        ("big_bird", "BigBird"),
374
        ("bigbird_pegasus", "BigBird-Pegasus"),
Kamal Raj Kanakarajan's avatar
Kamal Raj Kanakarajan committed
375
        ("biogpt", "BioGpt"),
NielsRogge's avatar
NielsRogge committed
376
        ("bit", "BiT"),
377
378
        ("blenderbot", "Blenderbot"),
        ("blenderbot-small", "BlenderbotSmall"),
Younes Belkada's avatar
Younes Belkada committed
379
        ("blip", "BLIP"),
NielsRogge's avatar
NielsRogge committed
380
        ("blip-2", "BLIP-2"),
Younes Belkada's avatar
Younes Belkada committed
381
        ("bloom", "BLOOM"),
382
        ("bort", "BORT"),
383
        ("bridgetower", "BridgeTower"),
384
385
        ("byt5", "ByT5"),
        ("camembert", "CamemBERT"),
386
        ("canine", "CANINE"),
387
        ("chinese_clip", "Chinese-CLIP"),
Suraj Patil's avatar
Suraj Patil committed
388
        ("clip", "CLIP"),
NielsRogge's avatar
NielsRogge committed
389
        ("clipseg", "CLIPSeg"),
rooa's avatar
rooa committed
390
        ("codegen", "CodeGen"),
391
        ("conditional_detr", "Conditional DETR"),
392
        ("convbert", "ConvBERT"),
393
        ("convnext", "ConvNeXT"),
394
395
        ("cpm", "CPM"),
        ("ctrl", "CTRL"),
NielsRogge's avatar
NielsRogge committed
396
        ("cvt", "CvT"),
397
398
399
400
401
402
        ("data2vec-audio", "Data2VecAudio"),
        ("data2vec-text", "Data2VecText"),
        ("data2vec-vision", "Data2VecVision"),
        ("deberta", "DeBERTa"),
        ("deberta-v2", "DeBERTa-v2"),
        ("decision_transformer", "Decision Transformer"),
NielsRogge's avatar
NielsRogge committed
403
        ("deformable_detr", "Deformable DETR"),
NielsRogge's avatar
NielsRogge committed
404
        ("deit", "DeiT"),
NielsRogge's avatar
NielsRogge committed
405
        ("deta", "DETA"),
NielsRogge's avatar
NielsRogge committed
406
        ("detr", "DETR"),
407
        ("dialogpt", "DialoGPT"),
408
        ("dinat", "DiNAT"),
409
410
        ("distilbert", "DistilBERT"),
        ("dit", "DiT"),
NielsRogge's avatar
NielsRogge committed
411
        ("donut-swin", "DonutSwin"),
412
413
        ("dpr", "DPR"),
        ("dpt", "DPT"),
414
        ("efficientformer", "EfficientFormer"),
415
416
        ("electra", "ELECTRA"),
        ("encoder-decoder", "Encoder decoder"),
417
        ("ernie", "ERNIE"),
418
        ("ernie_m", "ErnieM"),
419
        ("esm", "ESM"),
420
        ("flan-t5", "FLAN-T5"),
421
        ("flaubert", "FlauBERT"),
422
        ("flava", "FLAVA"),
423
424
425
        ("fnet", "FNet"),
        ("fsmt", "FairSeq Machine-Translation"),
        ("funnel", "Funnel Transformer"),
426
        ("git", "GIT"),
427
        ("glpn", "GLPN"),
428
        ("gpt-sw3", "GPT-Sw3"),
429
        ("gpt2", "OpenAI GPT-2"),
Suraj Patil's avatar
Suraj Patil committed
430
        ("gpt_neo", "GPT Neo"),
431
        ("gpt_neox", "GPT NeoX"),
432
        ("gpt_neox_japanese", "GPT NeoX Japanese"),
433
        ("gptj", "GPT-J"),
434
        ("graphormer", "Graphormer"),
435
        ("groupvit", "GroupViT"),
436
437
        ("herbert", "HerBERT"),
        ("hubert", "Hubert"),
Sehoon Kim's avatar
Sehoon Kim committed
438
        ("ibert", "I-BERT"),
439
        ("imagegpt", "ImageGPT"),
440
        ("jukebox", "Jukebox"),
441
442
        ("layoutlm", "LayoutLM"),
        ("layoutlmv2", "LayoutLMv2"),
NielsRogge's avatar
NielsRogge committed
443
        ("layoutlmv3", "LayoutLMv3"),
444
445
        ("layoutxlm", "LayoutXLM"),
        ("led", "LED"),
446
        ("levit", "LeViT"),
NielsRogge's avatar
NielsRogge committed
447
        ("lilt", "LiLT"),
448
        ("longformer", "Longformer"),
Daniel Stancl's avatar
Daniel Stancl committed
449
        ("longt5", "LongT5"),
450
451
452
        ("luke", "LUKE"),
        ("lxmert", "LXMERT"),
        ("m2m_100", "M2M100"),
453
        ("marian", "Marian"),
NielsRogge's avatar
NielsRogge committed
454
        ("markuplm", "MarkupLM"),
Alara Dirik's avatar
Alara Dirik committed
455
        ("mask2former", "Mask2Former"),
456
        ("maskformer", "MaskFormer"),
457
        ("maskformer-swin", "MaskFormerSwin"),
458
        ("mbart", "mBART"),
459
        ("mbart50", "mBART-50"),
Chan Woo Kim's avatar
Chan Woo Kim committed
460
        ("mctct", "M-CTC-T"),
461
462
        ("megatron-bert", "Megatron-BERT"),
        ("megatron_gpt2", "Megatron-GPT2"),
463
464
        ("mluke", "mLUKE"),
        ("mobilebert", "MobileBERT"),
465
        ("mobilenet_v1", "MobileNetV1"),
466
        ("mobilenet_v2", "MobileNetV2"),
467
        ("mobilevit", "MobileViT"),
468
        ("mpnet", "MPNet"),
469
        ("mt5", "MT5"),
StevenTang1998's avatar
StevenTang1998 committed
470
        ("mvp", "MVP"),
471
        ("nat", "NAT"),
472
        ("nezha", "Nezha"),
Lysandre Debut's avatar
Lysandre Debut committed
473
        ("nllb", "NLLB"),
474
        ("nystromformer", "Nystr枚mformer"),
Jitesh Jain's avatar
Jitesh Jain committed
475
        ("oneformer", "OneFormer"),
476
        ("openai-gpt", "OpenAI GPT"),
Younes Belkada's avatar
Younes Belkada committed
477
        ("opt", "OPT"),
478
        ("owlvit", "OWL-ViT"),
479
        ("pegasus", "Pegasus"),
Jason Phang's avatar
Jason Phang committed
480
        ("pegasus_x", "PEGASUS-X"),
481
482
483
484
485
486
487
        ("perceiver", "Perceiver"),
        ("phobert", "PhoBERT"),
        ("plbart", "PLBart"),
        ("poolformer", "PoolFormer"),
        ("prophetnet", "ProphetNet"),
        ("qdqbert", "QDQBert"),
        ("rag", "RAG"),
488
        ("realm", "REALM"),
489
        ("reformer", "Reformer"),
490
491
492
493
        ("regnet", "RegNet"),
        ("rembert", "RemBERT"),
        ("resnet", "ResNet"),
        ("retribert", "RetriBERT"),
494
        ("roberta", "RoBERTa"),
495
        ("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
Weiwe Shi's avatar
Weiwe Shi committed
496
        ("roc_bert", "RoCBert"),
497
498
499
500
        ("roformer", "RoFormer"),
        ("segformer", "SegFormer"),
        ("sew", "SEW"),
        ("sew-d", "SEW-D"),
501
        ("speech-encoder-decoder", "Speech Encoder decoder"),
502
503
        ("speech_to_text", "Speech2Text"),
        ("speech_to_text_2", "Speech2Text2"),
504
        ("speecht5", "SpeechT5"),
Ori Ram's avatar
Ori Ram committed
505
        ("splinter", "Splinter"),
506
        ("squeezebert", "SqueezeBERT"),
507
        ("swin", "Swin Transformer"),
NielsRogge's avatar
NielsRogge committed
508
        ("swin2sr", "Swin2SR"),
509
        ("swinv2", "Swin Transformer V2"),
510
        ("switch_transformers", "SwitchTransformers"),
511
512
        ("t5", "T5"),
        ("t5v1.1", "T5v1.1"),
513
        ("table-transformer", "Table Transformer"),
514
515
        ("tapas", "TAPAS"),
        ("tapex", "TAPEX"),
516
        ("time_series_transformer", "Time Series Transformer"),
517
        ("timesformer", "TimeSformer"),
Carl's avatar
Carl committed
518
        ("trajectory_transformer", "Trajectory Transformer"),
519
520
        ("transfo-xl", "Transformer-XL"),
        ("trocr", "TrOCR"),
Zineng Tang's avatar
Zineng Tang committed
521
        ("tvlt", "TVLT"),
522
        ("ul2", "UL2"),
523
        ("unispeech", "UniSpeech"),
524
        ("unispeech-sat", "UniSpeechSat"),
NielsRogge's avatar
NielsRogge committed
525
        ("upernet", "UPerNet"),
526
        ("van", "VAN"),
NielsRogge's avatar
NielsRogge committed
527
        ("videomae", "VideoMAE"),
528
529
530
        ("vilt", "ViLT"),
        ("vision-encoder-decoder", "Vision Encoder decoder"),
        ("vision-text-dual-encoder", "VisionTextDualEncoder"),
531
        ("visual_bert", "VisualBERT"),
532
        ("vit", "ViT"),
NielsRogge's avatar
NielsRogge committed
533
        ("vit_hybrid", "ViT Hybrid"),
534
        ("vit_mae", "ViTMAE"),
535
        ("vit_msn", "ViTMSN"),
536
        ("wav2vec2", "Wav2Vec2"),
537
        ("wav2vec2-conformer", "Wav2Vec2-Conformer"),
538
        ("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
Patrick von Platen's avatar
Patrick von Platen committed
539
        ("wavlm", "WavLM"),
540
        ("whisper", "Whisper"),
NielsRogge's avatar
NielsRogge committed
541
        ("xclip", "X-CLIP"),
542
543
        ("xglm", "XGLM"),
        ("xlm", "XLM"),
544
        ("xlm-prophetnet", "XLM-ProphetNet"),
545
546
        ("xlm-roberta", "XLM-RoBERTa"),
        ("xlm-roberta-xl", "XLM-RoBERTa-XL"),
547
        ("xlm-v", "XLM-V"),
548
        ("xlnet", "XLNet"),
549
550
        ("xls_r", "XLS-R"),
        ("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
Jannis Vamvas's avatar
Jannis Vamvas committed
551
        ("xmod", "X-MOD"),
552
553
        ("yolos", "YOLOS"),
        ("yoso", "YOSO"),
554
555
556
    ]
)

557
SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
558
559
560
561
562
    [
        ("openai-gpt", "openai"),
        ("data2vec-audio", "data2vec"),
        ("data2vec-text", "data2vec"),
        ("data2vec-vision", "data2vec"),
NielsRogge's avatar
NielsRogge committed
563
        ("donut-swin", "donut"),
564
        ("maskformer-swin", "maskformer"),
NielsRogge's avatar
NielsRogge committed
565
        ("xclip", "x_clip"),
566
    ]
567
)
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593


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
    return None


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

    def __init__(self, mapping):
        self._mapping = mapping
594
        self._extra_content = {}
595
596
597
        self._modules = {}

    def __getitem__(self, key):
598
599
        if key in self._extra_content:
            return self._extra_content[key]
600
601
602
603
604
605
        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")
606
607
608
609
610
611
612
        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)
613
614

    def keys(self):
615
        return list(self._mapping.keys()) + list(self._extra_content.keys())
616
617

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

620
    def items(self):
621
        return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
622
623

    def __iter__(self):
624
        return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
625
626

    def __contains__(self, item):
627
628
629
630
631
632
633
634
635
        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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700


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]]):
701
    if isinstance(model_class, (list, tuple)):
Stas Bekman's avatar
Stas Bekman committed
702
703
        return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
    return f"[`{model_class}`]"
704
705


706
707
708
709
710
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
711
            model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
712
713
        else:
            model_type_to_name = {
714
715
716
                model_type: _get_class_name(model_class)
                for model_type, model_class in config_to_class.items()
                if model_type in MODEL_NAMES_MAPPING
717
718
            }
        lines = [
719
            f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
720
            for model_type in sorted(model_type_to_name.keys())
721
722
        ]
    else:
723
724
725
726
727
        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
        }
728
        config_to_model_name = {
729
            config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
730
731
        }
        lines = [
Sylvain Gugger's avatar
Sylvain Gugger committed
732
733
            f"{indent}- [`{config_name}`] configuration class:"
            f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
734
            for config_name in sorted(config_to_name.keys())
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
        ]
    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
754
755
                f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
                f" docstring is:\n{docstrings}"
756
757
758
759
760
761
762
            )
        fn.__doc__ = docstrings
        return fn

    return docstring_decorator


Julien Chaumond's avatar
Julien Chaumond committed
763
class AutoConfig:
Lysandre Debut's avatar
Lysandre Debut committed
764
    r"""
765
    This is a generic configuration class that will be instantiated as one of the configuration classes of the library
766
    when created with the [`~AutoConfig.from_pretrained`] class method.
767

768
    This class cannot be instantiated directly using `__init__()` (throws an error).
769
    """
770

771
    def __init__(self):
772
773
774
775
        raise EnvironmentError(
            "AutoConfig is designed to be instantiated "
            "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
        )
776

777
    @classmethod
778
779
780
781
    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)
782
        raise ValueError(
783
            f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
784
        )
785

786
    @classmethod
787
    @replace_list_option_in_docstrings()
788
    def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
789
790
        r"""
        Instantiate one of the configuration classes of the library from a pretrained model configuration.
791

Sylvain Gugger's avatar
Sylvain Gugger committed
792
793
        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`:
794

795
        List options
Lysandre Debut's avatar
Lysandre Debut committed
796
797

        Args:
798
            pretrained_model_name_or_path (`str` or `os.PathLike`):
799
800
                Can be either:

801
802
803
804
                    - 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
805
806
                      [`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
                      e.g., `./my_model_directory/`.
807
808
809
                    - A path or url to a saved configuration JSON *file*, e.g.,
                      `./my_model_directory/configuration.json`.
            cache_dir (`str` or `os.PathLike`, *optional*):
810
811
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
812
            force_download (`bool`, *optional*, defaults to `False`):
813
814
                Whether or not to force the (re-)download the model weights and configuration files and override the
                cached versions if they exist.
815
            resume_download (`bool`, *optional*, defaults to `False`):
816
817
                Whether or not to delete incompletely received files. Will attempt to resume the download if such a
                file exists.
818
            proxies (`Dict[str, str]`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
819
820
                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.
821
            revision (`str`, *optional*, defaults to `"main"`):
Julien Chaumond's avatar
Julien Chaumond committed
822
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
823
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
Julien Chaumond's avatar
Julien Chaumond committed
824
                identifier allowed by git.
825
826
            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                If `False`, then this function returns just the final configuration object.
827

Sylvain Gugger's avatar
Sylvain Gugger committed
828
829
830
                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.
831
            trust_remote_code (`bool`, *optional*, defaults to `False`):
832
                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
833
834
                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.
835
            kwargs(additional keyword arguments, *optional*):
836
                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
837
                values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
838
                by the `return_unused_kwargs` keyword parameter.
Lysandre Debut's avatar
Lysandre Debut committed
839

840
        Examples:
841

842
843
        ```python
        >>> from transformers import AutoConfig
844

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

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

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

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

857
        >>> # Change some config attributes when loading a pretrained config.
Sylvain Gugger's avatar
Sylvain Gugger committed
858
        >>> config = AutoConfig.from_pretrained("bert-base-uncased", output_attentions=True, foo=False)
859
860
        >>> config.output_attentions
        True
Sylvain Gugger's avatar
Sylvain Gugger committed
861
862
863
864

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

868
        >>> unused_kwargs
869
870
        {'foo': False}
        ```"""
871
        kwargs["_from_auto"] = True
872
873
        kwargs["name_or_path"] = pretrained_model_name_or_path
        trust_remote_code = kwargs.pop("trust_remote_code", False)
874
        config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
875
876
877
        if "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]:
            if not trust_remote_code:
                raise ValueError(
Sylvain Gugger's avatar
Sylvain Gugger committed
878
879
880
                    f"Loading {pretrained_model_name_or_path} requires you to execute the configuration file in that"
                    " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
                    " set the option `trust_remote_code=True` to remove this error."
881
882
                )
            if kwargs.get("revision", None) is None:
883
                logger.warning(
884
885
886
887
888
889
890
891
                    "Explicitly passing a `revision` is encouraged when loading a configuration with custom code to "
                    "ensure no malicious code has been contributed in a newer revision."
                )
            class_ref = config_dict["auto_map"]["AutoConfig"]
            module_file, class_name = class_ref.split(".")
            config_class = get_class_from_dynamic_module(
                pretrained_model_name_or_path, module_file + ".py", class_name, **kwargs
            )
892
            config_class.register_for_auto_class()
893
894
            return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
        elif "model_type" in config_dict:
895
            config_class = CONFIG_MAPPING[config_dict["model_type"]]
896
            return config_class.from_dict(config_dict, **unused_kwargs)
897
898
        else:
            # Fallback: use pattern matching on the string.
899
900
            # 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):
901
                if pattern in str(pretrained_model_name_or_path):
902
                    return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
903

904
        raise ValueError(
905
            f"Unrecognized model in {pretrained_model_name_or_path}. "
906
            f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
907
            f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
908
        )
909
910
911
912
913
914
915

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

        Args:
916
917
            model_type (`str`): The model type like "bert" or "gpt".
            config ([`PretrainedConfig`]): The config to register.
918
919
920
921
922
923
924
925
        """
        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)