configuration_auto.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. # coding=utf-8
  2. # Copyright 2018 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Auto Config class."""
  16. import importlib
  17. import os
  18. import re
  19. import warnings
  20. from collections import OrderedDict
  21. from typing import List, Union
  22. from ...configuration_utils import PretrainedConfig
  23. from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
  24. from ...utils import CONFIG_NAME, logging
  25. logger = logging.get_logger(__name__)
  26. CONFIG_MAPPING_NAMES = OrderedDict(
  27. [
  28. # Add configs here
  29. ("albert", "AlbertConfig"),
  30. ("align", "AlignConfig"),
  31. ("altclip", "AltCLIPConfig"),
  32. ("audio-spectrogram-transformer", "ASTConfig"),
  33. ("autoformer", "AutoformerConfig"),
  34. ("bark", "BarkConfig"),
  35. ("bart", "BartConfig"),
  36. ("beit", "BeitConfig"),
  37. ("bert", "BertConfig"),
  38. ("bert-generation", "BertGenerationConfig"),
  39. ("big_bird", "BigBirdConfig"),
  40. ("bigbird_pegasus", "BigBirdPegasusConfig"),
  41. ("biogpt", "BioGptConfig"),
  42. ("bit", "BitConfig"),
  43. ("blenderbot", "BlenderbotConfig"),
  44. ("blenderbot-small", "BlenderbotSmallConfig"),
  45. ("blip", "BlipConfig"),
  46. ("blip-2", "Blip2Config"),
  47. ("bloom", "BloomConfig"),
  48. ("bridgetower", "BridgeTowerConfig"),
  49. ("bros", "BrosConfig"),
  50. ("camembert", "CamembertConfig"),
  51. ("canine", "CanineConfig"),
  52. ("chameleon", "ChameleonConfig"),
  53. ("chinese_clip", "ChineseCLIPConfig"),
  54. ("chinese_clip_vision_model", "ChineseCLIPVisionConfig"),
  55. ("clap", "ClapConfig"),
  56. ("clip", "CLIPConfig"),
  57. ("clip_text_model", "CLIPTextConfig"),
  58. ("clip_vision_model", "CLIPVisionConfig"),
  59. ("clipseg", "CLIPSegConfig"),
  60. ("clvp", "ClvpConfig"),
  61. ("code_llama", "LlamaConfig"),
  62. ("codegen", "CodeGenConfig"),
  63. ("cohere", "CohereConfig"),
  64. ("conditional_detr", "ConditionalDetrConfig"),
  65. ("convbert", "ConvBertConfig"),
  66. ("convnext", "ConvNextConfig"),
  67. ("convnextv2", "ConvNextV2Config"),
  68. ("cpmant", "CpmAntConfig"),
  69. ("ctrl", "CTRLConfig"),
  70. ("cvt", "CvtConfig"),
  71. ("dac", "DacConfig"),
  72. ("data2vec-audio", "Data2VecAudioConfig"),
  73. ("data2vec-text", "Data2VecTextConfig"),
  74. ("data2vec-vision", "Data2VecVisionConfig"),
  75. ("dbrx", "DbrxConfig"),
  76. ("deberta", "DebertaConfig"),
  77. ("deberta-v2", "DebertaV2Config"),
  78. ("decision_transformer", "DecisionTransformerConfig"),
  79. ("deformable_detr", "DeformableDetrConfig"),
  80. ("deit", "DeiTConfig"),
  81. ("depth_anything", "DepthAnythingConfig"),
  82. ("deta", "DetaConfig"),
  83. ("detr", "DetrConfig"),
  84. ("dinat", "DinatConfig"),
  85. ("dinov2", "Dinov2Config"),
  86. ("distilbert", "DistilBertConfig"),
  87. ("donut-swin", "DonutSwinConfig"),
  88. ("dpr", "DPRConfig"),
  89. ("dpt", "DPTConfig"),
  90. ("efficientformer", "EfficientFormerConfig"),
  91. ("efficientnet", "EfficientNetConfig"),
  92. ("electra", "ElectraConfig"),
  93. ("encodec", "EncodecConfig"),
  94. ("encoder-decoder", "EncoderDecoderConfig"),
  95. ("ernie", "ErnieConfig"),
  96. ("ernie_m", "ErnieMConfig"),
  97. ("esm", "EsmConfig"),
  98. ("falcon", "FalconConfig"),
  99. ("falcon_mamba", "FalconMambaConfig"),
  100. ("fastspeech2_conformer", "FastSpeech2ConformerConfig"),
  101. ("flaubert", "FlaubertConfig"),
  102. ("flava", "FlavaConfig"),
  103. ("fnet", "FNetConfig"),
  104. ("focalnet", "FocalNetConfig"),
  105. ("fsmt", "FSMTConfig"),
  106. ("funnel", "FunnelConfig"),
  107. ("fuyu", "FuyuConfig"),
  108. ("gemma", "GemmaConfig"),
  109. ("gemma2", "Gemma2Config"),
  110. ("git", "GitConfig"),
  111. ("glm", "GlmConfig"),
  112. ("glpn", "GLPNConfig"),
  113. ("gpt-sw3", "GPT2Config"),
  114. ("gpt2", "GPT2Config"),
  115. ("gpt_bigcode", "GPTBigCodeConfig"),
  116. ("gpt_neo", "GPTNeoConfig"),
  117. ("gpt_neox", "GPTNeoXConfig"),
  118. ("gpt_neox_japanese", "GPTNeoXJapaneseConfig"),
  119. ("gptj", "GPTJConfig"),
  120. ("gptsan-japanese", "GPTSanJapaneseConfig"),
  121. ("granite", "GraniteConfig"),
  122. ("granitemoe", "GraniteMoeConfig"),
  123. ("graphormer", "GraphormerConfig"),
  124. ("grounding-dino", "GroundingDinoConfig"),
  125. ("groupvit", "GroupViTConfig"),
  126. ("hiera", "HieraConfig"),
  127. ("hubert", "HubertConfig"),
  128. ("ibert", "IBertConfig"),
  129. ("idefics", "IdeficsConfig"),
  130. ("idefics2", "Idefics2Config"),
  131. ("idefics3", "Idefics3Config"),
  132. ("imagegpt", "ImageGPTConfig"),
  133. ("informer", "InformerConfig"),
  134. ("instructblip", "InstructBlipConfig"),
  135. ("instructblipvideo", "InstructBlipVideoConfig"),
  136. ("jamba", "JambaConfig"),
  137. ("jetmoe", "JetMoeConfig"),
  138. ("jukebox", "JukeboxConfig"),
  139. ("kosmos-2", "Kosmos2Config"),
  140. ("layoutlm", "LayoutLMConfig"),
  141. ("layoutlmv2", "LayoutLMv2Config"),
  142. ("layoutlmv3", "LayoutLMv3Config"),
  143. ("led", "LEDConfig"),
  144. ("levit", "LevitConfig"),
  145. ("lilt", "LiltConfig"),
  146. ("llama", "LlamaConfig"),
  147. ("llava", "LlavaConfig"),
  148. ("llava_next", "LlavaNextConfig"),
  149. ("llava_next_video", "LlavaNextVideoConfig"),
  150. ("llava_onevision", "LlavaOnevisionConfig"),
  151. ("longformer", "LongformerConfig"),
  152. ("longt5", "LongT5Config"),
  153. ("luke", "LukeConfig"),
  154. ("lxmert", "LxmertConfig"),
  155. ("m2m_100", "M2M100Config"),
  156. ("mamba", "MambaConfig"),
  157. ("mamba2", "Mamba2Config"),
  158. ("marian", "MarianConfig"),
  159. ("markuplm", "MarkupLMConfig"),
  160. ("mask2former", "Mask2FormerConfig"),
  161. ("maskformer", "MaskFormerConfig"),
  162. ("maskformer-swin", "MaskFormerSwinConfig"),
  163. ("mbart", "MBartConfig"),
  164. ("mctct", "MCTCTConfig"),
  165. ("mega", "MegaConfig"),
  166. ("megatron-bert", "MegatronBertConfig"),
  167. ("mgp-str", "MgpstrConfig"),
  168. ("mimi", "MimiConfig"),
  169. ("mistral", "MistralConfig"),
  170. ("mixtral", "MixtralConfig"),
  171. ("mllama", "MllamaConfig"),
  172. ("mobilebert", "MobileBertConfig"),
  173. ("mobilenet_v1", "MobileNetV1Config"),
  174. ("mobilenet_v2", "MobileNetV2Config"),
  175. ("mobilevit", "MobileViTConfig"),
  176. ("mobilevitv2", "MobileViTV2Config"),
  177. ("moshi", "MoshiConfig"),
  178. ("mpnet", "MPNetConfig"),
  179. ("mpt", "MptConfig"),
  180. ("mra", "MraConfig"),
  181. ("mt5", "MT5Config"),
  182. ("musicgen", "MusicgenConfig"),
  183. ("musicgen_melody", "MusicgenMelodyConfig"),
  184. ("mvp", "MvpConfig"),
  185. ("nat", "NatConfig"),
  186. ("nemotron", "NemotronConfig"),
  187. ("nezha", "NezhaConfig"),
  188. ("nllb-moe", "NllbMoeConfig"),
  189. ("nougat", "VisionEncoderDecoderConfig"),
  190. ("nystromformer", "NystromformerConfig"),
  191. ("olmo", "OlmoConfig"),
  192. ("olmoe", "OlmoeConfig"),
  193. ("omdet-turbo", "OmDetTurboConfig"),
  194. ("oneformer", "OneFormerConfig"),
  195. ("open-llama", "OpenLlamaConfig"),
  196. ("openai-gpt", "OpenAIGPTConfig"),
  197. ("opt", "OPTConfig"),
  198. ("owlv2", "Owlv2Config"),
  199. ("owlvit", "OwlViTConfig"),
  200. ("paligemma", "PaliGemmaConfig"),
  201. ("patchtsmixer", "PatchTSMixerConfig"),
  202. ("patchtst", "PatchTSTConfig"),
  203. ("pegasus", "PegasusConfig"),
  204. ("pegasus_x", "PegasusXConfig"),
  205. ("perceiver", "PerceiverConfig"),
  206. ("persimmon", "PersimmonConfig"),
  207. ("phi", "PhiConfig"),
  208. ("phi3", "Phi3Config"),
  209. ("phimoe", "PhimoeConfig"),
  210. ("pix2struct", "Pix2StructConfig"),
  211. ("pixtral", "PixtralVisionConfig"),
  212. ("plbart", "PLBartConfig"),
  213. ("poolformer", "PoolFormerConfig"),
  214. ("pop2piano", "Pop2PianoConfig"),
  215. ("prophetnet", "ProphetNetConfig"),
  216. ("pvt", "PvtConfig"),
  217. ("pvt_v2", "PvtV2Config"),
  218. ("qdqbert", "QDQBertConfig"),
  219. ("qwen2", "Qwen2Config"),
  220. ("qwen2_audio", "Qwen2AudioConfig"),
  221. ("qwen2_audio_encoder", "Qwen2AudioEncoderConfig"),
  222. ("qwen2_moe", "Qwen2MoeConfig"),
  223. ("qwen2_vl", "Qwen2VLConfig"),
  224. ("rag", "RagConfig"),
  225. ("realm", "RealmConfig"),
  226. ("recurrent_gemma", "RecurrentGemmaConfig"),
  227. ("reformer", "ReformerConfig"),
  228. ("regnet", "RegNetConfig"),
  229. ("rembert", "RemBertConfig"),
  230. ("resnet", "ResNetConfig"),
  231. ("retribert", "RetriBertConfig"),
  232. ("roberta", "RobertaConfig"),
  233. ("roberta-prelayernorm", "RobertaPreLayerNormConfig"),
  234. ("roc_bert", "RoCBertConfig"),
  235. ("roformer", "RoFormerConfig"),
  236. ("rt_detr", "RTDetrConfig"),
  237. ("rt_detr_resnet", "RTDetrResNetConfig"),
  238. ("rwkv", "RwkvConfig"),
  239. ("sam", "SamConfig"),
  240. ("seamless_m4t", "SeamlessM4TConfig"),
  241. ("seamless_m4t_v2", "SeamlessM4Tv2Config"),
  242. ("segformer", "SegformerConfig"),
  243. ("seggpt", "SegGptConfig"),
  244. ("sew", "SEWConfig"),
  245. ("sew-d", "SEWDConfig"),
  246. ("siglip", "SiglipConfig"),
  247. ("siglip_vision_model", "SiglipVisionConfig"),
  248. ("speech-encoder-decoder", "SpeechEncoderDecoderConfig"),
  249. ("speech_to_text", "Speech2TextConfig"),
  250. ("speech_to_text_2", "Speech2Text2Config"),
  251. ("speecht5", "SpeechT5Config"),
  252. ("splinter", "SplinterConfig"),
  253. ("squeezebert", "SqueezeBertConfig"),
  254. ("stablelm", "StableLmConfig"),
  255. ("starcoder2", "Starcoder2Config"),
  256. ("superpoint", "SuperPointConfig"),
  257. ("swiftformer", "SwiftFormerConfig"),
  258. ("swin", "SwinConfig"),
  259. ("swin2sr", "Swin2SRConfig"),
  260. ("swinv2", "Swinv2Config"),
  261. ("switch_transformers", "SwitchTransformersConfig"),
  262. ("t5", "T5Config"),
  263. ("table-transformer", "TableTransformerConfig"),
  264. ("tapas", "TapasConfig"),
  265. ("time_series_transformer", "TimeSeriesTransformerConfig"),
  266. ("timesformer", "TimesformerConfig"),
  267. ("timm_backbone", "TimmBackboneConfig"),
  268. ("trajectory_transformer", "TrajectoryTransformerConfig"),
  269. ("transfo-xl", "TransfoXLConfig"),
  270. ("trocr", "TrOCRConfig"),
  271. ("tvlt", "TvltConfig"),
  272. ("tvp", "TvpConfig"),
  273. ("udop", "UdopConfig"),
  274. ("umt5", "UMT5Config"),
  275. ("unispeech", "UniSpeechConfig"),
  276. ("unispeech-sat", "UniSpeechSatConfig"),
  277. ("univnet", "UnivNetConfig"),
  278. ("upernet", "UperNetConfig"),
  279. ("van", "VanConfig"),
  280. ("video_llava", "VideoLlavaConfig"),
  281. ("videomae", "VideoMAEConfig"),
  282. ("vilt", "ViltConfig"),
  283. ("vipllava", "VipLlavaConfig"),
  284. ("vision-encoder-decoder", "VisionEncoderDecoderConfig"),
  285. ("vision-text-dual-encoder", "VisionTextDualEncoderConfig"),
  286. ("visual_bert", "VisualBertConfig"),
  287. ("vit", "ViTConfig"),
  288. ("vit_hybrid", "ViTHybridConfig"),
  289. ("vit_mae", "ViTMAEConfig"),
  290. ("vit_msn", "ViTMSNConfig"),
  291. ("vitdet", "VitDetConfig"),
  292. ("vitmatte", "VitMatteConfig"),
  293. ("vits", "VitsConfig"),
  294. ("vivit", "VivitConfig"),
  295. ("wav2vec2", "Wav2Vec2Config"),
  296. ("wav2vec2-bert", "Wav2Vec2BertConfig"),
  297. ("wav2vec2-conformer", "Wav2Vec2ConformerConfig"),
  298. ("wavlm", "WavLMConfig"),
  299. ("whisper", "WhisperConfig"),
  300. ("xclip", "XCLIPConfig"),
  301. ("xglm", "XGLMConfig"),
  302. ("xlm", "XLMConfig"),
  303. ("xlm-prophetnet", "XLMProphetNetConfig"),
  304. ("xlm-roberta", "XLMRobertaConfig"),
  305. ("xlm-roberta-xl", "XLMRobertaXLConfig"),
  306. ("xlnet", "XLNetConfig"),
  307. ("xmod", "XmodConfig"),
  308. ("yolos", "YolosConfig"),
  309. ("yoso", "YosoConfig"),
  310. ("zamba", "ZambaConfig"),
  311. ("zoedepth", "ZoeDepthConfig"),
  312. ]
  313. )
  314. MODEL_NAMES_MAPPING = OrderedDict(
  315. [
  316. # Add full (and cased) model names here
  317. ("albert", "ALBERT"),
  318. ("align", "ALIGN"),
  319. ("altclip", "AltCLIP"),
  320. ("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
  321. ("autoformer", "Autoformer"),
  322. ("bark", "Bark"),
  323. ("bart", "BART"),
  324. ("barthez", "BARThez"),
  325. ("bartpho", "BARTpho"),
  326. ("beit", "BEiT"),
  327. ("bert", "BERT"),
  328. ("bert-generation", "Bert Generation"),
  329. ("bert-japanese", "BertJapanese"),
  330. ("bertweet", "BERTweet"),
  331. ("big_bird", "BigBird"),
  332. ("bigbird_pegasus", "BigBird-Pegasus"),
  333. ("biogpt", "BioGpt"),
  334. ("bit", "BiT"),
  335. ("blenderbot", "Blenderbot"),
  336. ("blenderbot-small", "BlenderbotSmall"),
  337. ("blip", "BLIP"),
  338. ("blip-2", "BLIP-2"),
  339. ("bloom", "BLOOM"),
  340. ("bort", "BORT"),
  341. ("bridgetower", "BridgeTower"),
  342. ("bros", "BROS"),
  343. ("byt5", "ByT5"),
  344. ("camembert", "CamemBERT"),
  345. ("canine", "CANINE"),
  346. ("chameleon", "Chameleon"),
  347. ("chinese_clip", "Chinese-CLIP"),
  348. ("chinese_clip_vision_model", "ChineseCLIPVisionModel"),
  349. ("clap", "CLAP"),
  350. ("clip", "CLIP"),
  351. ("clip_text_model", "CLIPTextModel"),
  352. ("clip_vision_model", "CLIPVisionModel"),
  353. ("clipseg", "CLIPSeg"),
  354. ("clvp", "CLVP"),
  355. ("code_llama", "CodeLlama"),
  356. ("codegen", "CodeGen"),
  357. ("cohere", "Cohere"),
  358. ("conditional_detr", "Conditional DETR"),
  359. ("convbert", "ConvBERT"),
  360. ("convnext", "ConvNeXT"),
  361. ("convnextv2", "ConvNeXTV2"),
  362. ("cpm", "CPM"),
  363. ("cpmant", "CPM-Ant"),
  364. ("ctrl", "CTRL"),
  365. ("cvt", "CvT"),
  366. ("dac", "DAC"),
  367. ("data2vec-audio", "Data2VecAudio"),
  368. ("data2vec-text", "Data2VecText"),
  369. ("data2vec-vision", "Data2VecVision"),
  370. ("dbrx", "DBRX"),
  371. ("deberta", "DeBERTa"),
  372. ("deberta-v2", "DeBERTa-v2"),
  373. ("decision_transformer", "Decision Transformer"),
  374. ("deformable_detr", "Deformable DETR"),
  375. ("deit", "DeiT"),
  376. ("deplot", "DePlot"),
  377. ("depth_anything", "Depth Anything"),
  378. ("depth_anything_v2", "Depth Anything V2"),
  379. ("deta", "DETA"),
  380. ("detr", "DETR"),
  381. ("dialogpt", "DialoGPT"),
  382. ("dinat", "DiNAT"),
  383. ("dinov2", "DINOv2"),
  384. ("distilbert", "DistilBERT"),
  385. ("dit", "DiT"),
  386. ("donut-swin", "DonutSwin"),
  387. ("dpr", "DPR"),
  388. ("dpt", "DPT"),
  389. ("efficientformer", "EfficientFormer"),
  390. ("efficientnet", "EfficientNet"),
  391. ("electra", "ELECTRA"),
  392. ("encodec", "EnCodec"),
  393. ("encoder-decoder", "Encoder decoder"),
  394. ("ernie", "ERNIE"),
  395. ("ernie_m", "ErnieM"),
  396. ("esm", "ESM"),
  397. ("falcon", "Falcon"),
  398. ("falcon_mamba", "FalconMamba"),
  399. ("fastspeech2_conformer", "FastSpeech2Conformer"),
  400. ("flan-t5", "FLAN-T5"),
  401. ("flan-ul2", "FLAN-UL2"),
  402. ("flaubert", "FlauBERT"),
  403. ("flava", "FLAVA"),
  404. ("fnet", "FNet"),
  405. ("focalnet", "FocalNet"),
  406. ("fsmt", "FairSeq Machine-Translation"),
  407. ("funnel", "Funnel Transformer"),
  408. ("fuyu", "Fuyu"),
  409. ("gemma", "Gemma"),
  410. ("gemma2", "Gemma2"),
  411. ("git", "GIT"),
  412. ("glm", "GLM"),
  413. ("glpn", "GLPN"),
  414. ("gpt-sw3", "GPT-Sw3"),
  415. ("gpt2", "OpenAI GPT-2"),
  416. ("gpt_bigcode", "GPTBigCode"),
  417. ("gpt_neo", "GPT Neo"),
  418. ("gpt_neox", "GPT NeoX"),
  419. ("gpt_neox_japanese", "GPT NeoX Japanese"),
  420. ("gptj", "GPT-J"),
  421. ("gptsan-japanese", "GPTSAN-japanese"),
  422. ("granite", "Granite"),
  423. ("granitemoe", "GraniteMoeMoe"),
  424. ("graphormer", "Graphormer"),
  425. ("grounding-dino", "Grounding DINO"),
  426. ("groupvit", "GroupViT"),
  427. ("herbert", "HerBERT"),
  428. ("hiera", "Hiera"),
  429. ("hubert", "Hubert"),
  430. ("ibert", "I-BERT"),
  431. ("idefics", "IDEFICS"),
  432. ("idefics2", "Idefics2"),
  433. ("idefics3", "Idefics3"),
  434. ("imagegpt", "ImageGPT"),
  435. ("informer", "Informer"),
  436. ("instructblip", "InstructBLIP"),
  437. ("instructblipvideo", "InstructBlipVideo"),
  438. ("jamba", "Jamba"),
  439. ("jetmoe", "JetMoe"),
  440. ("jukebox", "Jukebox"),
  441. ("kosmos-2", "KOSMOS-2"),
  442. ("layoutlm", "LayoutLM"),
  443. ("layoutlmv2", "LayoutLMv2"),
  444. ("layoutlmv3", "LayoutLMv3"),
  445. ("layoutxlm", "LayoutXLM"),
  446. ("led", "LED"),
  447. ("levit", "LeViT"),
  448. ("lilt", "LiLT"),
  449. ("llama", "LLaMA"),
  450. ("llama2", "Llama2"),
  451. ("llama3", "Llama3"),
  452. ("llava", "LLaVa"),
  453. ("llava_next", "LLaVA-NeXT"),
  454. ("llava_next_video", "LLaVa-NeXT-Video"),
  455. ("llava_onevision", "LLaVA-Onevision"),
  456. ("longformer", "Longformer"),
  457. ("longt5", "LongT5"),
  458. ("luke", "LUKE"),
  459. ("lxmert", "LXMERT"),
  460. ("m2m_100", "M2M100"),
  461. ("madlad-400", "MADLAD-400"),
  462. ("mamba", "Mamba"),
  463. ("mamba2", "mamba2"),
  464. ("marian", "Marian"),
  465. ("markuplm", "MarkupLM"),
  466. ("mask2former", "Mask2Former"),
  467. ("maskformer", "MaskFormer"),
  468. ("maskformer-swin", "MaskFormerSwin"),
  469. ("matcha", "MatCha"),
  470. ("mbart", "mBART"),
  471. ("mbart50", "mBART-50"),
  472. ("mctct", "M-CTC-T"),
  473. ("mega", "MEGA"),
  474. ("megatron-bert", "Megatron-BERT"),
  475. ("megatron_gpt2", "Megatron-GPT2"),
  476. ("mgp-str", "MGP-STR"),
  477. ("mimi", "Mimi"),
  478. ("mistral", "Mistral"),
  479. ("mixtral", "Mixtral"),
  480. ("mllama", "Mllama"),
  481. ("mluke", "mLUKE"),
  482. ("mms", "MMS"),
  483. ("mobilebert", "MobileBERT"),
  484. ("mobilenet_v1", "MobileNetV1"),
  485. ("mobilenet_v2", "MobileNetV2"),
  486. ("mobilevit", "MobileViT"),
  487. ("mobilevitv2", "MobileViTV2"),
  488. ("moshi", "Moshi"),
  489. ("mpnet", "MPNet"),
  490. ("mpt", "MPT"),
  491. ("mra", "MRA"),
  492. ("mt5", "MT5"),
  493. ("musicgen", "MusicGen"),
  494. ("musicgen_melody", "MusicGen Melody"),
  495. ("mvp", "MVP"),
  496. ("myt5", "myt5"),
  497. ("nat", "NAT"),
  498. ("nemotron", "Nemotron"),
  499. ("nezha", "Nezha"),
  500. ("nllb", "NLLB"),
  501. ("nllb-moe", "NLLB-MOE"),
  502. ("nougat", "Nougat"),
  503. ("nystromformer", "Nyströmformer"),
  504. ("olmo", "OLMo"),
  505. ("olmoe", "OLMoE"),
  506. ("omdet-turbo", "OmDet-Turbo"),
  507. ("oneformer", "OneFormer"),
  508. ("open-llama", "OpenLlama"),
  509. ("openai-gpt", "OpenAI GPT"),
  510. ("opt", "OPT"),
  511. ("owlv2", "OWLv2"),
  512. ("owlvit", "OWL-ViT"),
  513. ("paligemma", "PaliGemma"),
  514. ("patchtsmixer", "PatchTSMixer"),
  515. ("patchtst", "PatchTST"),
  516. ("pegasus", "Pegasus"),
  517. ("pegasus_x", "PEGASUS-X"),
  518. ("perceiver", "Perceiver"),
  519. ("persimmon", "Persimmon"),
  520. ("phi", "Phi"),
  521. ("phi3", "Phi3"),
  522. ("phimoe", "Phimoe"),
  523. ("phobert", "PhoBERT"),
  524. ("pix2struct", "Pix2Struct"),
  525. ("pixtral", "Pixtral"),
  526. ("plbart", "PLBart"),
  527. ("poolformer", "PoolFormer"),
  528. ("pop2piano", "Pop2Piano"),
  529. ("prophetnet", "ProphetNet"),
  530. ("pvt", "PVT"),
  531. ("pvt_v2", "PVTv2"),
  532. ("qdqbert", "QDQBert"),
  533. ("qwen2", "Qwen2"),
  534. ("qwen2_audio", "Qwen2Audio"),
  535. ("qwen2_audio_encoder", "Qwen2AudioEncoder"),
  536. ("qwen2_moe", "Qwen2MoE"),
  537. ("qwen2_vl", "Qwen2VL"),
  538. ("rag", "RAG"),
  539. ("realm", "REALM"),
  540. ("recurrent_gemma", "RecurrentGemma"),
  541. ("reformer", "Reformer"),
  542. ("regnet", "RegNet"),
  543. ("rembert", "RemBERT"),
  544. ("resnet", "ResNet"),
  545. ("retribert", "RetriBERT"),
  546. ("roberta", "RoBERTa"),
  547. ("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
  548. ("roc_bert", "RoCBert"),
  549. ("roformer", "RoFormer"),
  550. ("rt_detr", "RT-DETR"),
  551. ("rt_detr_resnet", "RT-DETR-ResNet"),
  552. ("rwkv", "RWKV"),
  553. ("sam", "SAM"),
  554. ("seamless_m4t", "SeamlessM4T"),
  555. ("seamless_m4t_v2", "SeamlessM4Tv2"),
  556. ("segformer", "SegFormer"),
  557. ("seggpt", "SegGPT"),
  558. ("sew", "SEW"),
  559. ("sew-d", "SEW-D"),
  560. ("siglip", "SigLIP"),
  561. ("siglip_vision_model", "SiglipVisionModel"),
  562. ("speech-encoder-decoder", "Speech Encoder decoder"),
  563. ("speech_to_text", "Speech2Text"),
  564. ("speech_to_text_2", "Speech2Text2"),
  565. ("speecht5", "SpeechT5"),
  566. ("splinter", "Splinter"),
  567. ("squeezebert", "SqueezeBERT"),
  568. ("stablelm", "StableLm"),
  569. ("starcoder2", "Starcoder2"),
  570. ("superpoint", "SuperPoint"),
  571. ("swiftformer", "SwiftFormer"),
  572. ("swin", "Swin Transformer"),
  573. ("swin2sr", "Swin2SR"),
  574. ("swinv2", "Swin Transformer V2"),
  575. ("switch_transformers", "SwitchTransformers"),
  576. ("t5", "T5"),
  577. ("t5v1.1", "T5v1.1"),
  578. ("table-transformer", "Table Transformer"),
  579. ("tapas", "TAPAS"),
  580. ("tapex", "TAPEX"),
  581. ("time_series_transformer", "Time Series Transformer"),
  582. ("timesformer", "TimeSformer"),
  583. ("timm_backbone", "TimmBackbone"),
  584. ("trajectory_transformer", "Trajectory Transformer"),
  585. ("transfo-xl", "Transformer-XL"),
  586. ("trocr", "TrOCR"),
  587. ("tvlt", "TVLT"),
  588. ("tvp", "TVP"),
  589. ("udop", "UDOP"),
  590. ("ul2", "UL2"),
  591. ("umt5", "UMT5"),
  592. ("unispeech", "UniSpeech"),
  593. ("unispeech-sat", "UniSpeechSat"),
  594. ("univnet", "UnivNet"),
  595. ("upernet", "UPerNet"),
  596. ("van", "VAN"),
  597. ("video_llava", "VideoLlava"),
  598. ("videomae", "VideoMAE"),
  599. ("vilt", "ViLT"),
  600. ("vipllava", "VipLlava"),
  601. ("vision-encoder-decoder", "Vision Encoder decoder"),
  602. ("vision-text-dual-encoder", "VisionTextDualEncoder"),
  603. ("visual_bert", "VisualBERT"),
  604. ("vit", "ViT"),
  605. ("vit_hybrid", "ViT Hybrid"),
  606. ("vit_mae", "ViTMAE"),
  607. ("vit_msn", "ViTMSN"),
  608. ("vitdet", "VitDet"),
  609. ("vitmatte", "ViTMatte"),
  610. ("vits", "VITS"),
  611. ("vivit", "ViViT"),
  612. ("wav2vec2", "Wav2Vec2"),
  613. ("wav2vec2-bert", "Wav2Vec2-BERT"),
  614. ("wav2vec2-conformer", "Wav2Vec2-Conformer"),
  615. ("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
  616. ("wavlm", "WavLM"),
  617. ("whisper", "Whisper"),
  618. ("xclip", "X-CLIP"),
  619. ("xglm", "XGLM"),
  620. ("xlm", "XLM"),
  621. ("xlm-prophetnet", "XLM-ProphetNet"),
  622. ("xlm-roberta", "XLM-RoBERTa"),
  623. ("xlm-roberta-xl", "XLM-RoBERTa-XL"),
  624. ("xlm-v", "XLM-V"),
  625. ("xlnet", "XLNet"),
  626. ("xls_r", "XLS-R"),
  627. ("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
  628. ("xmod", "X-MOD"),
  629. ("yolos", "YOLOS"),
  630. ("yoso", "YOSO"),
  631. ("zamba", "Zamba"),
  632. ("zoedepth", "ZoeDepth"),
  633. ]
  634. )
  635. # This is tied to the processing `-` -> `_` in `model_type_to_module_name`. For example, instead of putting
  636. # `transfo-xl` (as in `CONFIG_MAPPING_NAMES`), we should use `transfo_xl`.
  637. DEPRECATED_MODELS = [
  638. "bort",
  639. "deta",
  640. "efficientformer",
  641. "ernie_m",
  642. "gptsan_japanese",
  643. "graphormer",
  644. "jukebox",
  645. "mctct",
  646. "mega",
  647. "mmbt",
  648. "nat",
  649. "nezha",
  650. "open_llama",
  651. "qdqbert",
  652. "realm",
  653. "retribert",
  654. "speech_to_text_2",
  655. "tapex",
  656. "trajectory_transformer",
  657. "transfo_xl",
  658. "tvlt",
  659. "van",
  660. "vit_hybrid",
  661. "xlm_prophetnet",
  662. ]
  663. SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
  664. [
  665. ("openai-gpt", "openai"),
  666. ("data2vec-audio", "data2vec"),
  667. ("data2vec-text", "data2vec"),
  668. ("data2vec-vision", "data2vec"),
  669. ("donut-swin", "donut"),
  670. ("kosmos-2", "kosmos2"),
  671. ("maskformer-swin", "maskformer"),
  672. ("xclip", "x_clip"),
  673. ("clip_vision_model", "clip"),
  674. ("qwen2_audio_encoder", "qwen2_audio"),
  675. ("clip_text_model", "clip"),
  676. ("siglip_vision_model", "siglip"),
  677. ("chinese_clip_vision_model", "chinese_clip"),
  678. ("rt_detr_resnet", "rt_detr"),
  679. ]
  680. )
  681. def model_type_to_module_name(key):
  682. """Converts a config key to the corresponding module."""
  683. # Special treatment
  684. if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME:
  685. key = SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key]
  686. if key in DEPRECATED_MODELS:
  687. key = f"deprecated.{key}"
  688. return key
  689. key = key.replace("-", "_")
  690. if key in DEPRECATED_MODELS:
  691. key = f"deprecated.{key}"
  692. return key
  693. def config_class_to_model_type(config):
  694. """Converts a config class name to the corresponding model type"""
  695. for key, cls in CONFIG_MAPPING_NAMES.items():
  696. if cls == config:
  697. return key
  698. # if key not found check in extra content
  699. for key, cls in CONFIG_MAPPING._extra_content.items():
  700. if cls.__name__ == config:
  701. return key
  702. return None
  703. class _LazyConfigMapping(OrderedDict):
  704. """
  705. A dictionary that lazily load its values when they are requested.
  706. """
  707. def __init__(self, mapping):
  708. self._mapping = mapping
  709. self._extra_content = {}
  710. self._modules = {}
  711. def __getitem__(self, key):
  712. if key in self._extra_content:
  713. return self._extra_content[key]
  714. if key not in self._mapping:
  715. raise KeyError(key)
  716. value = self._mapping[key]
  717. module_name = model_type_to_module_name(key)
  718. if module_name not in self._modules:
  719. self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
  720. if hasattr(self._modules[module_name], value):
  721. return getattr(self._modules[module_name], value)
  722. # Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the
  723. # object at the top level.
  724. transformers_module = importlib.import_module("transformers")
  725. return getattr(transformers_module, value)
  726. def keys(self):
  727. return list(self._mapping.keys()) + list(self._extra_content.keys())
  728. def values(self):
  729. return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values())
  730. def items(self):
  731. return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
  732. def __iter__(self):
  733. return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
  734. def __contains__(self, item):
  735. return item in self._mapping or item in self._extra_content
  736. def register(self, key, value, exist_ok=False):
  737. """
  738. Register a new configuration in this mapping.
  739. """
  740. if key in self._mapping.keys() and not exist_ok:
  741. raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.")
  742. self._extra_content[key] = value
  743. CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES)
  744. class _LazyLoadAllMappings(OrderedDict):
  745. """
  746. A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values,
  747. etc.)
  748. Args:
  749. mapping: The mapping to load.
  750. """
  751. def __init__(self, mapping):
  752. self._mapping = mapping
  753. self._initialized = False
  754. self._data = {}
  755. def _initialize(self):
  756. if self._initialized:
  757. return
  758. for model_type, map_name in self._mapping.items():
  759. module_name = model_type_to_module_name(model_type)
  760. module = importlib.import_module(f".{module_name}", "transformers.models")
  761. mapping = getattr(module, map_name)
  762. self._data.update(mapping)
  763. self._initialized = True
  764. def __getitem__(self, key):
  765. self._initialize()
  766. return self._data[key]
  767. def keys(self):
  768. self._initialize()
  769. return self._data.keys()
  770. def values(self):
  771. self._initialize()
  772. return self._data.values()
  773. def items(self):
  774. self._initialize()
  775. return self._data.keys()
  776. def __iter__(self):
  777. self._initialize()
  778. return iter(self._data)
  779. def __contains__(self, item):
  780. self._initialize()
  781. return item in self._data
  782. def _get_class_name(model_class: Union[str, List[str]]):
  783. if isinstance(model_class, (list, tuple)):
  784. return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
  785. return f"[`{model_class}`]"
  786. def _list_model_options(indent, config_to_class=None, use_model_types=True):
  787. if config_to_class is None and not use_model_types:
  788. raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.")
  789. if use_model_types:
  790. if config_to_class is None:
  791. model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
  792. else:
  793. model_type_to_name = {
  794. model_type: _get_class_name(model_class)
  795. for model_type, model_class in config_to_class.items()
  796. if model_type in MODEL_NAMES_MAPPING
  797. }
  798. lines = [
  799. f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
  800. for model_type in sorted(model_type_to_name.keys())
  801. ]
  802. else:
  803. config_to_name = {
  804. CONFIG_MAPPING_NAMES[config]: _get_class_name(clas)
  805. for config, clas in config_to_class.items()
  806. if config in CONFIG_MAPPING_NAMES
  807. }
  808. config_to_model_name = {
  809. config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
  810. }
  811. lines = [
  812. f"{indent}- [`{config_name}`] configuration class:"
  813. f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
  814. for config_name in sorted(config_to_name.keys())
  815. ]
  816. return "\n".join(lines)
  817. def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True):
  818. def docstring_decorator(fn):
  819. docstrings = fn.__doc__
  820. if docstrings is None:
  821. # Example: -OO
  822. return fn
  823. lines = docstrings.split("\n")
  824. i = 0
  825. while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None:
  826. i += 1
  827. if i < len(lines):
  828. indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
  829. if use_model_types:
  830. indent = f"{indent} "
  831. lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
  832. docstrings = "\n".join(lines)
  833. else:
  834. raise ValueError(
  835. f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
  836. f" docstring is:\n{docstrings}"
  837. )
  838. fn.__doc__ = docstrings
  839. return fn
  840. return docstring_decorator
  841. class AutoConfig:
  842. r"""
  843. This is a generic configuration class that will be instantiated as one of the configuration classes of the library
  844. when created with the [`~AutoConfig.from_pretrained`] class method.
  845. This class cannot be instantiated directly using `__init__()` (throws an error).
  846. """
  847. def __init__(self):
  848. raise EnvironmentError(
  849. "AutoConfig is designed to be instantiated "
  850. "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
  851. )
  852. @classmethod
  853. def for_model(cls, model_type: str, *args, **kwargs):
  854. if model_type in CONFIG_MAPPING:
  855. config_class = CONFIG_MAPPING[model_type]
  856. return config_class(*args, **kwargs)
  857. raise ValueError(
  858. f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
  859. )
  860. @classmethod
  861. @replace_list_option_in_docstrings()
  862. def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
  863. r"""
  864. Instantiate one of the configuration classes of the library from a pretrained model configuration.
  865. The configuration class to instantiate is selected based on the `model_type` property of the config object that
  866. is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
  867. List options
  868. Args:
  869. pretrained_model_name_or_path (`str` or `os.PathLike`):
  870. Can be either:
  871. - A string, the *model id* of a pretrained model configuration hosted inside a model repo on
  872. huggingface.co.
  873. - A path to a *directory* containing a configuration file saved using the
  874. [`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
  875. e.g., `./my_model_directory/`.
  876. - A path or url to a saved configuration JSON *file*, e.g.,
  877. `./my_model_directory/configuration.json`.
  878. cache_dir (`str` or `os.PathLike`, *optional*):
  879. Path to a directory in which a downloaded pretrained model configuration should be cached if the
  880. standard cache should not be used.
  881. force_download (`bool`, *optional*, defaults to `False`):
  882. Whether or not to force the (re-)download the model weights and configuration files and override the
  883. cached versions if they exist.
  884. resume_download:
  885. Deprecated and ignored. All downloads are now resumed by default when possible.
  886. Will be removed in v5 of Transformers.
  887. proxies (`Dict[str, str]`, *optional*):
  888. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  889. 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
  890. revision (`str`, *optional*, defaults to `"main"`):
  891. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  892. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  893. identifier allowed by git.
  894. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  895. If `False`, then this function returns just the final configuration object.
  896. If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
  897. dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
  898. part of `kwargs` which has not been used to update `config` and is otherwise ignored.
  899. trust_remote_code (`bool`, *optional*, defaults to `False`):
  900. Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
  901. should only be set to `True` for repositories you trust and in which you have read the code, as it will
  902. execute code present on the Hub on your local machine.
  903. kwargs(additional keyword arguments, *optional*):
  904. The values in kwargs of any keys which are configuration attributes will be used to override the loaded
  905. values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
  906. by the `return_unused_kwargs` keyword parameter.
  907. Examples:
  908. ```python
  909. >>> from transformers import AutoConfig
  910. >>> # Download configuration from huggingface.co and cache.
  911. >>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
  912. >>> # Download configuration from huggingface.co (user-uploaded) and cache.
  913. >>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
  914. >>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
  915. >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
  916. >>> # Load a specific configuration file.
  917. >>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
  918. >>> # Change some config attributes when loading a pretrained config.
  919. >>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
  920. >>> config.output_attentions
  921. True
  922. >>> config, unused_kwargs = AutoConfig.from_pretrained(
  923. ... "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
  924. ... )
  925. >>> config.output_attentions
  926. True
  927. >>> unused_kwargs
  928. {'foo': False}
  929. ```"""
  930. use_auth_token = kwargs.pop("use_auth_token", None)
  931. if use_auth_token is not None:
  932. warnings.warn(
  933. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  934. FutureWarning,
  935. )
  936. if kwargs.get("token", None) is not None:
  937. raise ValueError(
  938. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  939. )
  940. kwargs["token"] = use_auth_token
  941. kwargs["_from_auto"] = True
  942. kwargs["name_or_path"] = pretrained_model_name_or_path
  943. trust_remote_code = kwargs.pop("trust_remote_code", None)
  944. code_revision = kwargs.pop("code_revision", None)
  945. config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
  946. has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]
  947. has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING
  948. trust_remote_code = resolve_trust_remote_code(
  949. trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
  950. )
  951. if has_remote_code and trust_remote_code:
  952. class_ref = config_dict["auto_map"]["AutoConfig"]
  953. config_class = get_class_from_dynamic_module(
  954. class_ref, pretrained_model_name_or_path, code_revision=code_revision, **kwargs
  955. )
  956. if os.path.isdir(pretrained_model_name_or_path):
  957. config_class.register_for_auto_class()
  958. return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
  959. elif "model_type" in config_dict:
  960. try:
  961. config_class = CONFIG_MAPPING[config_dict["model_type"]]
  962. except KeyError:
  963. raise ValueError(
  964. f"The checkpoint you are trying to load has model type `{config_dict['model_type']}` "
  965. "but Transformers does not recognize this architecture. This could be because of an "
  966. "issue with the checkpoint, or because your version of Transformers is out of date."
  967. )
  968. return config_class.from_dict(config_dict, **unused_kwargs)
  969. else:
  970. # Fallback: use pattern matching on the string.
  971. # We go from longer names to shorter names to catch roberta before bert (for instance)
  972. for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True):
  973. if pattern in str(pretrained_model_name_or_path):
  974. return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
  975. raise ValueError(
  976. f"Unrecognized model in {pretrained_model_name_or_path}. "
  977. f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
  978. f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
  979. )
  980. @staticmethod
  981. def register(model_type, config, exist_ok=False):
  982. """
  983. Register a new configuration for this class.
  984. Args:
  985. model_type (`str`): The model type like "bert" or "gpt".
  986. config ([`PretrainedConfig`]): The config to register.
  987. """
  988. if issubclass(config, PretrainedConfig) and config.model_type != model_type:
  989. raise ValueError(
  990. "The config you are passing has a `model_type` attribute that is not consistent with the model type "
  991. f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they "
  992. "match!"
  993. )
  994. CONFIG_MAPPING.register(model_type, config, exist_ok=exist_ok)