configuration_utils.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import annotations
  15. import copy
  16. import json
  17. import os
  18. import re
  19. import warnings
  20. from typing import Any, Dict, List, Optional, Tuple, Union
  21. import paddle
  22. from ......utils import logging
  23. from ..utils import CONFIG_NAME, LEGACY_CONFIG_NAME, resolve_file_path
  24. _re_configuration_file = re.compile(r"config\.(.*)\.json")
  25. def attribute_map(config: PretrainedConfig, kwargs: Dict[str, Any]) -> Dict[str, Any]:
  26. """map the <old-attr> to <new-attr> with configuration
  27. Args:
  28. config (PretrainedConfig): the instance of PretrainedConfig
  29. kwargs (Dict[str, Any]): the kwargs of attribute
  30. """
  31. for old_key, new_key in config.attribute_map.items():
  32. if old_key in kwargs:
  33. if new_key in kwargs:
  34. logging.warning(
  35. f"receive param<{old_key}> and param<{new_key}>, but the first one will be adopt"
  36. )
  37. kwargs[new_key] = kwargs.pop(old_key)
  38. return kwargs
  39. def convert_to_legacy_config(
  40. attribute_map: Dict[str, str], config: Dict[str, Any]
  41. ) -> Dict[str, Any]:
  42. """
  43. works when there are different fields between huggingface and paddle
  44. Args:
  45. attribute_map (Dict[str, str]): mapping of between standard config and paddle config
  46. config (Dict[str, Any]): config of huggingface transformers models
  47. Returns: the config which can be mapped into config of paddle model
  48. """
  49. if "init_args" in config:
  50. args = []
  51. for init_arg in config["init_args"]:
  52. init_arg = convert_to_legacy_config(attribute_map, init_arg)
  53. args.append(init_arg)
  54. config["init_args"] = args
  55. # TODO(wj-Mcat): to improve compatibility for: old local config and new PretrainedConfig, eg:
  56. # { "init_args": [], "init_class": "", "num_classes": 12 }
  57. for standard_field, paddle_field in attribute_map.items():
  58. value = config.pop(standard_field, None) or config.pop(paddle_field, None)
  59. if value is not None:
  60. config[paddle_field] = value
  61. return config
  62. def flatten_model_config(config: dict) -> dict:
  63. """flatten the model config which can be old-style model config
  64. Args:
  65. config (dict): the source of config which can be flatten config or nest config
  66. Returns:
  67. dict: the flatten config
  68. """
  69. # 1. extract the init_args into the top level
  70. init_args = config.pop("init_args", [])
  71. index = 0
  72. while index < len(init_args):
  73. if isinstance(init_args[index], dict):
  74. for key, value in init_args[index].items():
  75. if key not in config:
  76. config[key] = value
  77. init_args.pop(index)
  78. else:
  79. index += 1
  80. if init_args:
  81. config["init_args"] = init_args
  82. # 2. convert `init_class` into `architectures`
  83. if "init_class" in config:
  84. config["architectures"] = [config.pop("init_class")]
  85. return config
  86. def set_expected_keys(config, llm_meta, kwargs):
  87. for key, value in llm_meta.items():
  88. if key in kwargs:
  89. value = kwargs.pop(key)
  90. setattr(config, key, value)
  91. return kwargs
  92. class LlmMetaConfig:
  93. op_fusion_attributes = [
  94. # name, type, default_value, comment
  95. (
  96. "use_flash_attention",
  97. bool,
  98. False,
  99. "Whether to use flash attention to accelerate training.",
  100. ),
  101. ("use_fused_rms_norm", bool, False, "llama or other model, use_fused_rms_norm"),
  102. ("use_fused_rope", bool, False, "Enable rope fusion or not."),
  103. ("use_fused_linear", bool, False, "GPT3 model, use fused linear layer"),
  104. (
  105. "use_fused_dropout_add",
  106. bool,
  107. False,
  108. "GPT3 model, use fused `dropout + residual add` op.",
  109. ),
  110. (
  111. "use_fused_linear_cross_entropy",
  112. bool,
  113. False,
  114. "use fused `linear + cross_entropy` fuse op.",
  115. ),
  116. ]
  117. hybrid_parallel_attributes = [
  118. # tensor_parallel
  119. ("tensor_parallel_degree", int, 1, "tensor_parallel_degree"),
  120. ("tensor_parallel_rank", int, 0, "tensor_parallel_rank"),
  121. ("tensor_parallel_output", bool, True, "tensor_parallel_output"),
  122. # pipeline_parallel
  123. ("pipeline_parallel_degree", int, 1, "pipeline_parallel_degree"),
  124. ("virtual_pp_degree", int, 1, "Virtual pipeline degree"),
  125. # pp refine recompute
  126. ("no_recompute_layers", Optional[List[int]], None, "no_recompute_layers"),
  127. (
  128. "pp_recompute_interval",
  129. int,
  130. 1,
  131. "The interval for the number of layers at which recomputation occurs. A value of 0 indicates no recomputation. Default is 0.",
  132. ),
  133. # sep_parallel
  134. ("sep_parallel_degree", int, 1, "sep_parallel_degree"),
  135. ("context_parallel_degree", int, 1, "context_parallel_degree"),
  136. ("sequence_parallel", bool, False, "Whether to use sequence parallel"),
  137. (
  138. "fuse_sequence_parallel_allreduce",
  139. bool,
  140. False,
  141. "Whether to use fuse sequence parallel allreduce",
  142. ),
  143. ]
  144. recompute_attributes = [
  145. ("recompute", bool, False, "recompute"),
  146. (
  147. "recompute_granularity",
  148. str,
  149. "full",
  150. "Recompute granularity, Choose among ['full', 'core_attn', 'full_attn']",
  151. ),
  152. ("recompute_use_reentrant", bool, False, "recompute_use_reentrant"),
  153. # refined_recompute attributes
  154. (
  155. "refined_recompute",
  156. str,
  157. "",
  158. "refined_recompute, Choose from 'mlp_row_ln', 'mlp_column_ln', 'attention_row_ln', 'attention_column_ln', 'flash_attn']",
  159. ),
  160. ("offload_recompute_inputs", bool, False, "offload_recompute_inputs"),
  161. ]
  162. @classmethod
  163. def _get_defaults(cls):
  164. ret = {}
  165. for attrs in [
  166. cls.op_fusion_attributes,
  167. cls.hybrid_parallel_attributes,
  168. cls.recompute_attributes,
  169. ]:
  170. for attr in attrs:
  171. # return dict of key and default values
  172. ret[attr[0]] = attr[2]
  173. return ret
  174. @classmethod
  175. def _get_all_meta(cls):
  176. ret = []
  177. for attrs in [
  178. cls.op_fusion_attributes,
  179. cls.hybrid_parallel_attributes,
  180. cls.recompute_attributes,
  181. ]:
  182. for attr in attrs:
  183. # return dict of key and default values
  184. ret.append(attr)
  185. return ret
  186. @classmethod
  187. def _get_unsavable_keys(cls):
  188. ret = set()
  189. for attrs in [
  190. cls.op_fusion_attributes,
  191. cls.hybrid_parallel_attributes,
  192. cls.recompute_attributes,
  193. ]:
  194. for attr in attrs:
  195. ret.add(attr[0])
  196. return ret
  197. @classmethod
  198. def set_llm_config(cls, config, args):
  199. for key, value in cls._get_defaults().items():
  200. setattr(config, key, getattr(args, key, value))
  201. class PretrainedConfig:
  202. r"""
  203. Base class for all configuration classes. Handles a few parameters common to all models' configurations as well as
  204. methods for loading/downloading/saving configurations.
  205. <Tip>
  206. A configuration file can be loaded and saved to disk. Loading the configuration file and using this file to
  207. initialize a model does **not** load the model weights. It only affects the model's configuration.
  208. </Tip>
  209. Class attributes (overridden by derived classes):
  210. - **model_type** (`str`) -- An identifier for the model type, serialized into the JSON file, and used to recreate
  211. the correct object in [`~paddlenlp.AutoConfig`].
  212. - **is_composition** (`bool`) -- Whether the config class is composed of multiple sub-configs. In this case the
  213. config has to be initialized from two or more configs of type [`~paddlenlp.PretrainedConfig`] like:
  214. [`~paddlenlp.EncoderDecoderConfig`] or [`~RagConfig`].
  215. - **keys_to_ignore_at_inference** (`List[str]`) -- A list of keys to ignore by default when looking at dictionary
  216. outputs of the model during inference.
  217. - **attribute_map** (`Dict[str, str]`) -- A dict that maps model specific attribute names to the standardized
  218. naming of attributes.
  219. Common attributes (present in all subclasses):
  220. - **vocab_size** (`int`) -- The number of tokens in the vocabulary, which is also the first dimension of the
  221. embeddings matrix (this attribute may be missing for models that don't have a text modality like ViT).
  222. - **hidden_size** (`int`) -- The hidden size of the model.
  223. - **num_attention_heads** (`int`) -- The number of attention heads used in the multi-head attention layers of the
  224. model.
  225. - **num_hidden_layers** (`int`) -- The number of blocks in the model.
  226. Arg:
  227. name_or_path (`str`, *optional*, defaults to `""`):
  228. Store the string that was passed to [`PreTrainedModel.from_pretrained`] or
  229. [`PreTrainedModel.from_pretrained`] as `pretrained_model_name_or_path` if the configuration was created
  230. with such a method.
  231. output_hidden_states (`bool`, *optional*, defaults to `False`):
  232. Whether or not the model should return all hidden-states.
  233. output_attentions (`bool`, *optional*, defaults to `False`):
  234. Whether or not the model should returns all attentions.
  235. return_dict (`bool`, *optional*, defaults to `True`):
  236. Whether or not the model should return a [`~paddlenlp.transformers.model_outputs.ModelOutput`] instead of a plain tuple.
  237. is_encoder_decoder (`bool`, *optional*, defaults to `False`):
  238. Whether the model is used as an encoder/decoder or not.
  239. is_decoder (`bool`, *optional*, defaults to `False`):
  240. Whether the model is used as decoder or not (in which case it's used as an encoder).
  241. cross_attention_hidden_size** (`bool`, *optional*):
  242. The hidden size of the cross-attention layer in case the model is used as a decoder in an encoder-decoder
  243. setting and the cross-attention hidden dimension differs from `self.config.hidden_size`.
  244. add_cross_attention (`bool`, *optional*, defaults to `False`):
  245. Whether cross-attention layers should be added to the model. Note, this option is only relevant for models
  246. that can be used as decoder models within the [`EncoderDecoderModel`] class, which consists of all models
  247. in `AUTO_MODELS_FOR_CAUSAL_LM`.
  248. tie_encoder_decoder (`bool`, *optional*, defaults to `False`):
  249. Whether all encoder weights should be tied to their equivalent decoder weights. This requires the encoder
  250. and decoder model to have the exact same parameter names.
  251. prune_heads (`Dict[int, List[int]]`, *optional*, defaults to `{}`):
  252. Pruned heads of the model. The keys are the selected layer indices and the associated values, the list of
  253. heads to prune in said layer.
  254. 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.
  255. chunk_size_feed_forward (`int`, *optional*, defaults to `0`):
  256. The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that
  257. the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` <
  258. sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed
  259. Forward Chunking work?](../glossary.html#feed-forward-chunking).
  260. > Parameters for sequence generation
  261. max_length (`int`, *optional*, defaults to 20):
  262. Maximum length that will be used by default in the `generate` method of the model.
  263. min_length (`int`, *optional*, defaults to 10):
  264. Minimum length that will be used by default in the `generate` method of the model.
  265. do_sample (`bool`, *optional*, defaults to `False`):
  266. Flag that will be used by default in the `generate` method of the model. Whether or not to use sampling ;
  267. use greedy decoding otherwise.
  268. early_stopping (`bool`, *optional*, defaults to `False`):
  269. Flag that will be used by default in the `generate` method of the model. Whether to stop the beam search
  270. when at least `num_beams` sentences are finished per batch or not.
  271. num_beams (`int`, *optional*, defaults to 1):
  272. Number of beams for beam search that will be used by default in the `generate` method of the model. 1 means
  273. no beam search.
  274. num_beam_groups (`int`, *optional*, defaults to 1):
  275. Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams
  276. that will be used by default in the `generate` method of the model. 1 means no group beam search.
  277. diversity_penalty (`float`, *optional*, defaults to 0.0):
  278. Value to control diversity for group beam search. that will be used by default in the `generate` method of
  279. the model. 0 means no diversity penalty. The higher the penalty, the more diverse are the outputs.
  280. temperature (`float`, *optional*, defaults to 1):
  281. The value used to module the next token probabilities that will be used by default in the `generate` method
  282. of the model. Must be strictly positive.
  283. top_k (`int`, *optional*, defaults to 50):
  284. Number of highest probability vocabulary tokens to keep for top-k-filtering that will be used by default in
  285. the `generate` method of the model.
  286. top_p (`float`, *optional*, defaults to 1):
  287. Value that will be used by default in the `generate` method of the model for `top_p`. If set to float < 1,
  288. only the most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
  289. repetition_penalty (`float`, *optional*, defaults to 1):
  290. Parameter for repetition penalty that will be used by default in the `generate` method of the model. 1.0
  291. means no penalty.
  292. length_penalty (`float`, *optional*, defaults to 1):
  293. Exponential penalty to the length that will be used by default in the `generate` method of the model.
  294. no_repeat_ngram_size (`int`, *optional*, defaults to 0) -- Value that will be used by default in the
  295. `generate` method of the model for `no_repeat_ngram_size`. If set to int > 0, all ngrams of that size can
  296. only occur once.
  297. encoder_no_repeat_ngram_size (`int`, *optional*, defaults to 0) -- Value that will be used by
  298. default in the `generate` method of the model for `encoder_no_repeat_ngram_size`. If set to int > 0, all
  299. ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
  300. bad_words_ids (`List[int]`, *optional*):
  301. List of token ids that are not allowed to be generated that will be used by default in the `generate`
  302. method of the model. In order to get the tokens of the words that should not appear in the generated text,
  303. use `tokenizer.encode(bad_word, add_prefix_space=True)`.
  304. num_return_sequences (`int`, *optional*, defaults to 1):
  305. Number of independently computed returned sequences for each element in the batch that will be used by
  306. default in the `generate` method of the model.
  307. output_scores (`bool`, *optional*, defaults to `False`):
  308. Whether the model should return the logits when used for generation.
  309. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  310. Whether the model should return a [`~paddlenlp.transformers.model_outputs.ModelOutput`] instead of a `paddlenlp.Tensor`.
  311. forced_bos_token_id (`int`, *optional*):
  312. The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for
  313. multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be the target
  314. language token.
  315. forced_eos_token_id (`int`, *optional*):
  316. The id of the token to force as the last generated token when `max_length` is reached.
  317. remove_invalid_values (`bool`, *optional*):
  318. Whether to remove possible _nan_ and _inf_ outputs of the model to prevent the generation method to crash.
  319. Note that using `remove_invalid_values` can slow down generation.
  320. > Parameters for fine-tuning tasks
  321. architectures (`List[str]`, *optional*):
  322. Model architectures that can be used with the model pretrained weights.
  323. finetuning_task (`str`, *optional*):
  324. Name of the task used to fine-tune the model. This can be used when converting from an original checkpoint.
  325. id2label (`Dict[int, str]`, *optional*):
  326. A map from index (for instance prediction index, or target index) to label.
  327. label2id (`Dict[str, int]`, *optional*): A map from label to index for the model.
  328. num_labels (`int`, *optional*):
  329. Number of labels to use in the last layer added to the model, typically for a classification task.
  330. task_specific_params (`Dict[str, Any]`, *optional*):
  331. Additional keyword arguments to store for the current task.
  332. problem_type (`str`, *optional*):
  333. Problem type for `XxxForSequenceClassification` models. Can be one of `"regression"`,
  334. `"single_label_classification"` or `"multi_label_classification"`.
  335. > Parameters linked to the tokenizer
  336. tokenizer_class (`str`, *optional*):
  337. The name of the associated tokenizer class to use (if none is set, will use the tokenizer associated to the
  338. model by default).
  339. prefix (`str`, *optional*):
  340. A specific prompt that should be added at the beginning of each text before calling the model.
  341. bos_token_id (`int`, *optional*): The id of the _beginning-of-stream_ token.
  342. pad_token_id (`int`, *optional*): The id of the _padding_ token.
  343. eos_token_id (`int`, *optional*): The id of the _end-of-stream_ token.
  344. decoder_start_token_id (`int`, *optional*):
  345. If an encoder-decoder model starts decoding with a different token than _bos_, the id of that token.
  346. sep_token_id (`int`, *optional*): The id of the _separation_ token.
  347. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  348. Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
  349. model has a output word embedding layer.
  350. dtype (`str`, *optional*):
  351. The `dtype` of the weights. This attribute can be used to initialize the model to a non-default `dtype`
  352. (which is normally `float32`) and thus allow for optimal storage allocation. For example, if the saved
  353. model is `float16`, ideally we want to load it back using the minimal amount of memory needed to load
  354. `float16` weights. Since the config object is stored in plain text, this attribute contains just the
  355. floating type string without the `paddle.` prefix. For example, for `paddle.float16` ``dtype` is the
  356. `"float16"` string.
  357. This attribute is currently not being used during model loading time, but this may change in the future
  358. versions. But we can already start preparing for the future by saving the dtype with save_pretrained.
  359. """
  360. model_type: str = ""
  361. is_composition: bool = False
  362. pretrained_init_configuration = {}
  363. # global attribute mapping
  364. attribute_map: Dict[str, str] = {"num_classes": "num_labels"}
  365. _auto_class: Optional[str] = None
  366. # Fix me, it is global for all config
  367. _unsavable_keys = set()
  368. def __setattr__(self, key, value):
  369. if key in super().__getattribute__("attribute_map"):
  370. key = super().__getattribute__("attribute_map")[key]
  371. super().__setattr__(key, value)
  372. assert hasattr(self, key)
  373. def __getattribute__(self, key):
  374. if key != "attribute_map" and key in super().__getattribute__("attribute_map"):
  375. key = super().__getattribute__("attribute_map")[key]
  376. return super().__getattribute__(key)
  377. def __getitem__(self, key):
  378. return getattr(self, key, None)
  379. def __setitem__(self, key, value):
  380. if hasattr(self, key):
  381. setattr(self, key, value)
  382. def __init__(self, **kwargs):
  383. # Attributes with defaults
  384. # map the old attr to new atr, eg: num_classes -> num_labels
  385. kwargs = attribute_map(self, kwargs=kwargs)
  386. kwargs.pop("transformers_version", None)
  387. llm_meta = LlmMetaConfig._get_defaults()
  388. self._unsavable_keys.update(LlmMetaConfig._get_unsavable_keys())
  389. self._unsavable_keys.remove("tensor_parallel_degree")
  390. kwargs = set_expected_keys(self, llm_meta, kwargs)
  391. if self.sequence_parallel:
  392. assert (
  393. self.tensor_parallel_degree > 1
  394. ), f"senquence-parallel only works in tensor parallel, got tensor parallel degree={self.tensor_parallel_degree}"
  395. self.chunk_size_feed_forward = kwargs.pop("chunk_size_feed_forward", 0)
  396. self.return_dict = kwargs.pop("return_dict", False)
  397. self.output_hidden_states = kwargs.pop("output_hidden_states", False)
  398. self.output_attentions = kwargs.pop("output_attentions", False)
  399. self.use_cache = kwargs.pop("use_cache", False)
  400. # for transformers fuse
  401. self.fuse_attention_qkv = kwargs.pop("fuse_attention_qkv", False)
  402. self.fuse_attention_ffn = kwargs.pop("fuse_attention_ffn", False)
  403. self.pruned_heads = kwargs.pop("pruned_heads", {})
  404. self.tie_word_embeddings = kwargs.pop(
  405. "tie_word_embeddings", True
  406. ) # Whether input and output word embeddings should be tied for all MLM, LM and Seq2Seq models.
  407. # parameter for model dtype
  408. if "torch_dtype" in kwargs:
  409. self.dtype = kwargs.pop("torch_dtype")
  410. else:
  411. self.dtype = kwargs.pop("dtype", paddle.get_default_dtype())
  412. # Is decoder is used in encoder-decoder models to differentiate encoder from decoder
  413. self.is_encoder_decoder = kwargs.pop("is_encoder_decoder", False)
  414. self.is_decoder = kwargs.pop("is_decoder", False)
  415. self.cross_attention_hidden_size = kwargs.pop(
  416. "cross_attention_hidden_size", None
  417. )
  418. self.add_cross_attention = kwargs.pop("add_cross_attention", False)
  419. self.tie_encoder_decoder = kwargs.pop("tie_encoder_decoder", False)
  420. # Retrocompatibility: Parameters for sequence generation. While we will keep the ability to load these
  421. # parameters, saving them will be deprecated. In a distant future, we won't need to load them.
  422. for parameter_name, default_value in self._get_generation_defaults().items():
  423. setattr(self, parameter_name, kwargs.pop(parameter_name, default_value))
  424. # Fine-tuning task arguments
  425. self.architectures = kwargs.pop("architectures", None)
  426. self.finetuning_task = kwargs.pop("finetuning_task", None)
  427. self.id2label = kwargs.pop("id2label", None)
  428. self.label2id = kwargs.pop("label2id", None)
  429. if self.id2label is not None:
  430. num_labels = kwargs.pop("num_labels", None)
  431. if num_labels is not None and len(self.id2label) != num_labels:
  432. logging.warning(
  433. f"You passed along `num_labels={num_labels}` with an incompatible id to label map: "
  434. f"{self.id2label}. The number of labels will be overwritten to {self.num_labels}."
  435. )
  436. self.id2label = dict(
  437. (int(key), value) for key, value in self.id2label.items()
  438. )
  439. # Keys are always strings in JSON so convert ids to int here.
  440. else:
  441. self.num_labels = kwargs.pop("num_labels", 2)
  442. self.num_choices = kwargs.pop("num_choices", None)
  443. self.classifier_dropout = kwargs.pop("classifier_dropout", None)
  444. # Tokenizer arguments TODO: eventually tokenizer and models should share the same config
  445. self.tokenizer_class = kwargs.pop("tokenizer_class", None)
  446. self.prefix = kwargs.pop("prefix", None)
  447. self.bos_token_id = kwargs.pop("bos_token_id", None)
  448. self.pad_token_id = kwargs.pop("pad_token_id", None)
  449. self.eos_token_id = kwargs.pop("eos_token_id", None)
  450. self.sep_token_id = kwargs.pop("sep_token_id", None)
  451. self.decoder_start_token_id = kwargs.pop("decoder_start_token_id", None)
  452. # task specific arguments
  453. self.task_specific_params = kwargs.pop("task_specific_params", None)
  454. # regression / multi-label classification
  455. self.problem_type = kwargs.pop("problem_type", None)
  456. allowed_problem_types = (
  457. "regression",
  458. "single_label_classification",
  459. "multi_label_classification",
  460. )
  461. if (
  462. self.problem_type is not None
  463. and self.problem_type not in allowed_problem_types
  464. ):
  465. raise ValueError(
  466. f"The config parameter `problem_type` was not understood: received {self.problem_type} "
  467. "but only 'regression', 'single_label_classification' and 'multi_label_classification' are valid."
  468. )
  469. # Name or path to the pretrained checkpoint
  470. self._name_or_path = str(kwargs.pop("name_or_path", ""))
  471. # Drop the transformers version info
  472. self.paddlenlp_version = kwargs.pop("paddlenlp_version", None)
  473. # Deal with gradient checkpointing
  474. if kwargs.get("gradient_checkpointing", False):
  475. warnings.warn(
  476. "Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 "
  477. "Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the "
  478. "`Trainer` API, pass `gradient_checkpointing=True` in your `TrainingArguments`."
  479. )
  480. # Additional attributes without default values
  481. for key, value in kwargs.items():
  482. try:
  483. setattr(self, key, value)
  484. except AttributeError as err:
  485. logging.error(f"Can't set {key} with value {value} for {self}")
  486. raise err
  487. @staticmethod
  488. def _get_generation_defaults() -> Dict[str, Any]:
  489. return {
  490. "max_length": 20,
  491. "min_length": 0,
  492. "do_sample": False,
  493. "early_stopping": False,
  494. "num_beams": 1,
  495. "num_beam_groups": 1,
  496. "diversity_penalty": 0.0,
  497. "temperature": 1.0,
  498. "top_k": 50,
  499. "top_p": 1.0,
  500. "typical_p": 1.0,
  501. "repetition_penalty": 1.0,
  502. "length_penalty": 1.0,
  503. "no_repeat_ngram_size": 0,
  504. "encoder_no_repeat_ngram_size": 0,
  505. "bad_words_ids": None,
  506. "num_return_sequences": 1,
  507. "output_scores": False,
  508. "return_dict_in_generate": False,
  509. "forced_bos_token_id": None,
  510. "forced_eos_token_id": None,
  511. "remove_invalid_values": False,
  512. "exponential_decay_length_penalty": None,
  513. "suppress_tokens": None,
  514. "begin_suppress_tokens": None,
  515. }
  516. def _has_non_default_generation_parameters(self) -> bool:
  517. """
  518. Whether or not this instance holds non-default generation parameters.
  519. """
  520. for parameter_name, default_value in self._get_generation_defaults().items():
  521. if (
  522. hasattr(self, parameter_name)
  523. and getattr(self, parameter_name) != default_value
  524. ):
  525. return True
  526. return False
  527. @property
  528. def name_or_path(self) -> str:
  529. return getattr(self, "_name_or_path", None)
  530. @name_or_path.setter
  531. def name_or_path(self, value):
  532. self._name_or_path = str(
  533. value
  534. ) # Make sure that name_or_path is a string (for JSON encoding)
  535. @property
  536. def use_return_dict(self) -> bool:
  537. """
  538. `bool`: Whether or not return [`~paddlenlp.transformers.model_outputs.ModelOutput`] instead of tuples.
  539. """
  540. return self.return_dict
  541. @property
  542. def num_labels(self) -> int:
  543. """
  544. `int`: The number of labels for classification models.
  545. """
  546. return len(self.id2label)
  547. @num_labels.setter
  548. def num_labels(self, num_labels: int):
  549. if (
  550. not hasattr(self, "id2label")
  551. or self.id2label is None
  552. or len(self.id2label) != num_labels
  553. ):
  554. self.id2label = {i: f"LABEL_{i}" for i in range(num_labels)}
  555. self.label2id = dict(zip(self.id2label.values(), self.id2label.keys()))
  556. @classmethod
  557. def from_pretrained(
  558. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  559. ) -> PretrainedConfig:
  560. r"""
  561. Instantiate a [`PretrainedConfig`] (or a derived class) from a pretrained model configuration.
  562. Args:
  563. pretrained_model_name_or_path (`str` or `os.PathLike`):
  564. This can be either:
  565. - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
  566. paddlenlp bos server. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
  567. namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
  568. - a path to a *directory* containing a configuration file saved using the
  569. [`~PretrainedConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
  570. - a path or url to a saved configuration JSON *file*, e.g., `./my_model_directory/configuration.json`.
  571. kwargs (`Dict[str, Any]`, *optional*):
  572. The values in kwargs of any keys which are configuration attributes will be used to override the loaded
  573. values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
  574. by the `return_unused_kwargs` keyword parameter.
  575. <Tip>
  576. Passing `use_auth_token=True` is required when you want to use a private model.
  577. </Tip>
  578. Returns:
  579. [`PretrainedConfig`]: The configuration object instantiated from this pretrained model.
  580. """
  581. config_dict, kwargs = cls.get_config_dict(
  582. pretrained_model_name_or_path, **kwargs
  583. )
  584. return cls.from_dict(config_dict, **kwargs)
  585. @classmethod
  586. def get_config_dict(
  587. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  588. ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
  589. """
  590. From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
  591. [`PretrainedConfig`] using `from_dict`.
  592. Parameters:
  593. pretrained_model_name_or_path (`str` or `os.PathLike`):
  594. The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
  595. Returns:
  596. `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the configuration object.
  597. """
  598. original_kwargs = copy.deepcopy(kwargs)
  599. cache_dir = kwargs.pop("cache_dir", None)
  600. subfolder = kwargs.get("subfolder", "")
  601. if subfolder is None:
  602. subfolder = ""
  603. kwargs["cache_dir"] = cache_dir
  604. kwargs["subfolder"] = subfolder
  605. # Get config dict associated with the base config file
  606. config_dict, kwargs = cls._get_config_dict(
  607. pretrained_model_name_or_path, **kwargs
  608. )
  609. if config_dict is None:
  610. return {}, kwargs
  611. # That config file may point us toward another config file to use.
  612. if "configuration_files" in config_dict:
  613. original_kwargs["cache_dir"] = os.path.join(
  614. cache_dir, pretrained_model_name_or_path, subfolder
  615. )
  616. configuration_file = get_configuration_file(
  617. config_dict["configuration_files"]
  618. )
  619. config_dict, kwargs = cls._get_config_dict(
  620. pretrained_model_name_or_path,
  621. _configuration_file=configuration_file,
  622. **original_kwargs,
  623. )
  624. return config_dict, kwargs
  625. @classmethod
  626. def _get_config_dict(
  627. cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
  628. ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
  629. cache_dir = kwargs.pop("cache_dir", None)
  630. from_hf_hub = kwargs.pop("from_hf_hub", False)
  631. from_aistudio = kwargs.pop("from_aistudio", False)
  632. subfolder = kwargs.pop("subfolder", "")
  633. if subfolder is None:
  634. subfolder = ""
  635. force_download = kwargs.pop("force_download", False)
  636. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  637. resolved_config_file = None
  638. # 0. init from pretrained_init_configuration
  639. if pretrained_model_name_or_path in cls.pretrained_init_configuration:
  640. # which can be: dict or url
  641. pretrained_model_name_or_path_ = cls.pretrained_init_configuration[
  642. pretrained_model_name_or_path
  643. ]
  644. if isinstance(pretrained_model_name_or_path_, dict):
  645. return pretrained_model_name_or_path_, kwargs
  646. configuration_file = kwargs.pop("_configuration_file", CONFIG_NAME)
  647. filenames = (
  648. [configuration_file, LEGACY_CONFIG_NAME]
  649. if configuration_file == CONFIG_NAME
  650. else [configuration_file, CONFIG_NAME, LEGACY_CONFIG_NAME]
  651. )
  652. resolved_config_file = resolve_file_path(
  653. pretrained_model_name_or_path,
  654. filenames,
  655. subfolder,
  656. cache_dir=cache_dir,
  657. force_download=force_download,
  658. from_aistudio=from_aistudio,
  659. from_hf_hub=from_hf_hub,
  660. )
  661. if resolved_config_file is None:
  662. return None, kwargs
  663. try:
  664. logging.info(f"Loading configuration file {resolved_config_file}")
  665. # Load config dict
  666. config_dict = cls._dict_from_json_file(resolved_config_file)
  667. except (json.JSONDecodeError, UnicodeDecodeError):
  668. raise EnvironmentError(
  669. f"Config file<'{resolved_config_file}'> is not a valid JSON file."
  670. )
  671. return config_dict, kwargs
  672. @classmethod
  673. def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PretrainedConfig":
  674. """
  675. Instantiates a [`PretrainedConfig`] from a Python dictionary of parameters.
  676. Args:
  677. config_dict (`Dict[str, Any]`):
  678. Dictionary that will be used to instantiate the configuration object. Such a dictionary can be
  679. retrieved from a pretrained checkpoint by leveraging the [`~PretrainedConfig.get_config_dict`] method.
  680. kwargs (`Dict[str, Any]`):
  681. Additional parameters from which to initialize the configuration object.
  682. Returns:
  683. [`PretrainedConfig`]: The configuration object instantiated from those parameters.
  684. """
  685. return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
  686. # do standard config map: there are some old-school pretrained-config not refactored.
  687. config_dict = convert_to_legacy_config(cls.attribute_map, config_dict)
  688. config_dict = flatten_model_config(config_dict)
  689. if (
  690. "model_type" in config_dict
  691. and hasattr(cls, "model_type")
  692. and config_dict["model_type"] != cls.model_type
  693. ):
  694. logging.warning(
  695. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  696. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  697. )
  698. config = cls(**config_dict)
  699. if hasattr(config, "pruned_heads"):
  700. config.pruned_heads = dict(
  701. (int(key), value) for key, value in config.pruned_heads.items()
  702. )
  703. # Update config with kwargs if needed
  704. if "num_labels" in kwargs and "id2label" in kwargs:
  705. num_labels = kwargs["num_labels"]
  706. id2label = kwargs["id2label"] if kwargs["id2label"] is not None else []
  707. if len(id2label) != num_labels:
  708. raise ValueError(
  709. f"You passed along `num_labels={num_labels }` with an incompatible id to label map: "
  710. f"{kwargs['id2label']}. Since those arguments are inconsistent with each other, you should remove "
  711. "one of them."
  712. )
  713. to_remove = []
  714. for key, value in kwargs.items():
  715. if hasattr(config, key):
  716. setattr(config, key, value)
  717. if key != "dtype":
  718. to_remove.append(key)
  719. for key in to_remove:
  720. kwargs.pop(key, None)
  721. if return_unused_kwargs:
  722. return config, kwargs
  723. else:
  724. return config
  725. @classmethod
  726. def from_json_file(cls, json_file: Union[str, os.PathLike]) -> "PretrainedConfig":
  727. """
  728. Instantiates a [`PretrainedConfig`] from the path to a JSON file of parameters.
  729. Args:
  730. json_file (`str` or `os.PathLike`):
  731. Path to the JSON file containing the parameters.
  732. Returns:
  733. [`PretrainedConfig`]: The configuration object instantiated from that JSON file.
  734. """
  735. config_dict = cls._dict_from_json_file(json_file)
  736. return cls(**config_dict)
  737. @classmethod
  738. def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
  739. with open(json_file, "r", encoding="utf-8") as reader:
  740. text = reader.read()
  741. return json.loads(text)
  742. def __eq__(self, other):
  743. return self.__dict__ == other.__dict__
  744. def to_diff_dict(self, saving_file=False) -> Dict[str, Any]:
  745. """
  746. Removes all attributes from config which correspond to the default config attributes for better readability and
  747. serializes to a Python dictionary.
  748. Returns:
  749. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
  750. """
  751. config_dict = self.to_dict(saving_file=saving_file)
  752. # get the default config dict
  753. default_config_dict = PretrainedConfig().to_dict(saving_file=saving_file)
  754. # get class specific config dict
  755. class_config_dict = (
  756. self.__class__().to_dict(saving_file=saving_file)
  757. if not self.is_composition
  758. else {}
  759. )
  760. serializable_config_dict = {}
  761. # only serialize values that differ from the default config
  762. for key, value in config_dict.items():
  763. if (
  764. key not in default_config_dict
  765. or key == "paddlenlp_version"
  766. or value != default_config_dict[key]
  767. or (key in class_config_dict and value != class_config_dict[key])
  768. ):
  769. serializable_config_dict[key] = value
  770. return serializable_config_dict
  771. def register_unsavable_keys(self, keys):
  772. # Save: not save it in any case
  773. # Print: show it if non default value
  774. if isinstance(keys, list) or isinstance(keys, tuple):
  775. for key in keys:
  776. self._unsavable_keys.add(key)
  777. else:
  778. self._unsavable_keys.add(keys)
  779. def to_dict(self, saving_file=False) -> Dict[str, Any]:
  780. """
  781. Serializes this instance to a Python dictionary.
  782. Returns:
  783. `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
  784. """
  785. output = copy.deepcopy(self.__dict__)
  786. if hasattr(self.__class__, "model_type"):
  787. output["model_type"] = self.__class__.model_type
  788. if "_auto_class" in output:
  789. del output["_auto_class"]
  790. if "moe_group" in output:
  791. del output["moe_group"]
  792. for key, value in output.items():
  793. # Deal with nested configs like CLIP
  794. if isinstance(value, PretrainedConfig):
  795. value = value.to_dict()
  796. del value["paddlenlp_version"]
  797. output[key] = value
  798. # Fix for rewrote from_pretrained method, hasattr
  799. if saving_file and hasattr(self, "_unsavable_keys"):
  800. for key in list(output.keys()):
  801. if key in self._unsavable_keys:
  802. output.pop(key)
  803. return output
  804. def update(self, config_dict: Dict[str, Any]):
  805. """
  806. Updates attributes of this class with attributes from `config_dict`.
  807. Args:
  808. config_dict (`Dict[str, Any]`): Dictionary of attributes that should be updated for this class.
  809. """
  810. for key, value in config_dict.items():
  811. setattr(self, key, value)
  812. def update_from_string(self, update_str: str):
  813. """
  814. Updates attributes of this class with attributes from `update_str`.
  815. The expected format is ints, floats and strings as is, and for booleans use `true` or `false`. For example:
  816. "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
  817. The keys to change have to already exist in the config object.
  818. Args:
  819. update_str (`str`): String with attributes that should be updated for this class.
  820. """
  821. d = dict(x.split("=") for x in update_str.split(","))
  822. for k, v in d.items():
  823. if not hasattr(self, k):
  824. raise ValueError(f"key {k} isn't in the original config dict")
  825. old_v = getattr(self, k)
  826. if isinstance(old_v, bool):
  827. if v.lower() in ["true", "1", "y", "yes"]:
  828. v = True
  829. elif v.lower() in ["false", "0", "n", "no"]:
  830. v = False
  831. else:
  832. raise ValueError(f"can't derive true or false from {v} (key {k})")
  833. elif isinstance(old_v, int):
  834. v = int(v)
  835. elif isinstance(old_v, float):
  836. v = float(v)
  837. elif not isinstance(old_v, str):
  838. raise ValueError(
  839. f"You can only update int, float, bool or string values in the config, got {v} for key {k}"
  840. )
  841. setattr(self, k, v)
  842. def get(self, key, default=None):
  843. """
  844. Return the value for key if config class has the attribute , else default.
  845. If default is not given, it defaults to None, so that this method never raises a AttributeError.
  846. """
  847. try:
  848. value = self.__getattribute__(key)
  849. except AttributeError:
  850. return default
  851. else:
  852. return value
  853. def get_configuration_file(configuration_files: List[str]) -> str:
  854. """
  855. Get the configuration file to use for this version of paddlenlp.
  856. # TODO: there is not supported actual application models, but useful.
  857. this method has not been tested, so be caution to use this feature.
  858. Args:
  859. configuration_files (`List[str]`): The list of available configuration files.
  860. Returns:
  861. `str`: The configuration file to use.
  862. """
  863. # NOTE adapt for PaddleX
  864. configuration_file = CONFIG_NAME
  865. return configuration_file