configuration_utils.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  2. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Configuration base class and utilities."""
  16. import copy
  17. import json
  18. import os
  19. import warnings
  20. from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union
  21. from packaging import version
  22. from . import __version__
  23. from .dynamic_module_utils import custom_object_save
  24. from .modeling_gguf_pytorch_utils import load_gguf_checkpoint
  25. from .utils import (
  26. CONFIG_NAME,
  27. PushToHubMixin,
  28. cached_file,
  29. copy_func,
  30. download_url,
  31. extract_commit_hash,
  32. is_remote_url,
  33. is_torch_available,
  34. logging,
  35. )
  36. from .utils.generic import is_timm_config_dict
  37. if TYPE_CHECKING:
  38. import torch
  39. logger = logging.get_logger(__name__)
  40. # type hinting: specifying the type of config class that inherits from PretrainedConfig
  41. SpecificPretrainedConfigType = TypeVar("SpecificPretrainedConfigType", bound="PretrainedConfig")
  42. class PretrainedConfig(PushToHubMixin):
  43. # no-format
  44. r"""
  45. Base class for all configuration classes. Handles a few parameters common to all models' configurations as well as
  46. methods for loading/downloading/saving configurations.
  47. <Tip>
  48. A configuration file can be loaded and saved to disk. Loading the configuration file and using this file to
  49. initialize a model does **not** load the model weights. It only affects the model's configuration.
  50. </Tip>
  51. Class attributes (overridden by derived classes):
  52. - **model_type** (`str`) -- An identifier for the model type, serialized into the JSON file, and used to recreate
  53. the correct object in [`~transformers.AutoConfig`].
  54. - **has_no_defaults_at_init** (`bool`) -- Whether the config class can be initialized without providing input arguments.
  55. Some configurations requires inputs to be defined at init and have no default values, usually these are composite configs,
  56. (but not necessarily) such as [`~transformers.EncoderDecoderConfig`] or [`~RagConfig`]. They have to be initialized from
  57. two or more configs of type [`~transformers.PretrainedConfig`].
  58. - **keys_to_ignore_at_inference** (`list[str]`) -- A list of keys to ignore by default when looking at dictionary
  59. outputs of the model during inference.
  60. - **attribute_map** (`dict[str, str]`) -- A dict that maps model specific attribute names to the standardized
  61. naming of attributes.
  62. - **base_model_tp_plan** (`dict[str, Any]`) -- A dict that maps sub-modules FQNs of a base model to a tensor
  63. parallel plan applied to the sub-module when `model.tensor_parallel` is called.
  64. - **base_model_pp_plan** (`dict[str, tuple[list[str]]]`) -- A dict that maps child-modules of a base model to a
  65. pipeline parallel plan that enables users to place the child-module on the appropriate device.
  66. Common attributes (present in all subclasses):
  67. - **vocab_size** (`int`) -- The number of tokens in the vocabulary, which is also the first dimension of the
  68. embeddings matrix (this attribute may be missing for models that don't have a text modality like ViT).
  69. - **hidden_size** (`int`) -- The hidden size of the model.
  70. - **num_attention_heads** (`int`) -- The number of attention heads used in the multi-head attention layers of the
  71. model.
  72. - **num_hidden_layers** (`int`) -- The number of blocks in the model.
  73. <Tip warning={true}>
  74. Setting parameters for sequence generation in the model config is deprecated. For backward compatibility, loading
  75. some of them will still be possible, but attempting to overwrite them will throw an exception -- you should set
  76. them in a [~transformers.GenerationConfig]. Check the documentation of [~transformers.GenerationConfig] for more
  77. information about the individual parameters.
  78. </Tip>
  79. Arg:
  80. name_or_path (`str`, *optional*, defaults to `""`):
  81. Store the string that was passed to [`PreTrainedModel.from_pretrained`] or
  82. [`TFPreTrainedModel.from_pretrained`] as `pretrained_model_name_or_path` if the configuration was created
  83. with such a method.
  84. output_hidden_states (`bool`, *optional*, defaults to `False`):
  85. Whether or not the model should return all hidden-states.
  86. output_attentions (`bool`, *optional*, defaults to `False`):
  87. Whether or not the model should returns all attentions.
  88. return_dict (`bool`, *optional*, defaults to `True`):
  89. Whether or not the model should return a [`~transformers.utils.ModelOutput`] instead of a plain tuple.
  90. is_encoder_decoder (`bool`, *optional*, defaults to `False`):
  91. Whether the model is used as an encoder/decoder or not.
  92. is_decoder (`bool`, *optional*, defaults to `False`):
  93. Whether to only use the decoder in an encoder-decoder architecture, otherwise it has no effect on
  94. decoder-only or encoder-only architectures.
  95. cross_attention_hidden_size (`bool`, *optional*):
  96. The hidden size of the cross-attention layer in case the model is used as a decoder in an encoder-decoder
  97. setting and the cross-attention hidden dimension differs from `self.config.hidden_size`.
  98. add_cross_attention (`bool`, *optional*, defaults to `False`):
  99. Whether cross-attention layers should be added to the model. Note, this option is only relevant for models
  100. that can be used as decoder models within the [`EncoderDecoderModel`] class, which consists of all models
  101. in `AUTO_MODELS_FOR_CAUSAL_LM`.
  102. tie_encoder_decoder (`bool`, *optional*, defaults to `False`):
  103. Whether all encoder weights should be tied to their equivalent decoder weights. This requires the encoder
  104. and decoder model to have the exact same parameter names.
  105. prune_heads (`dict[int, list[int]]`, *optional*, defaults to `{}`):
  106. Pruned heads of the model. The keys are the selected layer indices and the associated values, the list of
  107. heads to prune in said layer.
  108. For instance `{1: [0, 2], 2: [2, 3]}` will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2.
  109. chunk_size_feed_forward (`int`, *optional*, defaults to `0`):
  110. The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that
  111. the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` <
  112. sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed
  113. Forward Chunking work?](../glossary.html#feed-forward-chunking).
  114. > Parameters for fine-tuning tasks
  115. architectures (`list[str]`, *optional*):
  116. Model architectures that can be used with the model pretrained weights.
  117. finetuning_task (`str`, *optional*):
  118. Name of the task used to fine-tune the model. This can be used when converting from an original (TensorFlow
  119. or PyTorch) checkpoint.
  120. id2label (`dict[int, str]`, *optional*):
  121. A map from index (for instance prediction index, or target index) to label.
  122. label2id (`dict[str, int]`, *optional*):
  123. A map from label to index for the model.
  124. num_labels (`int`, *optional*):
  125. Number of labels to use in the last layer added to the model, typically for a classification task.
  126. task_specific_params (`dict[str, Any]`, *optional*):
  127. Additional keyword arguments to store for the current task.
  128. problem_type (`str`, *optional*):
  129. Problem type for `XxxForSequenceClassification` models. Can be one of `"regression"`,
  130. `"single_label_classification"` or `"multi_label_classification"`.
  131. > Parameters linked to the tokenizer
  132. tokenizer_class (`str`, *optional*):
  133. The name of the associated tokenizer class to use (if none is set, will use the tokenizer associated to the
  134. model by default).
  135. prefix (`str`, *optional*):
  136. A specific prompt that should be added at the beginning of each text before calling the model.
  137. bos_token_id (`int`, *optional*):
  138. The id of the _beginning-of-stream_ token.
  139. pad_token_id (`int`, *optional*):
  140. The id of the _padding_ token.
  141. eos_token_id (`int`, *optional*):
  142. The id of the _end-of-stream_ token.
  143. decoder_start_token_id (`int`, *optional*):
  144. If an encoder-decoder model starts decoding with a different token than _bos_, the id of that token.
  145. sep_token_id (`int`, *optional*):
  146. The id of the _separation_ token.
  147. > PyTorch specific parameters
  148. torchscript (`bool`, *optional*, defaults to `False`):
  149. Whether or not the model should be used with Torchscript.
  150. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  151. Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
  152. model has a output word embedding layer.
  153. dtype (`str`, *optional*):
  154. The `dtype` of the weights. This attribute can be used to initialize the model to a non-default `dtype`
  155. (which is normally `float32`) and thus allow for optimal storage allocation. For example, if the saved
  156. model is `float16`, ideally we want to load it back using the minimal amount of memory needed to load
  157. `float16` weights.
  158. """
  159. model_type: str = ""
  160. base_config_key: str = ""
  161. sub_configs: dict[str, type["PretrainedConfig"]] = {}
  162. has_no_defaults_at_init: bool = False
  163. attribute_map: dict[str, str] = {}
  164. base_model_tp_plan: Optional[dict[str, Any]] = None
  165. base_model_pp_plan: Optional[dict[str, tuple[list[str]]]] = None
  166. base_model_ep_plan: Optional[dict[str, tuple[list[str]]]] = None
  167. _auto_class: Optional[str] = None
  168. def __setattr__(self, key, value):
  169. if key in super().__getattribute__("attribute_map"):
  170. key = super().__getattribute__("attribute_map")[key]
  171. super().__setattr__(key, value)
  172. def __getattribute__(self, key):
  173. if key != "attribute_map" and key in super().__getattribute__("attribute_map"):
  174. key = super().__getattribute__("attribute_map")[key]
  175. return super().__getattribute__(key)
  176. def __init__(
  177. self,
  178. *,
  179. # All models common arguments
  180. output_hidden_states: bool = False,
  181. output_attentions: bool = False,
  182. return_dict: bool = True,
  183. torchscript: bool = False,
  184. dtype: Optional[Union[str, "torch.dtype"]] = None,
  185. # Common arguments
  186. pruned_heads: Optional[dict[int, list[int]]] = None,
  187. tie_word_embeddings: bool = True,
  188. chunk_size_feed_forward: int = 0,
  189. is_encoder_decoder: bool = False,
  190. is_decoder: bool = False,
  191. cross_attention_hidden_size: Optional[int] = None,
  192. add_cross_attention: bool = False,
  193. tie_encoder_decoder: bool = False,
  194. # Fine-tuning task arguments
  195. architectures: Optional[list[str]] = None,
  196. finetuning_task: Optional[str] = None,
  197. id2label: Optional[dict[int, str]] = None,
  198. label2id: Optional[dict[str, int]] = None,
  199. num_labels: Optional[int] = None,
  200. task_specific_params: Optional[dict[str, Any]] = None,
  201. problem_type: Optional[str] = None,
  202. # Tokenizer kwargs
  203. tokenizer_class: Optional[str] = None,
  204. prefix: Optional[str] = None,
  205. bos_token_id: Optional[int] = None,
  206. pad_token_id: Optional[int] = None,
  207. eos_token_id: Optional[int] = None,
  208. sep_token_id: Optional[int] = None,
  209. decoder_start_token_id: Optional[int] = None,
  210. **kwargs,
  211. ):
  212. # Validation for some arguments
  213. if label2id is not None and not isinstance(label2id, dict):
  214. raise ValueError("Argument label2id should be a dictionary.")
  215. if id2label is not None and not isinstance(id2label, dict):
  216. raise ValueError("Argument id2label should be a dictionary.")
  217. if num_labels is not None and id2label is not None and len(id2label) != num_labels:
  218. logger.warning(
  219. f"You passed `num_labels={num_labels}` which is incompatible to "
  220. f"the `id2label` map of length `{len(id2label)}`."
  221. )
  222. if problem_type is not None and problem_type not in (
  223. "regression",
  224. "single_label_classification",
  225. "multi_label_classification",
  226. ):
  227. raise ValueError(
  228. f"The config parameter `problem_type` was not understood: received {problem_type} "
  229. "but only 'regression', 'single_label_classification' and 'multi_label_classification' are valid."
  230. )
  231. # BC for the `torch_dtype` argument instead of the simpler `dtype`
  232. # Do not warn, as it would otherwise always be triggered since most configs on the hub have `torch_dtype`
  233. if (torch_dtype := kwargs.pop("torch_dtype", None)) is not None:
  234. # If both are provided, keep `dtype`
  235. dtype = dtype if dtype is not None else torch_dtype
  236. if dtype is not None and isinstance(dtype, str) and is_torch_available():
  237. # we will start using self.dtype in v5, but to be consistent with
  238. # from_pretrained's dtype arg convert it to an actual torch.dtype object
  239. import torch
  240. dtype = getattr(torch, dtype)
  241. # Attributes common for all models
  242. self.return_dict = return_dict
  243. self.output_hidden_states = output_hidden_states
  244. self.torchscript = torchscript
  245. self.dtype = dtype
  246. self._output_attentions = output_attentions # has public property
  247. # Less common kwargs, only used by some models
  248. self.pruned_heads = pruned_heads if pruned_heads is not None else {}
  249. self.tie_word_embeddings = tie_word_embeddings
  250. self.chunk_size_feed_forward = chunk_size_feed_forward
  251. # Encoder-decoder models attributes
  252. self.is_encoder_decoder = is_encoder_decoder
  253. self.is_decoder = is_decoder # used in encoder-decoder models to differentiate encoder from decoder
  254. self.cross_attention_hidden_size = cross_attention_hidden_size
  255. self.add_cross_attention = add_cross_attention
  256. self.tie_encoder_decoder = tie_encoder_decoder
  257. # Fine-tuning task attributes
  258. self.architectures = architectures
  259. self.finetuning_task = finetuning_task
  260. self.id2label = id2label
  261. self.label2id = label2id
  262. self.task_specific_params = task_specific_params
  263. self.problem_type = problem_type
  264. if self.id2label is None:
  265. self._create_id_label_maps(num_labels if num_labels is not None else 2)
  266. else:
  267. # Keys are always strings in JSON so convert ids to int here.
  268. self.id2label = {int(key): value for key, value in self.id2label.items()}
  269. # Tokenizer attributes
  270. self.tokenizer_class = tokenizer_class
  271. self.prefix = prefix
  272. self.bos_token_id = bos_token_id
  273. self.pad_token_id = pad_token_id
  274. self.eos_token_id = eos_token_id
  275. self.sep_token_id = sep_token_id
  276. self.decoder_start_token_id = decoder_start_token_id
  277. # Retrocompatibility: Parameters for sequence generation. While we will keep the ability to load these
  278. # parameters, saving them will be deprecated. In a distant future, we won't need to load them.
  279. for parameter_name, default_value in self._get_global_generation_defaults().items():
  280. setattr(self, parameter_name, kwargs.pop(parameter_name, default_value))
  281. # Name or path to the pretrained checkpoint
  282. self._name_or_path = str(kwargs.pop("name_or_path", ""))
  283. self._commit_hash = kwargs.pop("_commit_hash", None)
  284. # Attention implementation to use, if relevant (it sets it recursively on sub-configs)
  285. self._attn_implementation = kwargs.pop("attn_implementation", None)
  286. # Drop the transformers version info
  287. self.transformers_version = kwargs.pop("transformers_version", None)
  288. # Deal with gradient checkpointing
  289. if kwargs.get("gradient_checkpointing", False):
  290. warnings.warn(
  291. "Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 "
  292. "Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the "
  293. "`Trainer` API, pass `gradient_checkpointing=True` in your `TrainingArguments`."
  294. )
  295. # Additional attributes without default values
  296. for key, value in kwargs.items():
  297. try:
  298. setattr(self, key, value)
  299. except AttributeError as err:
  300. logger.error(f"Can't set {key} with value {value} for {self}")
  301. raise err
  302. # TODO: remove later, deprecated arguments for TF models
  303. self.tf_legacy_loss = kwargs.pop("tf_legacy_loss", False)
  304. self.use_bfloat16 = kwargs.pop("use_bfloat16", False)
  305. def _create_id_label_maps(self, num_labels: int):
  306. self.id2label = {i: f"LABEL_{i}" for i in range(num_labels)}
  307. self.label2id = dict(zip(self.id2label.values(), self.id2label.keys()))
  308. @property
  309. def name_or_path(self) -> Optional[str]:
  310. return getattr(self, "_name_or_path", None)
  311. @name_or_path.setter
  312. def name_or_path(self, value):
  313. self._name_or_path = str(value) # Make sure that name_or_path is a string (for JSON encoding)
  314. @property
  315. def output_attentions(self):
  316. """
  317. `bool`: Whether or not the model should returns all attentions.
  318. """
  319. return self._output_attentions
  320. @output_attentions.setter
  321. def output_attentions(self, value: bool):
  322. # If we set `output_attentions` explicitly before the attn implementation, dispatch eager
  323. if value and self._attn_implementation is None:
  324. self._attn_implementation = "eager"
  325. if value and self._attn_implementation != "eager":
  326. raise ValueError(
  327. "The `output_attentions` attribute is not supported when using the `attn_implementation` set to "
  328. f"{self._attn_implementation}. Please set it to 'eager' instead."
  329. )
  330. self._output_attentions = value
  331. @property
  332. def use_return_dict(self) -> bool:
  333. """
  334. `bool`: Whether or not return [`~utils.ModelOutput`] instead of tuples.
  335. """
  336. # If torchscript is set, force `return_dict=False` to avoid jit errors
  337. return self.return_dict and not self.torchscript
  338. @property
  339. def num_labels(self) -> int:
  340. """
  341. `int`: The number of labels for classification models.
  342. """
  343. return len(self.id2label)
  344. @num_labels.setter
  345. def num_labels(self, num_labels: int):
  346. # we do not store `num_labels` attribute in config, but instead
  347. # compute it based on the length of the `id2label` map
  348. if self.id2label is None or self.num_labels != num_labels:
  349. self._create_id_label_maps(num_labels)
  350. @property
  351. def _attn_implementation(self):
  352. return self._attn_implementation_internal
  353. @_attn_implementation.setter
  354. def _attn_implementation(self, value: Optional[Union[str, dict]]):
  355. """We set it recursively on the sub-configs as well"""
  356. # Set if for current config
  357. current_attn = getattr(self, "_attn_implementation", None)
  358. attn_implementation = value if not isinstance(value, dict) else value.get("", current_attn)
  359. self._attn_implementation_internal = attn_implementation
  360. # Set it recursively on the subconfigs
  361. for subconfig_key in self.sub_configs:
  362. subconfig = getattr(self, subconfig_key, None)
  363. if subconfig is not None:
  364. current_subconfig_attn = getattr(subconfig, "_attn_implementation", None)
  365. sub_implementation = (
  366. value if not isinstance(value, dict) else value.get(subconfig_key, current_subconfig_attn)
  367. )
  368. subconfig._attn_implementation = sub_implementation
  369. @property
  370. def torch_dtype(self):
  371. logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
  372. return self.dtype
  373. @torch_dtype.setter
  374. def torch_dtype(self, value):
  375. logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
  376. self.dtype = value
  377. def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
  378. """
  379. Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the
  380. [`~PretrainedConfig.from_pretrained`] class method.
  381. Args:
  382. save_directory (`str` or `os.PathLike`):
  383. Directory where the configuration JSON file will be saved (will be created if it does not exist).
  384. push_to_hub (`bool`, *optional*, defaults to `False`):
  385. Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
  386. repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
  387. namespace).
  388. kwargs (`dict[str, Any]`, *optional*):
  389. Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
  390. """
  391. self._set_token_in_kwargs(kwargs)
  392. if os.path.isfile(save_directory):
  393. raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
  394. non_default_generation_parameters = self._get_non_default_generation_parameters()
  395. if len(non_default_generation_parameters) > 0:
  396. # TODO (joao): this should be an exception if the user has modified the loaded config. See #33886
  397. warnings.warn(
  398. "Some non-default generation parameters are set in the model config. These should go into either a) "
  399. "`model.generation_config` (as opposed to `model.config`); OR b) a GenerationConfig file "
  400. "(https://huggingface.co/docs/transformers/generation_strategies#save-a-custom-decoding-strategy-with-your-model)."
  401. "This warning will become an exception in the future."
  402. f"\nNon-default generation parameters: {str(non_default_generation_parameters)}",
  403. UserWarning,
  404. )
  405. os.makedirs(save_directory, exist_ok=True)
  406. if push_to_hub:
  407. commit_message = kwargs.pop("commit_message", None)
  408. repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
  409. repo_id = self._create_repo(repo_id, **kwargs)
  410. files_timestamps = self._get_files_timestamps(save_directory)
  411. # This attribute is important to know on load, but should not be serialized on save.
  412. if "transformers_weights" in self:
  413. delattr(self, "transformers_weights")
  414. # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
  415. # loaded from the Hub.
  416. if self._auto_class is not None:
  417. custom_object_save(self, save_directory, config=self)
  418. # If we save using the predefined names, we can load using `from_pretrained`
  419. output_config_file = os.path.join(save_directory, CONFIG_NAME)
  420. self.to_json_file(output_config_file, use_diff=True)
  421. logger.info(f"Configuration saved in {output_config_file}")
  422. if push_to_hub:
  423. self._upload_modified_files(
  424. save_directory,
  425. repo_id,
  426. files_timestamps,
  427. commit_message=commit_message,
  428. token=kwargs.get("token"),
  429. )
  430. @staticmethod
  431. def _set_token_in_kwargs(kwargs, token=None):
  432. """Temporary method to deal with `token` and `use_auth_token`.
  433. This method is to avoid apply the same changes in all model config classes that overwrite `from_pretrained`.
  434. Need to clean up `use_auth_token` in a follow PR.
  435. """
  436. # Some model config classes like CLIP define their own `from_pretrained` without the new argument `token` yet.
  437. if token is None:
  438. token = kwargs.pop("token", None)
  439. use_auth_token = kwargs.pop("use_auth_token", None)
  440. if use_auth_token is not None:
  441. warnings.warn(
  442. "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
  443. FutureWarning,
  444. )
  445. if token is not None:
  446. raise ValueError(
  447. "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
  448. )
  449. token = use_auth_token
  450. if token is not None:
  451. kwargs["token"] = token
  452. @classmethod
  453. def from_pretrained(
  454. cls: type[SpecificPretrainedConfigType],
  455. pretrained_model_name_or_path: Union[str, os.PathLike],
  456. cache_dir: Optional[Union[str, os.PathLike]] = None,
  457. force_download: bool = False,
  458. local_files_only: bool = False,
  459. token: Optional[Union[str, bool]] = None,
  460. revision: str = "main",
  461. **kwargs,
  462. ) -> SpecificPretrainedConfigType:
  463. r"""
  464. Instantiate a [`PretrainedConfig`] (or a derived class) from a pretrained model configuration.
  465. Args:
  466. pretrained_model_name_or_path (`str` or `os.PathLike`):
  467. This can be either:
  468. - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
  469. huggingface.co.
  470. - a path to a *directory* containing a configuration file saved using the
  471. [`~PretrainedConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
  472. - a path or url to a saved configuration JSON *file*, e.g., `./my_model_directory/configuration.json`.
  473. cache_dir (`str` or `os.PathLike`, *optional*):
  474. Path to a directory in which a downloaded pretrained model configuration should be cached if the
  475. standard cache should not be used.
  476. force_download (`bool`, *optional*, defaults to `False`):
  477. Whether or not to force to (re-)download the configuration files and override the cached versions if
  478. they exist.
  479. resume_download:
  480. Deprecated and ignored. All downloads are now resumed by default when possible.
  481. Will be removed in v5 of Transformers.
  482. proxies (`dict[str, str]`, *optional*):
  483. A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
  484. 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
  485. token (`str` or `bool`, *optional*):
  486. The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
  487. the token generated when running `hf auth login` (stored in `~/.huggingface`).
  488. revision (`str`, *optional*, defaults to `"main"`):
  489. The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
  490. git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
  491. identifier allowed by git.
  492. <Tip>
  493. To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
  494. </Tip>
  495. return_unused_kwargs (`bool`, *optional*, defaults to `False`):
  496. If `False`, then this function returns just the final configuration object.
  497. If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
  498. dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
  499. part of `kwargs` which has not been used to update `config` and is otherwise ignored.
  500. subfolder (`str`, *optional*, defaults to `""`):
  501. In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
  502. specify the folder name here.
  503. kwargs (`dict[str, Any]`, *optional*):
  504. The values in kwargs of any keys which are configuration attributes will be used to override the loaded
  505. values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
  506. by the `return_unused_kwargs` keyword parameter.
  507. Returns:
  508. [`PretrainedConfig`]: The configuration object instantiated from this pretrained model.
  509. Examples:
  510. ```python
  511. # We can't instantiate directly the base class *PretrainedConfig* so let's show the examples on a
  512. # derived class: BertConfig
  513. config = BertConfig.from_pretrained(
  514. "google-bert/bert-base-uncased"
  515. ) # Download configuration from huggingface.co and cache.
  516. config = BertConfig.from_pretrained(
  517. "./test/saved_model/"
  518. ) # E.g. config (or model) was saved using *save_pretrained('./test/saved_model/')*
  519. config = BertConfig.from_pretrained("./test/saved_model/my_configuration.json")
  520. config = BertConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
  521. assert config.output_attentions == True
  522. config, unused_kwargs = BertConfig.from_pretrained(
  523. "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
  524. )
  525. assert config.output_attentions == True
  526. assert unused_kwargs == {"foo": False}
  527. ```"""
  528. kwargs["cache_dir"] = cache_dir
  529. kwargs["force_download"] = force_download
  530. kwargs["local_files_only"] = local_files_only
  531. kwargs["revision"] = revision
  532. cls._set_token_in_kwargs(kwargs, token)
  533. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  534. if cls.base_config_key and cls.base_config_key in config_dict:
  535. config_dict = config_dict[cls.base_config_key]
  536. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  537. # sometimes the config has no `base_config_key` if the config is used in several composite models
  538. # e.g. LlamaConfig. In that case we try to see if there is match in `model_type` before raising a warning
  539. for v in config_dict.values():
  540. if isinstance(v, dict) and v.get("model_type") == cls.model_type:
  541. config_dict = v
  542. # raise warning only if we still can't see a match in `model_type`
  543. if config_dict["model_type"] != cls.model_type:
  544. logger.warning(
  545. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  546. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  547. )
  548. return cls.from_dict(config_dict, **kwargs)
  549. @classmethod
  550. def get_config_dict(
  551. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  552. ) -> tuple[dict[str, Any], dict[str, Any]]:
  553. """
  554. From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
  555. [`PretrainedConfig`] using `from_dict`.
  556. Parameters:
  557. pretrained_model_name_or_path (`str` or `os.PathLike`):
  558. The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
  559. Returns:
  560. `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the configuration object.
  561. """
  562. cls._set_token_in_kwargs(kwargs)
  563. original_kwargs = copy.deepcopy(kwargs)
  564. # Get config dict associated with the base config file
  565. config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
  566. if config_dict is None:
  567. return {}, kwargs
  568. if "_commit_hash" in config_dict:
  569. original_kwargs["_commit_hash"] = config_dict["_commit_hash"]
  570. # That config file may point us toward another config file to use.
  571. if "configuration_files" in config_dict:
  572. configuration_file = get_configuration_file(config_dict["configuration_files"])
  573. config_dict, kwargs = cls._get_config_dict(
  574. pretrained_model_name_or_path, _configuration_file=configuration_file, **original_kwargs
  575. )
  576. return config_dict, kwargs
  577. @classmethod
  578. def _get_config_dict(
  579. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  580. ) -> tuple[dict[str, Any], dict[str, Any]]:
  581. cache_dir = kwargs.pop("cache_dir", None)
  582. force_download = kwargs.pop("force_download", False)
  583. resume_download = kwargs.pop("resume_download", None)
  584. proxies = kwargs.pop("proxies", None)
  585. token = kwargs.pop("token", None)
  586. local_files_only = kwargs.pop("local_files_only", False)
  587. revision = kwargs.pop("revision", None)
  588. trust_remote_code = kwargs.pop("trust_remote_code", None)
  589. subfolder = kwargs.pop("subfolder", "")
  590. from_pipeline = kwargs.pop("_from_pipeline", None)
  591. from_auto_class = kwargs.pop("_from_auto", False)
  592. commit_hash = kwargs.pop("_commit_hash", None)
  593. gguf_file = kwargs.get("gguf_file")
  594. if trust_remote_code is True:
  595. logger.warning(
  596. "The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is"
  597. " ignored."
  598. )
  599. user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
  600. if from_pipeline is not None:
  601. user_agent["using_pipeline"] = from_pipeline
  602. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  603. is_local = os.path.isdir(pretrained_model_name_or_path)
  604. if os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
  605. # Special case when pretrained_model_name_or_path is a local file
  606. resolved_config_file = pretrained_model_name_or_path
  607. is_local = True
  608. elif is_remote_url(pretrained_model_name_or_path):
  609. configuration_file = pretrained_model_name_or_path if gguf_file is None else gguf_file
  610. resolved_config_file = download_url(pretrained_model_name_or_path)
  611. else:
  612. configuration_file = kwargs.pop("_configuration_file", CONFIG_NAME) if gguf_file is None else gguf_file
  613. try:
  614. # Load from local folder or from cache or download from model Hub and cache
  615. resolved_config_file = cached_file(
  616. pretrained_model_name_or_path,
  617. configuration_file,
  618. cache_dir=cache_dir,
  619. force_download=force_download,
  620. proxies=proxies,
  621. resume_download=resume_download,
  622. local_files_only=local_files_only,
  623. token=token,
  624. user_agent=user_agent,
  625. revision=revision,
  626. subfolder=subfolder,
  627. _commit_hash=commit_hash,
  628. )
  629. if resolved_config_file is None:
  630. return None, kwargs
  631. commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
  632. except OSError:
  633. # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
  634. # the original exception.
  635. raise
  636. except Exception:
  637. # For any other exception, we throw a generic error.
  638. raise OSError(
  639. f"Can't load the configuration of '{pretrained_model_name_or_path}'. If you were trying to load it"
  640. " from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
  641. f" name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory"
  642. f" containing a {configuration_file} file"
  643. )
  644. try:
  645. if gguf_file:
  646. config_dict = load_gguf_checkpoint(resolved_config_file, return_tensors=False)["config"]
  647. else:
  648. # Load config dict
  649. config_dict = cls._dict_from_json_file(resolved_config_file)
  650. config_dict["_commit_hash"] = commit_hash
  651. except (json.JSONDecodeError, UnicodeDecodeError):
  652. raise OSError(f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file.")
  653. if is_local:
  654. logger.info(f"loading configuration file {resolved_config_file}")
  655. else:
  656. logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")
  657. # timm models are not saved with the model_type in the config file
  658. if "model_type" not in config_dict and is_timm_config_dict(config_dict):
  659. config_dict["model_type"] = "timm_wrapper"
  660. return config_dict, kwargs
  661. @classmethod
  662. def from_dict(
  663. cls: type[SpecificPretrainedConfigType], config_dict: dict[str, Any], **kwargs
  664. ) -> SpecificPretrainedConfigType:
  665. """
  666. Instantiates a [`PretrainedConfig`] from a Python dictionary of parameters.
  667. Args:
  668. config_dict (`dict[str, Any]`):
  669. Dictionary that will be used to instantiate the configuration object. Such a dictionary can be
  670. retrieved from a pretrained checkpoint by leveraging the [`~PretrainedConfig.get_config_dict`] method.
  671. kwargs (`dict[str, Any]`):
  672. Additional parameters from which to initialize the configuration object.
  673. Returns:
  674. [`PretrainedConfig`]: The configuration object instantiated from those parameters.
  675. """
  676. return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
  677. # Those arguments may be passed along for our internal telemetry.
  678. # We remove them so they don't appear in `return_unused_kwargs`.
  679. kwargs.pop("_from_auto", None)
  680. kwargs.pop("_from_pipeline", None)
  681. # The commit hash might have been updated in the `config_dict`, we don't want the kwargs to erase that update.
  682. if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
  683. kwargs["_commit_hash"] = config_dict["_commit_hash"]
  684. # For BC on the old `torch_dtype`
  685. if (torch_dtype := kwargs.pop("torch_dtype", None)) is not None:
  686. logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
  687. # If both are present, use `dtype`
  688. kwargs["dtype"] = kwargs.get("dtype", torch_dtype)
  689. # We remove it from kwargs so that it does not appear in `return_unused_kwargs`.
  690. config_dict["attn_implementation"] = kwargs.pop("attn_implementation", None)
  691. config = cls(**config_dict)
  692. if hasattr(config, "pruned_heads"):
  693. config.pruned_heads = {int(key): value for key, value in config.pruned_heads.items()}
  694. # Update config with kwargs if needed
  695. if "num_labels" in kwargs and "id2label" in kwargs:
  696. num_labels = kwargs["num_labels"]
  697. id2label = kwargs["id2label"] if kwargs["id2label"] is not None else []
  698. if len(id2label) != num_labels:
  699. raise ValueError(
  700. f"You passed along `num_labels={num_labels}` with an incompatible id to label map: "
  701. f"{kwargs['id2label']}. Since those arguments are inconsistent with each other, you should remove "
  702. "one of them."
  703. )
  704. to_remove = []
  705. for key, value in kwargs.items():
  706. if hasattr(config, key):
  707. current_attr = getattr(config, key)
  708. # To authorize passing a custom subconfig as kwarg in models that have nested configs.
  709. # We need to update only custom kwarg values instead and keep other attributes in subconfig.
  710. if isinstance(current_attr, PretrainedConfig) and isinstance(value, dict):
  711. current_attr_updated = current_attr.to_dict()
  712. current_attr_updated.update(value)
  713. value = current_attr.__class__(**current_attr_updated)
  714. setattr(config, key, value)
  715. if key != "dtype":
  716. to_remove.append(key)
  717. for key in to_remove:
  718. kwargs.pop(key, None)
  719. logger.info(f"Model config {config}")
  720. if return_unused_kwargs:
  721. return config, kwargs
  722. else:
  723. return config
  724. @classmethod
  725. def from_json_file(
  726. cls: type[SpecificPretrainedConfigType], json_file: Union[str, os.PathLike]
  727. ) -> SpecificPretrainedConfigType:
  728. """
  729. Instantiates a [`PretrainedConfig`] from the path to a JSON file of parameters.
  730. Args:
  731. json_file (`str` or `os.PathLike`):
  732. Path to the JSON file containing the parameters.
  733. Returns:
  734. [`PretrainedConfig`]: The configuration object instantiated from that JSON file.
  735. """
  736. config_dict = cls._dict_from_json_file(json_file)
  737. return cls(**config_dict)
  738. @classmethod
  739. def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
  740. with open(json_file, encoding="utf-8") as reader:
  741. text = reader.read()
  742. return json.loads(text)
  743. def __eq__(self, other):
  744. return isinstance(other, PretrainedConfig) and (self.__dict__ == other.__dict__)
  745. def __repr__(self):
  746. return f"{self.__class__.__name__} {self.to_json_string()}"
  747. def __iter__(self):
  748. yield from self.__dict__
  749. def to_diff_dict(self) -> dict[str, Any]:
  750. """
  751. Removes all attributes from the configuration that correspond to the default config attributes for
  752. better readability, while always retaining the `config` attribute from the class. Serializes to a
  753. Python dictionary.
  754. Returns:
  755. dict[str, Any]: Dictionary of all the attributes that make up this configuration instance.
  756. """
  757. config_dict = self.to_dict()
  758. # Get the default config dict (from a fresh PreTrainedConfig instance)
  759. default_config_dict = PretrainedConfig().to_dict()
  760. # get class specific config dict
  761. class_config_dict = self.__class__().to_dict() if not self.has_no_defaults_at_init else {}
  762. serializable_config_dict = {}
  763. # Only serialize values that differ from the default config,
  764. # except always keep the 'config' attribute.
  765. for key, value in config_dict.items():
  766. if (
  767. isinstance(getattr(self, key, None), PretrainedConfig)
  768. and key in class_config_dict
  769. and isinstance(class_config_dict[key], dict)
  770. or key in self.sub_configs
  771. ):
  772. # For nested configs we need to clean the diff recursively
  773. diff = recursive_diff_dict(value, default_config_dict, config_obj=getattr(self, key, None))
  774. if "model_type" in value:
  775. # Needs to be set even if it's not in the diff
  776. diff["model_type"] = value["model_type"]
  777. serializable_config_dict[key] = diff
  778. elif (
  779. key not in default_config_dict
  780. or key == "transformers_version"
  781. or key == "vocab_file"
  782. or value != default_config_dict[key]
  783. or (key in default_config_dict and value != class_config_dict.get(key, value))
  784. ):
  785. serializable_config_dict[key] = value
  786. self._remove_keys_not_serialized(serializable_config_dict)
  787. # Key removed only in diff dict
  788. if "_name_or_path" in serializable_config_dict:
  789. del serializable_config_dict["_name_or_path"]
  790. if hasattr(self, "quantization_config"):
  791. serializable_config_dict["quantization_config"] = (
  792. self.quantization_config.to_dict()
  793. if not isinstance(self.quantization_config, dict)
  794. else self.quantization_config
  795. )
  796. self.dict_dtype_to_str(serializable_config_dict)
  797. return serializable_config_dict
  798. def to_dict(self) -> dict[str, Any]:
  799. """
  800. Serializes this instance to a Python dictionary.
  801. Returns:
  802. `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  803. """
  804. output = copy.deepcopy(self.__dict__)
  805. if hasattr(self.__class__, "model_type"):
  806. output["model_type"] = self.__class__.model_type
  807. # Transformers version when serializing the model
  808. output["transformers_version"] = __version__
  809. for key, value in output.items():
  810. # Deal with nested configs like CLIP
  811. if isinstance(value, PretrainedConfig):
  812. value = value.to_dict()
  813. del value["transformers_version"]
  814. output[key] = value
  815. self._remove_keys_not_serialized(output)
  816. if hasattr(self, "quantization_config"):
  817. output["quantization_config"] = (
  818. self.quantization_config.to_dict()
  819. if not isinstance(self.quantization_config, dict)
  820. else self.quantization_config
  821. )
  822. self.dict_dtype_to_str(output)
  823. return output
  824. def to_json_string(self, use_diff: bool = True) -> str:
  825. """
  826. Serializes this instance to a JSON string.
  827. Args:
  828. use_diff (`bool`, *optional*, defaults to `True`):
  829. If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
  830. is serialized to JSON string.
  831. Returns:
  832. `str`: String containing all the attributes that make up this configuration instance in JSON format.
  833. """
  834. if use_diff is True:
  835. config_dict = self.to_diff_dict()
  836. else:
  837. config_dict = self.to_dict()
  838. return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
  839. def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
  840. """
  841. Save this instance to a JSON file.
  842. Args:
  843. json_file_path (`str` or `os.PathLike`):
  844. Path to the JSON file in which this configuration instance's parameters will be saved.
  845. use_diff (`bool`, *optional*, defaults to `True`):
  846. If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
  847. is serialized to JSON file.
  848. """
  849. with open(json_file_path, "w", encoding="utf-8") as writer:
  850. writer.write(self.to_json_string(use_diff=use_diff))
  851. def update(self, config_dict: dict[str, Any]):
  852. """
  853. Updates attributes of this class with attributes from `config_dict`.
  854. Args:
  855. config_dict (`dict[str, Any]`): Dictionary of attributes that should be updated for this class.
  856. """
  857. for key, value in config_dict.items():
  858. setattr(self, key, value)
  859. def update_from_string(self, update_str: str):
  860. """
  861. Updates attributes of this class with attributes from `update_str`.
  862. The expected format is ints, floats and strings as is, and for booleans use `true` or `false`. For example:
  863. "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
  864. The keys to change have to already exist in the config object.
  865. Args:
  866. update_str (`str`): String with attributes that should be updated for this class.
  867. """
  868. d = dict(x.split("=") for x in update_str.split(","))
  869. for k, v in d.items():
  870. if not hasattr(self, k):
  871. raise ValueError(f"key {k} isn't in the original config dict")
  872. old_v = getattr(self, k)
  873. if isinstance(old_v, bool):
  874. if v.lower() in ["true", "1", "y", "yes"]:
  875. v = True
  876. elif v.lower() in ["false", "0", "n", "no"]:
  877. v = False
  878. else:
  879. raise ValueError(f"can't derive true or false from {v} (key {k})")
  880. elif isinstance(old_v, int):
  881. v = int(v)
  882. elif isinstance(old_v, float):
  883. v = float(v)
  884. elif not isinstance(old_v, str):
  885. raise TypeError(
  886. f"You can only update int, float, bool or string values in the config, got {v} for key {k}"
  887. )
  888. setattr(self, k, v)
  889. def dict_dtype_to_str(self, d: dict[str, Any]) -> None:
  890. """
  891. Checks whether the passed dictionary and its nested dicts have a *dtype* key and if it's not None,
  892. converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
  893. string, which can then be stored in the json format.
  894. """
  895. if d.get("dtype") is not None:
  896. if isinstance(d["dtype"], dict):
  897. d["dtype"] = {k: str(v).split(".")[-1] for k, v in d["dtype"].items()}
  898. # models like Emu3 can have "dtype" as token in config's vocabulary map,
  899. # so we also exclude int type here to avoid error in this special case.
  900. elif not isinstance(d["dtype"], (str, int)):
  901. d["dtype"] = str(d["dtype"]).split(".")[1]
  902. for value in d.values():
  903. if isinstance(value, dict):
  904. self.dict_dtype_to_str(value)
  905. def _remove_keys_not_serialized(self, d: dict[str, Any]) -> None:
  906. """
  907. Checks and removes if there are any keys in the dict that should not be serialized when saving the config.
  908. Runs recursive check on the dict, to remove from all sub configs.
  909. """
  910. if hasattr(self, "quantization_config"):
  911. # Pop the `_pre_quantization_dtype` as torch.dtypes are not serializable.
  912. _ = d.pop("_pre_quantization_dtype", None)
  913. if "_auto_class" in d:
  914. del d["_auto_class"]
  915. if "_output_attentions" in d:
  916. d["output_attentions"] = d.pop("_output_attentions")
  917. if "_commit_hash" in d:
  918. del d["_commit_hash"]
  919. if "_attn_implementation_internal" in d:
  920. del d["_attn_implementation_internal"]
  921. # Do not serialize `base_model_tp_plan` for now
  922. if "base_model_tp_plan" in d:
  923. del d["base_model_tp_plan"]
  924. # Do not serialize `base_model_pp_plan` for now
  925. if "base_model_pp_plan" in d:
  926. del d["base_model_pp_plan"]
  927. for value in d.values():
  928. if isinstance(value, dict):
  929. self._remove_keys_not_serialized(value)
  930. @classmethod
  931. def register_for_auto_class(cls, auto_class="AutoConfig"):
  932. """
  933. Register this class with a given auto class. This should only be used for custom configurations as the ones in
  934. the library are already mapped with `AutoConfig`.
  935. Args:
  936. auto_class (`str` or `type`, *optional*, defaults to `"AutoConfig"`):
  937. The auto class to register this new configuration with.
  938. """
  939. if not isinstance(auto_class, str):
  940. auto_class = auto_class.__name__
  941. import transformers.models.auto as auto_module
  942. if not hasattr(auto_module, auto_class):
  943. raise ValueError(f"{auto_class} is not a valid auto class.")
  944. cls._auto_class = auto_class
  945. @staticmethod
  946. def _get_global_generation_defaults() -> dict[str, Any]:
  947. return {
  948. "max_length": 20,
  949. "min_length": 0,
  950. "do_sample": False,
  951. "early_stopping": False,
  952. "num_beams": 1,
  953. "temperature": 1.0,
  954. "top_k": 50,
  955. "top_p": 1.0,
  956. "typical_p": 1.0,
  957. "repetition_penalty": 1.0,
  958. "length_penalty": 1.0,
  959. "no_repeat_ngram_size": 0,
  960. "encoder_no_repeat_ngram_size": 0,
  961. "bad_words_ids": None,
  962. "num_return_sequences": 1,
  963. "output_scores": False,
  964. "return_dict_in_generate": False,
  965. "forced_bos_token_id": None,
  966. "forced_eos_token_id": None,
  967. "remove_invalid_values": False,
  968. "exponential_decay_length_penalty": None,
  969. "suppress_tokens": None,
  970. "begin_suppress_tokens": None,
  971. # Deprecated arguments (moved to the Hub). TODO joao, manuel: remove in v4.62.0
  972. "num_beam_groups": 1,
  973. "diversity_penalty": 0.0,
  974. }
  975. def _get_non_default_generation_parameters(self) -> dict[str, Any]:
  976. """
  977. Gets the non-default generation parameters on the PretrainedConfig instance
  978. """
  979. non_default_generation_parameters = {}
  980. decoder_attribute_name = None
  981. # Composite models don't have a default config, use their decoder config as a fallback for default values
  982. # If no known pattern is matched, then `default_config = None` -> check against the global generation defaults
  983. try:
  984. default_config = self.__class__()
  985. except ValueError:
  986. decoder_config = self.get_text_config(decoder=True)
  987. if decoder_config is not self:
  988. default_config = decoder_config.__class__()
  989. else:
  990. default_config = None
  991. # If it is a composite model, we want to check the subconfig that will be used for generation
  992. self_decoder_config = self if decoder_attribute_name is None else getattr(self, decoder_attribute_name)
  993. for parameter_name, default_global_value in self._get_global_generation_defaults().items():
  994. if hasattr(self_decoder_config, parameter_name):
  995. is_default_in_config = is_default_generation_value = None
  996. parameter_value = getattr(self_decoder_config, parameter_name)
  997. # Three cases in which is okay for the model config to hold generation config parameters:
  998. # 1. The parameter is set to `None`, effectively delegating its value to the generation config
  999. if parameter_value is None:
  1000. continue
  1001. # 2. If we have a default config, then the instance should hold the same generation defaults
  1002. if default_config is not None:
  1003. is_default_in_config = parameter_value == getattr(default_config, parameter_name)
  1004. # 3. if we don't have a default config, then the instance should hold the global generation defaults
  1005. else:
  1006. is_default_generation_value = parameter_value == default_global_value
  1007. is_non_default = (is_default_in_config is False) or (
  1008. is_default_in_config is None and is_default_generation_value is False
  1009. )
  1010. if is_non_default:
  1011. non_default_generation_parameters[parameter_name] = getattr(self_decoder_config, parameter_name)
  1012. return non_default_generation_parameters
  1013. def get_text_config(self, decoder=None, encoder=None) -> "PretrainedConfig":
  1014. """
  1015. Returns the text config related to the text input (encoder) or text output (decoder) of the model. The
  1016. `decoder` and `encoder` input arguments can be used to specify which end of the model we are interested in,
  1017. which is useful on models that have both text input and output modalities.
  1018. There are three possible outcomes of using this method:
  1019. 1. On most models, it returns the original config instance itself.
  1020. 2. On newer (2024+) composite models, it returns the text section of the config, which is nested under a set
  1021. of valid names.
  1022. 3. On older (2023-) composite models, it discards decoder-only parameters when `encoder=True` and vice-versa.
  1023. Args:
  1024. decoder (`Optional[bool]`, *optional*):
  1025. If set to `True`, then only search for decoder config names.
  1026. encoder (`Optional[bool]`, *optional*):
  1027. If set to `True`, then only search for encoder config names.
  1028. """
  1029. return_both = decoder == encoder # both unset or both set -> search all possible names
  1030. decoder_possible_text_config_names = ("decoder", "generator", "text_config")
  1031. encoder_possible_text_config_names = ("text_encoder",)
  1032. if return_both:
  1033. possible_text_config_names = encoder_possible_text_config_names + decoder_possible_text_config_names
  1034. elif decoder:
  1035. possible_text_config_names = decoder_possible_text_config_names
  1036. else:
  1037. possible_text_config_names = encoder_possible_text_config_names
  1038. valid_text_config_names = []
  1039. for text_config_name in possible_text_config_names:
  1040. if hasattr(self, text_config_name):
  1041. text_config = getattr(self, text_config_name, None)
  1042. if text_config is not None:
  1043. valid_text_config_names += [text_config_name]
  1044. if len(valid_text_config_names) > 1:
  1045. raise ValueError(
  1046. f"Multiple valid text configs were found in the model config: {valid_text_config_names}. In this "
  1047. "case, using `get_text_config()` would be ambiguous. Please specify the desired text config directly, "
  1048. "e.g. `text_config = config.sub_config_name`"
  1049. )
  1050. elif len(valid_text_config_names) == 1:
  1051. config_to_return = getattr(self, valid_text_config_names[0])
  1052. else:
  1053. config_to_return = self
  1054. # handle legacy models with flat config structure, when we only want one of the configs
  1055. if not return_both and len(valid_text_config_names) == 0 and config_to_return.is_encoder_decoder:
  1056. config_to_return = copy.deepcopy(config_to_return)
  1057. prefix_to_discard = "encoder" if decoder else "decoder"
  1058. prefix_to_keep = "decoder" if decoder else "encoder"
  1059. for key in config_to_return.to_dict():
  1060. # NOTE: We don't want to discard the key if it is mapped from a different attribute name at read time
  1061. if key.startswith(prefix_to_discard) and key not in config_to_return.attribute_map.values():
  1062. delattr(config_to_return, key)
  1063. if key.startswith(prefix_to_keep):
  1064. # [encoder/decoder]_layers -> num_hidden_layers
  1065. if key == prefix_to_keep + "_layers":
  1066. new_key = "num_hidden_layers"
  1067. # [encoder/decoder]_attention_heads -> num_attention_heads
  1068. elif key == prefix_to_keep + "_attention_heads":
  1069. new_key = "num_attention_heads"
  1070. # e.g. encoder_hidden_act -> hidden_act
  1071. else:
  1072. new_key = key[len(prefix_to_keep) + 1 :]
  1073. # Does the class map the new key into a different attribute name at read time? if so, let's write
  1074. # into that attribute instead
  1075. if new_key in config_to_return.attribute_map:
  1076. new_key = config_to_return.attribute_map[new_key]
  1077. value = getattr(config_to_return, key)
  1078. delattr(config_to_return, key)
  1079. setattr(config_to_return, new_key, value)
  1080. return config_to_return
  1081. @classmethod
  1082. def from_text_vision_configs(cls, text_config, vision_config, **kwargs):
  1083. r"""
  1084. Instantiate a model config (or a derived class) from text model configuration and vision model
  1085. configuration.
  1086. Returns:
  1087. [`PreTrainedConfig`]: An instance of a configuration object
  1088. """
  1089. warnings.warn(
  1090. "The `from_text_vision_configs` method is deprecated and will be removed in v4.60 of Transformers. Please instantiate "
  1091. "the config class directly with `MyConfig(text_config=text_config, vision_config=vision_config, **kwargs)` instead.",
  1092. FutureWarning,
  1093. )
  1094. return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
  1095. @classmethod
  1096. def from_text_audio_configs(cls, text_config, audio_config, **kwargs):
  1097. r"""
  1098. Instantiate a model config (or a derived class) from text model configuration and audio model
  1099. configuration.
  1100. Returns:
  1101. [`PreTrainedConfig`]: An instance of a configuration object
  1102. """
  1103. warnings.warn(
  1104. "The `from_text_audio_configs` method is deprecated and will be removed in v4.60 of Transformers. Please instantiate "
  1105. "the config class directly with `MyConfig(text_config=text_config, audio_config=audio_config, **kwargs)` instead.",
  1106. FutureWarning,
  1107. )
  1108. return cls(text_config=text_config.to_dict(), audio_config=audio_config.to_dict(), **kwargs)
  1109. def get_configuration_file(configuration_files: list[str]) -> str:
  1110. """
  1111. Get the configuration file to use for this version of transformers.
  1112. Args:
  1113. configuration_files (`list[str]`): The list of available configuration files.
  1114. Returns:
  1115. `str`: The configuration file to use.
  1116. """
  1117. configuration_files_map = {}
  1118. for file_name in configuration_files:
  1119. if file_name.startswith("config.") and file_name.endswith(".json") and file_name != "config.json":
  1120. v = file_name.removeprefix("config.").removesuffix(".json")
  1121. configuration_files_map[v] = file_name
  1122. available_versions = sorted(configuration_files_map.keys())
  1123. # Defaults to FULL_CONFIGURATION_FILE and then try to look at some newer versions.
  1124. configuration_file = CONFIG_NAME
  1125. transformers_version = version.parse(__version__)
  1126. for v in available_versions:
  1127. if version.parse(v) <= transformers_version:
  1128. configuration_file = configuration_files_map[v]
  1129. else:
  1130. # No point going further since the versions are sorted.
  1131. break
  1132. return configuration_file
  1133. def recursive_diff_dict(dict_a, dict_b, config_obj=None):
  1134. """
  1135. Helper function to recursively take the diff between two nested dictionaries. The resulting diff only contains the
  1136. values from `dict_a` that are different from values in `dict_b`.
  1137. dict_b : the default config dictionary. We want to remove values that are in this one
  1138. """
  1139. diff = {}
  1140. default = config_obj.__class__().to_dict() if config_obj is not None else {}
  1141. for key, value in dict_a.items():
  1142. obj_value = getattr(config_obj, str(key), None)
  1143. if isinstance(obj_value, PretrainedConfig) and key in dict_b and isinstance(dict_b[key], dict):
  1144. diff_value = recursive_diff_dict(value, dict_b[key], config_obj=obj_value)
  1145. diff[key] = diff_value
  1146. elif key not in dict_b or (value != default[key]):
  1147. diff[key] = value
  1148. return diff
  1149. PretrainedConfig.push_to_hub = copy_func(PretrainedConfig.push_to_hub)
  1150. if PretrainedConfig.push_to_hub.__doc__ is not None:
  1151. PretrainedConfig.push_to_hub.__doc__ = PretrainedConfig.push_to_hub.__doc__.format(
  1152. object="config", object_class="AutoConfig", object_files="configuration file"
  1153. )
  1154. ALLOWED_LAYER_TYPES = (
  1155. "full_attention",
  1156. "sliding_attention",
  1157. "chunked_attention",
  1158. "linear_attention", # used in minimax
  1159. )
  1160. def layer_type_validation(layer_types: list[str], num_hidden_layers: Optional[int] = None):
  1161. """Check that `layer_types` is correctly defined."""
  1162. if not all(layer_type in ALLOWED_LAYER_TYPES for layer_type in layer_types):
  1163. raise ValueError(f"The `layer_types` entries must be in {ALLOWED_LAYER_TYPES}")
  1164. if num_hidden_layers is not None and num_hidden_layers != len(layer_types):
  1165. raise ValueError(
  1166. f"`num_hidden_layers` ({num_hidden_layers}) must be equal to the number of layer types "
  1167. f"({len(layer_types)})"
  1168. )