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

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

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

515
SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
516
517
518
519
520
    [
        ("openai-gpt", "openai"),
        ("data2vec-audio", "data2vec"),
        ("data2vec-text", "data2vec"),
        ("data2vec-vision", "data2vec"),
NielsRogge's avatar
NielsRogge committed
521
        ("donut-swin", "donut"),
522
        ("maskformer-swin", "maskformer"),
NielsRogge's avatar
NielsRogge committed
523
        ("xclip", "x_clip"),
524
    ]
525
)
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


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
552
        self._extra_content = {}
553
554
555
        self._modules = {}

    def __getitem__(self, key):
556
557
        if key in self._extra_content:
            return self._extra_content[key]
558
559
560
561
562
563
        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")
564
565
566
567
568
569
570
        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)
571
572

    def keys(self):
573
        return list(self._mapping.keys()) + list(self._extra_content.keys())
574
575

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

578
    def items(self):
579
        return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
580
581

    def __iter__(self):
582
        return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
583
584

    def __contains__(self, item):
585
586
587
588
589
590
591
592
593
        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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658


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


664
665
666
667
668
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
669
            model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
670
671
        else:
            model_type_to_name = {
672
673
674
                model_type: _get_class_name(model_class)
                for model_type, model_class in config_to_class.items()
                if model_type in MODEL_NAMES_MAPPING
675
676
            }
        lines = [
677
            f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
678
            for model_type in sorted(model_type_to_name.keys())
679
680
        ]
    else:
681
682
683
684
685
        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
        }
686
        config_to_model_name = {
687
            config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
688
689
        }
        lines = [
Sylvain Gugger's avatar
Sylvain Gugger committed
690
691
            f"{indent}- [`{config_name}`] configuration class:"
            f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
692
            for config_name in sorted(config_to_name.keys())
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
        ]
    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
712
713
                f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
                f" docstring is:\n{docstrings}"
714
715
716
717
718
719
720
            )
        fn.__doc__ = docstrings
        return fn

    return docstring_decorator


Julien Chaumond's avatar
Julien Chaumond committed
721
class AutoConfig:
Lysandre Debut's avatar
Lysandre Debut committed
722
    r"""
723
    This is a generic configuration class that will be instantiated as one of the configuration classes of the library
724
    when created with the [`~AutoConfig.from_pretrained`] class method.
725

726
    This class cannot be instantiated directly using `__init__()` (throws an error).
727
    """
728

729
    def __init__(self):
730
731
732
733
        raise EnvironmentError(
            "AutoConfig is designed to be instantiated "
            "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
        )
734

735
    @classmethod
736
737
738
739
    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)
740
        raise ValueError(
741
            f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
742
        )
743

744
    @classmethod
745
    @replace_list_option_in_docstrings()
746
    def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
747
748
        r"""
        Instantiate one of the configuration classes of the library from a pretrained model configuration.
749

Sylvain Gugger's avatar
Sylvain Gugger committed
750
751
        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`:
752

753
        List options
Lysandre Debut's avatar
Lysandre Debut committed
754
755

        Args:
756
            pretrained_model_name_or_path (`str` or `os.PathLike`):
757
758
                Can be either:

759
760
761
762
                    - 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
763
764
                      [`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
                      e.g., `./my_model_directory/`.
765
766
767
                    - A path or url to a saved configuration JSON *file*, e.g.,
                      `./my_model_directory/configuration.json`.
            cache_dir (`str` or `os.PathLike`, *optional*):
768
769
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
770
            force_download (`bool`, *optional*, defaults to `False`):
771
772
                Whether or not to force the (re-)download the model weights and configuration files and override the
                cached versions if they exist.
773
            resume_download (`bool`, *optional*, defaults to `False`):
774
775
                Whether or not to delete incompletely received files. Will attempt to resume the download if such a
                file exists.
776
            proxies (`Dict[str, str]`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
777
778
                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.
779
            revision (`str`, *optional*, defaults to `"main"`):
Julien Chaumond's avatar
Julien Chaumond committed
780
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
781
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
Julien Chaumond's avatar
Julien Chaumond committed
782
                identifier allowed by git.
783
784
            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                If `False`, then this function returns just the final configuration object.
785

Sylvain Gugger's avatar
Sylvain Gugger committed
786
787
788
                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.
789
            trust_remote_code (`bool`, *optional*, defaults to `False`):
790
                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
791
792
                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.
793
            kwargs(additional keyword arguments, *optional*):
794
                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
795
                values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
796
                by the `return_unused_kwargs` keyword parameter.
Lysandre Debut's avatar
Lysandre Debut committed
797

798
        Examples:
799

800
801
        ```python
        >>> from transformers import AutoConfig
802

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

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

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

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

815
        >>> # Change some config attributes when loading a pretrained config.
Sylvain Gugger's avatar
Sylvain Gugger committed
816
        >>> config = AutoConfig.from_pretrained("bert-base-uncased", output_attentions=True, foo=False)
817
818
        >>> config.output_attentions
        True
Sylvain Gugger's avatar
Sylvain Gugger committed
819
820
821
822

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

826
        >>> unused_kwargs
827
828
        {'foo': False}
        ```"""
829
        kwargs["_from_auto"] = True
830
831
        kwargs["name_or_path"] = pretrained_model_name_or_path
        trust_remote_code = kwargs.pop("trust_remote_code", False)
832
        config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
833
834
835
        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
836
837
838
                    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."
839
840
                )
            if kwargs.get("revision", None) is None:
841
                logger.warning(
842
843
844
845
846
847
848
849
850
851
                    "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
            )
            return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
        elif "model_type" in config_dict:
852
            config_class = CONFIG_MAPPING[config_dict["model_type"]]
853
            return config_class.from_dict(config_dict, **unused_kwargs)
854
855
        else:
            # Fallback: use pattern matching on the string.
856
857
            # 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):
858
                if pattern in str(pretrained_model_name_or_path):
859
                    return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
860

861
        raise ValueError(
862
            f"Unrecognized model in {pretrained_model_name_or_path}. "
863
            f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
864
            f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
865
        )
866
867
868
869
870
871
872

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

        Args:
873
874
            model_type (`str`): The model type like "bert" or "gpt".
            config ([`PretrainedConfig`]): The config to register.
875
876
877
878
879
880
881
882
        """
        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)