codingutf8 2018 the google ai language team s and the huggingface inc team c 2018 nvidia corporation licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license configuration base class and utilities import copy import json import os import re import warnings from typing import any dict list optional tuple union from packaging import version from import version from dynamicmoduleutils import customobjectsave from utils import configname pushtohubmixin addmodelinfotoautomap cachedfile copyfunc downloadurl extractcommithash isremoteurl istorchavailable logging logger logging getloggername reconfigurationfile re compilerconfig json class pretrainedconfigpushtohubmixin noformat r base class for all configuration classes handles a few parameters common to all models configurations as well as methods for loadingdownloadingsaving configurations tip a configuration file can be loaded and saved to disk loading the configuration file and using this file to initialize a model does not load the model weights it only affects the model s configuration tip class attributes overridden by derived classes modeltype str an identifier for the model type serialized into the json file and used to recreate the correct object in transformers autoconfig iscomposition bool whether the config class is composed of multiple subconfigs in this case the config has to be initialized from two or more configs of type transformers pretrainedconfig like transformers encoderdecoderconfig or ragconfig keystoignoreatinference liststr a list of keys to ignore by default when looking at dictionary outputs of the model during inference attributemap dictstr str a dict that maps model specific attribute names to the standardized naming of attributes common attributes present in all subclasses vocabsize int the number of tokens in the vocabulary which is also the first dimension of the embeddings matrix this attribute may be missing for models that don t have a text modality like vit hiddensize int the hidden size of the model numattentionheads int the number of attention heads used in the multihead attention layers of the model numhiddenlayers int the number of blocks in the model arg nameorpath str optional defaults to store the string that was passed to pretrainedmodel frompretrained or tfpretrainedmodel frompretrained as pretrainedmodelnameorpath if the configuration was created with such a method outputhiddenstates bool optional defaults to false whether or not the model should return all hiddenstates outputattentions bool optional defaults to false whether or not the model should returns all attentions returndict bool optional defaults to true whether or not the model should return a transformers utils modeloutput instead of a plain tuple isencoderdecoder bool optional defaults to false whether the model is used as an encoderdecoder or not isdecoder bool optional defaults to false whether the model is used as decoder or not in which case it s used as an encoder crossattentionhiddensize bool optional the hidden size of the crossattention layer in case the model is used as a decoder in an encoderdecoder setting and the crossattention hidden dimension differs from self config hiddensize addcrossattention bool optional defaults to false whether crossattention layers should be added to the model note this option is only relevant for models that can be used as decoder models within the encoderdecodermodel class which consists of all models in automodelsforcausallm tieencoderdecoder bool optional defaults to false whether all encoder weights should be tied to their equivalent decoder weights this requires the encoder and decoder model to have the exact same parameter names pruneheads dictint listint optional defaults to pruned heads of the model the keys are the selected layer indices and the associated values the list of heads to prune in said layer 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 chunksizefeedforward int optional defaults to 0 the chunk size of all feed forward layers in the residual attention blocks a chunk size of 0 means that the feed forward layer is not chunked a chunk size of n means that the feed forward layer processes n sequencelength embeddings at a time for more information on feed forward chunking see how does feed forward chunking work glossary htmlfeedforwardchunking parameters for sequence generation maxlength int optional defaults to 20 maximum length that will be used by default in the generate method of the model minlength int optional defaults to 0 minimum length that will be used by default in the generate method of the model dosample bool optional defaults to false flag that will be used by default in the generate method of the model whether or not to use sampling use greedy decoding otherwise earlystopping bool optional defaults to false flag that will be used by default in the generate method of the model whether to stop the beam search when at least numbeams sentences are finished per batch or not numbeams int optional defaults to 1 number of beams for beam search that will be used by default in the generate method of the model 1 means no beam search numbeamgroups int optional defaults to 1 number of groups to divide numbeams into in order to ensure diversity among different groups of beams that will be used by default in the generate method of the model 1 means no group beam search diversitypenalty float optional defaults to 0 0 value to control diversity for group beam search that will be used by default in the generate method of the model 0 means no diversity penalty the higher the penalty the more diverse are the outputs temperature float optional defaults to 1 0 the value used to module the next token probabilities that will be used by default in the generate method of the model must be strictly positive topk int optional defaults to 50 number of highest probability vocabulary tokens to keep for topkfiltering that will be used by default in the generate method of the model topp float optional defaults to 1 value that will be used by default in the generate method of the model for topp if set to float 1 only the most probable tokens with probabilities that add up to topp or higher are kept for generation typicalp float optional defaults to 1 local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next given the partial text already generated if set to float 1 the smallest set of the most locally typical tokens with probabilities that add up to typicalp or higher are kept for generation see this paperhttps arxiv orgpdf2202 00666 pdf for more details repetitionpenalty float optional defaults to 1 parameter for repetition penalty that will be used by default in the generate method of the model 1 0 means no penalty lengthpenalty float optional defaults to 1 exponential penalty to the length that is used with beambased generation it is applied as an exponent to the sequence length which in turn is used to divide the score of the sequence since the score is the log likelihood of the sequence i e negative lengthpenalty 0 0 promotes longer sequences while lengthpenalty 0 0 encourages shorter sequences norepeatngramsize int optional defaults to 0 value that will be used by default in the generate method of the model for norepeatngramsize if set to int 0 all ngrams of that size can only occur once encodernorepeatngramsize int optional defaults to 0 value that will be used by default in the generate method of the model for encodernorepeatngramsize if set to int 0 all ngrams of that size that occur in the encoderinputids cannot occur in the decoderinputids badwordsids listint optional list of token ids that are not allowed to be generated that will be used by default in the generate method of the model in order to get the tokens of the words that should not appear in the generated text use tokenizer encodebadword addprefixspacetrue numreturnsequences int optional defaults to 1 number of independently computed returned sequences for each element in the batch that will be used by default in the generate method of the model outputscores bool optional defaults to false whether the model should return the logits when used for generation returndictingenerate bool optional defaults to false whether the model should return a transformers utils modeloutput instead of a torch longtensor forcedbostokenid int optional the id of the token to force as the first generated token after the decoderstarttokenid useful for multilingual models like mbart modeldocmbart where the first generated token needs to be the target language token forcedeostokenid int optional the id of the token to force as the last generated token when maxlength is reached removeinvalidvalues bool optional whether to remove possible nan and inf outputs of the model to prevent the generation method to crash note that using removeinvalidvalues can slow down generation parameters for finetuning tasks architectures liststr optional model architectures that can be used with the model pretrained weights finetuningtask str optional name of the task used to finetune the model this can be used when converting from an original tensorflow or pytorch checkpoint id2label dictint str optional a map from index for instance prediction index or target index to label label2id dictstr int optional a map from label to index for the model numlabels int optional number of labels to use in the last layer added to the model typically for a classification task taskspecificparams dictstr any optional additional keyword arguments to store for the current task problemtype str optional problem type for xxxforsequenceclassification models can be one of regression singlelabelclassification or multilabelclassification parameters linked to the tokenizer tokenizerclass str optional the name of the associated tokenizer class to use if none is set will use the tokenizer associated to the model by default prefix str optional a specific prompt that should be added at the beginning of each text before calling the model bostokenid int optional the id of the beginningofstream token padtokenid int optional the id of the padding token eostokenid int optional the id of the endofstream token decoderstarttokenid int optional if an encoderdecoder model starts decoding with a different token than bos the id of that token septokenid int optional the id of the separation token pytorch specific parameters torchscript bool optional defaults to false whether or not the model should be used with torchscript tiewordembeddings bool optional defaults to true whether the model s input and output word embeddings should be tied note that this is only relevant if the model has a output word embedding layer torchdtype str optional the dtype of the weights this attribute can be used to initialize the model to a nondefault dtype which is normally float32 and thus allow for optimal storage allocation for example if the saved model is float16 ideally we want to load it back using the minimal amount of memory needed to load float16 weights since the config object is stored in plain text this attribute contains just the floating type string without the torch prefix for example for torch float16 torchdtype is the float16 string this attribute is currently not being used during model loading time but this may change in the future versions but we can already start preparing for the future by saving the dtype with savepretrained tensorflow specific parameters usebfloat16 bool optional defaults to false whether or not the model should use bfloat16 scalars only used by some tensorflow models tflegacyloss bool optional defaults to false whether the model should use legacy tensorflow losses legacy losses have variable output shapes and may not be xlacompatible this option is here for backward compatibility and will be removed in transformers v5 attributes with defaults is decoder is used in encoderdecoder models to differentiate encoder from decoder parameters for sequence generation finetuning task arguments keys are always strings in json so convert ids to int here we will start using self torchdtype in v5 but to be consistent with frompretrained s torchdtype arg convert it to an actual torch dtype object tokenizer arguments todo eventually tokenizer and models should share the same config task specific arguments regression multilabel classification tpu arguments name or path to the pretrained checkpoint config hash drop the transformers version info deal with gradient checkpointing additional attributes without default values bool whether or not return utils modeloutput instead of tuples if torchscript is set force returndictfalse to avoid jit errors int the number of labels for classification models save a configuration object to the directory savedirectory so that it can be reloaded using the pretrainedconfig frompretrained class method args savedirectory str or os pathlike directory where the configuration json file will be saved will be created if it does not exist pushtohub bool optional defaults to false whether or not to push your model to the hugging face model hub after saving it you can specify the repository you want to push to with repoid will default to the name of savedirectory in your namespace kwargs dictstr any optional additional key word arguments passed along to the utils pushtohubmixin pushtohub method if we have a custom config we copy the file defining it in the folder and set the attributes so it can be loaded from the hub if we save using the predefined names we can load using frompretrained temporary method to deal with token and useauthtoken this method is to avoid apply the same changes in all model config classes that overwrite frompretrained need to clean up useauthtoken in a follow pr some model config classes like clip define their own frompretrained without the new argument token yet we can t instantiate directly the base class pretrainedconfig so let s show the examples on a derived class bertconfig from a pretrainedmodelnameorpath resolve to a dictionary of parameters to be used for instantiating a pretrainedconfig using fromdict parameters pretrainedmodelnameorpath str or os pathlike the identifier of the pretrained checkpoint from which we want the dictionary of parameters returns tupledict dict the dictionaryies that will be used to instantiate the configuration object get config dict associated with the base config file that config file may point us toward another config file to use special case when pretrainedmodelnameorpath is a local file load from local folder or from cache or download from model hub and cache raise any environment error raise by cachedfile it will have a helpful error message adapted to the original exception for any other exception we throw a generic error load config dict instantiates a pretrainedconfig from a python dictionary of parameters args configdict dictstr any dictionary that will be used to instantiate the configuration object such a dictionary can be retrieved from a pretrained checkpoint by leveraging the pretrainedconfig getconfigdict method kwargs dictstr any additional parameters from which to initialize the configuration object returns pretrainedconfig the configuration object instantiated from those parameters those arguments may be passed along for our internal telemetry we remove them so they don t appear in returnunusedkwargs the commit hash might have been updated in the configdict we don t want the kwargs to erase that update update config with kwargs if needed to ize passing a custom subconfig as kwarg in models that have nested configs instantiates a pretrainedconfig from the path to a json file of parameters args jsonfile str or os pathlike path to the json file containing the parameters returns pretrainedconfig the configuration object instantiated from that json file removes all attributes from config which correspond to the default config attributes for better readability and serializes to a python dictionary returns dictstr any dictionary of all the attributes that make up this configuration instance get the default config dict get class specific config dict only serialize values that differ from the default config for nested configs we need to clean the diff recursively needs to be set even if it s not in the diff pop the prequantizationdtype as torch dtypes are not serializable serializes this instance to a python dictionary returns dictstr any dictionary of all the attributes that make up this configuration instance transformers version when serializing the model deal with nested configs like clip pop the prequantizationdtype as torch dtypes are not serializable serializes this instance to a json string args usediff bool optional defaults to true if set to true only the difference between the config instance and the default pretrainedconfig is serialized to json string returns str string containing all the attributes that make up this configuration instance in json format save this instance to a json file args jsonfilepath str or os pathlike path to the json file in which this configuration instance s parameters will be saved usediff bool optional defaults to true if set to true only the difference between the config instance and the default pretrainedconfig is serialized to json file updates attributes of this class with attributes from configdict args configdict dictstr any dictionary of attributes that should be updated for this class updates attributes of this class with attributes from updatestr the expected format is ints floats and strings as is and for booleans use true or false for example nembd10 residpdrop0 2 scaleattnweightsfalse summarytypeclsindex the keys to change have to already exist in the config object args updatestr str string with attributes that should be updated for this class checks whether the passed dictionary and its nested dicts have a torchdtype key and if it s not none converts torch dtype to a string of just the type for example torch float32 get converted into float32 string which can then be stored in the json format register this class with a given auto class this should only be used for custom configurations as the ones in the library are already mapped with autoconfig tip warningtrue this api is experimental and may have some slight breaking changes in the next releases tip args autoclass str or type optional defaults to autoconfig the auto class to register this new configuration with get the configuration file to use for this version of transformers args configurationfiles liststr the list of available configuration files returns str the configuration file to use defaults to fullconfigurationfile and then try to look at some newer versions no point going further since the versions are sorted helper function to recursively take the diff between two nested dictionaries the resulting diff only contains the values from dicta that are different from values in dictb coding utf 8 2018 the google ai language team s and the huggingface inc team c 2018 nvidia corporation licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license configuration base class and utilities no format base class for all configuration classes handles a few parameters common to all models configurations as well as methods for loading downloading saving configurations tip a configuration file can be loaded and saved to disk loading the configuration file and using this file to initialize a model does not load the model weights it only affects the model s configuration tip class attributes overridden by derived classes model_type str an identifier for the model type serialized into the json file and used to recreate the correct object in transformers autoconfig is_composition bool whether the config class is composed of multiple sub configs in this case the config has to be initialized from two or more configs of type transformers pretrainedconfig like transformers encoderdecoderconfig or ragconfig keys_to_ignore_at_inference list str a list of keys to ignore by default when looking at dictionary outputs of the model during inference attribute_map dict str str a dict that maps model specific attribute names to the standardized naming of attributes common attributes present in all subclasses vocab_size int the number of tokens in the vocabulary which is also the first dimension of the embeddings matrix this attribute may be missing for models that don t have a text modality like vit hidden_size int the hidden size of the model num_attention_heads int the number of attention heads used in the multi head attention layers of the model num_hidden_layers int the number of blocks in the model arg name_or_path str optional defaults to store the string that was passed to pretrainedmodel from_pretrained or tfpretrainedmodel from_pretrained as pretrained_model_name_or_path if the configuration was created with such a method output_hidden_states bool optional defaults to false whether or not the model should return all hidden states output_attentions bool optional defaults to false whether or not the model should returns all attentions return_dict bool optional defaults to true whether or not the model should return a transformers utils modeloutput instead of a plain tuple is_encoder_decoder bool optional defaults to false whether the model is used as an encoder decoder or not is_decoder bool optional defaults to false whether the model is used as decoder or not in which case it s used as an encoder cross_attention_hidden_size bool optional the hidden size of the cross attention layer in case the model is used as a decoder in an encoder decoder setting and the cross attention hidden dimension differs from self config hidden_size add_cross_attention bool optional defaults to false whether cross attention layers should be added to the model note this option is only relevant for models that can be used as decoder models within the encoderdecodermodel class which consists of all models in auto_models_for_causal_lm tie_encoder_decoder bool optional defaults to false whether all encoder weights should be tied to their equivalent decoder weights this requires the encoder and decoder model to have the exact same parameter names prune_heads dict int list int optional defaults to pruned heads of the model the keys are the selected layer indices and the associated values the list of heads to prune in said layer 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 chunk_size_feed_forward int optional defaults to 0 the chunk size of all feed forward layers in the residual attention blocks a chunk size of 0 means that the feed forward layer is not chunked a chunk size of n means that the feed forward layer processes n sequence_length embeddings at a time for more information on feed forward chunking see how does feed forward chunking work glossary html feed forward chunking parameters for sequence generation max_length int optional defaults to 20 maximum length that will be used by default in the generate method of the model min_length int optional defaults to 0 minimum length that will be used by default in the generate method of the model do_sample bool optional defaults to false flag that will be used by default in the generate method of the model whether or not to use sampling use greedy decoding otherwise early_stopping bool optional defaults to false flag that will be used by default in the generate method of the model whether to stop the beam search when at least num_beams sentences are finished per batch or not num_beams int optional defaults to 1 number of beams for beam search that will be used by default in the generate method of the model 1 means no beam search num_beam_groups int optional defaults to 1 number of groups to divide num_beams into in order to ensure diversity among different groups of beams that will be used by default in the generate method of the model 1 means no group beam search diversity_penalty float optional defaults to 0 0 value to control diversity for group beam search that will be used by default in the generate method of the model 0 means no diversity penalty the higher the penalty the more diverse are the outputs temperature float optional defaults to 1 0 the value used to module the next token probabilities that will be used by default in the generate method of the model must be strictly positive top_k int optional defaults to 50 number of highest probability vocabulary tokens to keep for top k filtering that will be used by default in the generate method of the model top_p float optional defaults to 1 value that will be used by default in the generate method of the model for top_p if set to float 1 only the most probable tokens with probabilities that add up to top_p or higher are kept for generation typical_p float optional defaults to 1 local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next given the partial text already generated if set to float 1 the smallest set of the most locally typical tokens with probabilities that add up to typical_p or higher are kept for generation see this paper https arxiv org pdf 2202 00666 pdf for more details repetition_penalty float optional defaults to 1 parameter for repetition penalty that will be used by default in the generate method of the model 1 0 means no penalty length_penalty float optional defaults to 1 exponential penalty to the length that is used with beam based generation it is applied as an exponent to the sequence length which in turn is used to divide the score of the sequence since the score is the log likelihood of the sequence i e negative length_penalty 0 0 promotes longer sequences while length_penalty 0 0 encourages shorter sequences no_repeat_ngram_size int optional defaults to 0 value that will be used by default in the generate method of the model for no_repeat_ngram_size if set to int 0 all ngrams of that size can only occur once encoder_no_repeat_ngram_size int optional defaults to 0 value that will be used by default in the generate method of the model for encoder_no_repeat_ngram_size if set to int 0 all ngrams of that size that occur in the encoder_input_ids cannot occur in the decoder_input_ids bad_words_ids list int optional list of token ids that are not allowed to be generated that will be used by default in the generate method of the model in order to get the tokens of the words that should not appear in the generated text use tokenizer encode bad_word add_prefix_space true num_return_sequences int optional defaults to 1 number of independently computed returned sequences for each element in the batch that will be used by default in the generate method of the model output_scores bool optional defaults to false whether the model should return the logits when used for generation return_dict_in_generate bool optional defaults to false whether the model should return a transformers utils modeloutput instead of a torch longtensor forced_bos_token_id int optional the id of the token to force as the first generated token after the decoder_start_token_id useful for multilingual models like mbart model_doc mbart where the first generated token needs to be the target language token forced_eos_token_id int optional the id of the token to force as the last generated token when max_length is reached remove_invalid_values bool optional whether to remove possible _nan_ and _inf_ outputs of the model to prevent the generation method to crash note that using remove_invalid_values can slow down generation parameters for fine tuning tasks architectures list str optional model architectures that can be used with the model pretrained weights finetuning_task str optional name of the task used to fine tune the model this can be used when converting from an original tensorflow or pytorch checkpoint id2label dict int str optional a map from index for instance prediction index or target index to label label2id dict str int optional a map from label to index for the model num_labels int optional number of labels to use in the last layer added to the model typically for a classification task task_specific_params dict str any optional additional keyword arguments to store for the current task problem_type str optional problem type for xxxforsequenceclassification models can be one of regression single_label_classification or multi_label_classification parameters linked to the tokenizer tokenizer_class str optional the name of the associated tokenizer class to use if none is set will use the tokenizer associated to the model by default prefix str optional a specific prompt that should be added at the beginning of each text before calling the model bos_token_id int optional the id of the _beginning of stream_ token pad_token_id int optional the id of the _padding_ token eos_token_id int optional the id of the _end of stream_ token decoder_start_token_id int optional if an encoder decoder model starts decoding with a different token than _bos_ the id of that token sep_token_id int optional the id of the _separation_ token pytorch specific parameters torchscript bool optional defaults to false whether or not the model should be used with torchscript tie_word_embeddings bool optional defaults to true whether the model s input and output word embeddings should be tied note that this is only relevant if the model has a output word embedding layer torch_dtype str optional the dtype of the weights this attribute can be used to initialize the model to a non default dtype which is normally float32 and thus allow for optimal storage allocation for example if the saved model is float16 ideally we want to load it back using the minimal amount of memory needed to load float16 weights since the config object is stored in plain text this attribute contains just the floating type string without the torch prefix for example for torch float16 torch_dtype is the float16 string this attribute is currently not being used during model loading time but this may change in the future versions but we can already start preparing for the future by saving the dtype with save_pretrained tensorflow specific parameters use_bfloat16 bool optional defaults to false whether or not the model should use bfloat16 scalars only used by some tensorflow models tf_legacy_loss bool optional defaults to false whether the model should use legacy tensorflow losses legacy losses have variable output shapes and may not be xla compatible this option is here for backward compatibility and will be removed in transformers v5 attributes with defaults only used by pytorch models only used by pytorch models only used by tensorflow models whether input and output word embeddings should be tied for all mlm lm and seq2seq models is decoder is used in encoder decoder models to differentiate encoder from decoder parameters for sequence generation fine tuning task arguments keys are always strings in json so convert ids to int here we will start using self torch_dtype in v5 but to be consistent with from_pretrained s torch_dtype arg convert it to an actual torch dtype object tokenizer arguments todo eventually tokenizer and models should share the same config task specific arguments regression multi label classification tpu arguments name or path to the pretrained checkpoint config hash drop the transformers version info deal with gradient checkpointing additional attributes without default values make sure that name_or_path is a string for json encoding bool whether or not return utils modeloutput instead of tuples if torchscript is set force return_dict false to avoid jit errors int the number of labels for classification models save a configuration object to the directory save_directory so that it can be re loaded using the pretrainedconfig from_pretrained class method args save_directory str or os pathlike directory where the configuration json file will be saved will be created if it does not exist push_to_hub bool optional defaults to false whether or not to push your model to the hugging face model hub after saving it you can specify the repository you want to push to with repo_id will default to the name of save_directory in your namespace kwargs dict str any optional additional key word arguments passed along to the utils pushtohubmixin push_to_hub method if we have a custom config we copy the file defining it in the folder and set the attributes so it can be loaded from the hub if we save using the predefined names we can load using from_pretrained temporary method to deal with token and use_auth_token this method is to avoid apply the same changes in all model config classes that overwrite from_pretrained need to clean up use_auth_token in a follow pr some model config classes like clip define their own from_pretrained without the new argument token yet instantiate a pretrainedconfig or a derived class from a pretrained model configuration args pretrained_model_name_or_path str or os pathlike this can be either a string the model id of a pretrained model configuration hosted inside a model repo on huggingface co valid model ids can be located at the root level like bert base uncased or namespaced under a user or organization name like dbmdz bert base german cased a path to a directory containing a configuration file saved using the pretrainedconfig save_pretrained method e g my_model_directory a path or url to a saved configuration json file e g my_model_directory configuration json cache_dir str or os pathlike optional path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used force_download bool optional defaults to false whether or not to force to re download the configuration files and override the cached versions if they exist resume_download bool optional defaults to false whether or not to delete incompletely received file attempts to resume the download if such a file exists proxies dict str str optional a dictionary of proxy servers to use by protocol or endpoint e g http foo bar 3128 http hostname foo bar 4012 the proxies are used on each request token str or bool optional the token to use as http bearer ization for remote files if true or not specified will use the token generated when running huggingface cli login stored in huggingface revision str optional defaults to main the specific model version to use it can be a branch name a tag name or a commit id since we use a git based system for storing models and other artifacts on huggingface co so revision can be any identifier allowed by git tip to test a pull request you made on the hub you can pass revision refs pr pr_number tip return_unused_kwargs bool optional defaults to false if false then this function returns just the final configuration object if true then this functions returns a tuple config unused_kwargs where unused_kwargs is a dictionary consisting of the key value pairs whose keys are not configuration attributes i e the part of kwargs which has not been used to update config and is otherwise ignored subfolder str optional defaults to in case the relevant files are located inside a subfolder of the model repo on huggingface co you can specify the folder name here kwargs dict str any optional the values in kwargs of any keys which are configuration attributes will be used to override the loaded values behavior concerning key value pairs whose keys are not configuration attributes is controlled by the return_unused_kwargs keyword parameter returns pretrainedconfig the configuration object instantiated from this pretrained model examples python we can t instantiate directly the base class pretrainedconfig so let s show the examples on a derived class bertconfig config bertconfig from_pretrained bert base uncased download configuration from huggingface co and cache config bertconfig from_pretrained test saved_model e g config or model was saved using save_pretrained test saved_model config bertconfig from_pretrained test saved_model my_configuration json config bertconfig from_pretrained bert base uncased output_attentions true foo false assert config output_attentions true config unused_kwargs bertconfig from_pretrained bert base uncased output_attentions true foo false return_unused_kwargs true assert config output_attentions true assert unused_kwargs foo false from a pretrained_model_name_or_path resolve to a dictionary of parameters to be used for instantiating a pretrainedconfig using from_dict parameters pretrained_model_name_or_path str or os pathlike the identifier of the pre trained checkpoint from which we want the dictionary of parameters returns tuple dict dict the dictionary ies that will be used to instantiate the configuration object get config dict associated with the base config file that config file may point us toward another config file to use special case when pretrained_model_name_or_path is a local file load from local folder or from cache or download from model hub and cache raise any environment error raise by cached_file it will have a helpful error message adapted to the original exception for any other exception we throw a generic error load config dict instantiates a pretrainedconfig from a python dictionary of parameters args config_dict dict str any dictionary that will be used to instantiate the configuration object such a dictionary can be retrieved from a pretrained checkpoint by leveraging the pretrainedconfig get_config_dict method kwargs dict str any additional parameters from which to initialize the configuration object returns pretrainedconfig the configuration object instantiated from those parameters those arguments may be passed along for our internal telemetry we remove them so they don t appear in return_unused_kwargs the commit hash might have been updated in the config_dict we don t want the kwargs to erase that update update config with kwargs if needed to ize passing a custom subconfig as kwarg in models that have nested configs instantiates a pretrainedconfig from the path to a json file of parameters args json_file str or os pathlike path to the json file containing the parameters returns pretrainedconfig the configuration object instantiated from that json file removes all attributes from config which correspond to the default config attributes for better readability and serializes to a python dictionary returns dict str any dictionary of all the attributes that make up this configuration instance get the default config dict get class specific config dict only serialize values that differ from the default config for nested configs we need to clean the diff recursively needs to be set even if it s not in the diff pop the _pre_quantization_dtype as torch dtypes are not serializable serializes this instance to a python dictionary returns dict str any dictionary of all the attributes that make up this configuration instance transformers version when serializing the model deal with nested configs like clip pop the _pre_quantization_dtype as torch dtypes are not serializable serializes this instance to a json string args use_diff bool optional defaults to true if set to true only the difference between the config instance and the default pretrainedconfig is serialized to json string returns str string containing all the attributes that make up this configuration instance in json format save this instance to a json file args json_file_path str or os pathlike path to the json file in which this configuration instance s parameters will be saved use_diff bool optional defaults to true if set to true only the difference between the config instance and the default pretrainedconfig is serialized to json file updates attributes of this class with attributes from config_dict args config_dict dict str any dictionary of attributes that should be updated for this class updates attributes of this class with attributes from update_str the expected format is ints floats and strings as is and for booleans use true or false for example n_embd 10 resid_pdrop 0 2 scale_attn_weights false summary_type cls_index the keys to change have to already exist in the config object args update_str str string with attributes that should be updated for this class checks whether the passed dictionary and its nested dicts have a torch_dtype key and if it s not none converts torch dtype to a string of just the type for example torch float32 get converted into float32 string which can then be stored in the json format register this class with a given auto class this should only be used for custom configurations as the ones in the library are already mapped with autoconfig tip warning true this api is experimental and may have some slight breaking changes in the next releases tip args auto_class str or type optional defaults to autoconfig the auto class to register this new configuration with get the configuration file to use for this version of transformers args configuration_files list str the list of available configuration files returns str the configuration file to use defaults to full_configuration_file and then try to look at some newer versions no point going further since the versions are sorted helper function to recursively take the diff between two nested dictionaries the resulting diff only contains the values from dict_a that are different from values in dict_b
import copy
import json
import os
import re
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union

from packaging import version

from . import __version__
from .dynamic_module_utils import custom_object_save
from .utils import (
    CONFIG_NAME,
    PushToHubMixin,
    add_model_info_to_auto_map,
    cached_file,
    copy_func,
    download_url,
    extract_commit_hash,
    is_remote_url,
    is_torch_available,
    logging,
)


logger = logging.get_logger(__name__)

_re_configuration_file = re.compile(r"config\.(.*)\.json")


class PretrainedConfig(PushToHubMixin):
    
    r

    model_type: str = ""
    is_composition: bool = False
    attribute_map: Dict[str, str] = {}
    _auto_class: Optional[str] = None

    def __setattr__(self, key, value):
        if key in super().__getattribute__("attribute_map"):
            key = super().__getattribute__("attribute_map")[key]
        super().__setattr__(key, value)

    def __getattribute__(self, key):
        if key != "attribute_map" and key in super().__getattribute__("attribute_map"):
            key = super().__getattribute__("attribute_map")[key]
        return super().__getattribute__(key)

    def __init__(self, **kwargs):
        
        self.return_dict = kwargs.pop("return_dict", True)
        self.output_hidden_states = kwargs.pop("output_hidden_states", False)
        self.output_attentions = kwargs.pop("output_attentions", False)
        self.torchscript = kwargs.pop("torchscript", False)  
        self.torch_dtype = kwargs.pop("torch_dtype", None)  
        self.use_bfloat16 = kwargs.pop("use_bfloat16", False)
        self.tf_legacy_loss = kwargs.pop("tf_legacy_loss", False)  
        self.pruned_heads = kwargs.pop("pruned_heads", {})
        self.tie_word_embeddings = kwargs.pop(
            "tie_word_embeddings", True
        )  

        
        self.is_encoder_decoder = kwargs.pop("is_encoder_decoder", False)
        self.is_decoder = kwargs.pop("is_decoder", False)
        self.cross_attention_hidden_size = kwargs.pop("cross_attention_hidden_size", None)
        self.add_cross_attention = kwargs.pop("add_cross_attention", False)
        self.tie_encoder_decoder = kwargs.pop("tie_encoder_decoder", False)

        
        self.max_length = kwargs.pop("max_length", 20)
        self.min_length = kwargs.pop("min_length", 0)
        self.do_sample = kwargs.pop("do_sample", False)
        self.early_stopping = kwargs.pop("early_stopping", False)
        self.num_beams = kwargs.pop("num_beams", 1)
        self.num_beam_groups = kwargs.pop("num_beam_groups", 1)
        self.diversity_penalty = kwargs.pop("diversity_penalty", 0.0)
        self.temperature = kwargs.pop("temperature", 1.0)
        self.top_k = kwargs.pop("top_k", 50)
        self.top_p = kwargs.pop("top_p", 1.0)
        self.typical_p = kwargs.pop("typical_p", 1.0)
        self.repetition_penalty = kwargs.pop("repetition_penalty", 1.0)
        self.length_penalty = kwargs.pop("length_penalty", 1.0)
        self.no_repeat_ngram_size = kwargs.pop("no_repeat_ngram_size", 0)
        self.encoder_no_repeat_ngram_size = kwargs.pop("encoder_no_repeat_ngram_size", 0)
        self.bad_words_ids = kwargs.pop("bad_words_ids", None)
        self.num_return_sequences = kwargs.pop("num_return_sequences", 1)
        self.chunk_size_feed_forward = kwargs.pop("chunk_size_feed_forward", 0)
        self.output_scores = kwargs.pop("output_scores", False)
        self.return_dict_in_generate = kwargs.pop("return_dict_in_generate", False)
        self.forced_bos_token_id = kwargs.pop("forced_bos_token_id", None)
        self.forced_eos_token_id = kwargs.pop("forced_eos_token_id", None)
        self.remove_invalid_values = kwargs.pop("remove_invalid_values", False)
        self.exponential_decay_length_penalty = kwargs.pop("exponential_decay_length_penalty", None)
        self.suppress_tokens = kwargs.pop("suppress_tokens", None)
        self.begin_suppress_tokens = kwargs.pop("begin_suppress_tokens", None)

        
        self.architectures = kwargs.pop("architectures", None)
        self.finetuning_task = kwargs.pop("finetuning_task", None)
        self.id2label = kwargs.pop("id2label", None)
        self.label2id = kwargs.pop("label2id", None)
        if self.label2id is not None and not isinstance(self.label2id, dict):
            raise ValueError("Argument label2id should be a dictionary.")
        if self.id2label is not None:
            if not isinstance(self.id2label, dict):
                raise ValueError("Argument id2label should be a dictionary.")
            num_labels = kwargs.pop("num_labels", None)
            if num_labels is not None and len(self.id2label) != num_labels:
                logger.warning(
                    f"You passed along `num_labels={num_labels}` with an incompatible id to label map: "
                    f"{self.id2label}. The number of labels wil be overwritten to {self.num_labels}."
                )
            self.id2label = {int(key): value for key, value in self.id2label.items()}
            
        else:
            self.num_labels = kwargs.pop("num_labels", 2)

        if self.torch_dtype is not None and isinstance(self.torch_dtype, str):
            
            
            if is_torch_available():
                import torch

                self.torch_dtype = getattr(torch, self.torch_dtype)

        
        self.tokenizer_class = kwargs.pop("tokenizer_class", None)
        self.prefix = kwargs.pop("prefix", None)
        self.bos_token_id = kwargs.pop("bos_token_id", None)
        self.pad_token_id = kwargs.pop("pad_token_id", None)
        self.eos_token_id = kwargs.pop("eos_token_id", None)
        self.sep_token_id = kwargs.pop("sep_token_id", None)

        self.decoder_start_token_id = kwargs.pop("decoder_start_token_id", None)

        
        self.task_specific_params = kwargs.pop("task_specific_params", None)

        
        self.problem_type = kwargs.pop("problem_type", None)
        allowed_problem_types = ("regression", "single_label_classification", "multi_label_classification")
        if self.problem_type is not None and self.problem_type not in allowed_problem_types:
            raise ValueError(
                f"The config parameter `problem_type` was not understood: received {self.problem_type} "
                "but only 'regression', 'single_label_classification' and 'multi_label_classification' are valid."
            )

        
        if kwargs.pop("xla_device", None) is not None:
            logger.warning(
                "The `xla_device` argument has been deprecated in v4.4.0 of Transformers. It is ignored and you can "
                "safely remove it from your `config.json` file."
            )

        
        self._name_or_path = str(kwargs.pop("name_or_path", ""))
        
        self._commit_hash = kwargs.pop("_commit_hash", None)

        
        self.transformers_version = kwargs.pop("transformers_version", None)

        
        if kwargs.get("gradient_checkpointing", False):
            warnings.warn(
                "Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 "
                "Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the "
                "`Trainer` API, pass `gradient_checkpointing=True` in your `TrainingArguments`."
            )

        
        for key, value in kwargs.items():
            try:
                setattr(self, key, value)
            except AttributeError as err:
                logger.error(f"Can't set {key} with value {value} for {self}")
                raise err

    @property
    def name_or_path(self) -> str:
        return getattr(self, "_name_or_path", None)

    @name_or_path.setter
    def name_or_path(self, value):
        self._name_or_path = str(value)  

    @property
    def use_return_dict(self) -> bool:
        
        
        return self.return_dict and not self.torchscript

    @property
    def num_labels(self) -> int:
        
        return len(self.id2label)

    @num_labels.setter
    def num_labels(self, num_labels: int):
        if not hasattr(self, "id2label") or self.id2label is None or len(self.id2label) != num_labels:
            self.id2label = {i: f"LABEL_{i}" for i in range(num_labels)}
            self.label2id = dict(zip(self.id2label.values(), self.id2label.keys()))

    def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
        
        self._set_token_in_kwargs(kwargs)

        if os.path.isfile(save_directory):
            raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")

        os.makedirs(save_directory, exist_ok=True)

        if push_to_hub:
            commit_message = kwargs.pop("commit_message", None)
            repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
            repo_id = self._create_repo(repo_id, **kwargs)
            files_timestamps = self._get_files_timestamps(save_directory)

        
        
        if self._auto_class is not None:
            custom_object_save(self, save_directory, config=self)

        
        output_config_file = os.path.join(save_directory, CONFIG_NAME)

        self.to_json_file(output_config_file, use_diff=True)
        logger.info(f"Configuration saved in {output_config_file}")

        if push_to_hub:
            self._upload_modified_files(
                save_directory,
                repo_id,
                files_timestamps,
                commit_message=commit_message,
                token=kwargs.get("token"),
            )

    @staticmethod
    def _set_token_in_kwargs(kwargs, token=None):
        
        
        if token is None:
            token = kwargs.pop("token", None)
        use_auth_token = kwargs.pop("use_auth_token", None)

        if use_auth_token is not None:
            warnings.warn(
                "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
                FutureWarning,
            )
            if token is not None:
                raise ValueError(
                    "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
                )
            token = use_auth_token

        if token is not None:
            kwargs["token"] = token

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: Union[str, os.PathLike],
        cache_dir: Optional[Union[str, os.PathLike]] = None,
        force_download: bool = False,
        local_files_only: bool = False,
        token: Optional[Union[str, bool]] = None,
        revision: str = "main",
        **kwargs,
    ) -> "PretrainedConfig":
        r
        kwargs["cache_dir"] = cache_dir
        kwargs["force_download"] = force_download
        kwargs["local_files_only"] = local_files_only
        kwargs["revision"] = revision

        cls._set_token_in_kwargs(kwargs, token)

        config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
        if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
            logger.warning(
                f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
                f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
            )

        return cls.from_dict(config_dict, **kwargs)

    @classmethod
    def get_config_dict(
        cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
    ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
        
        cls._set_token_in_kwargs(kwargs)

        original_kwargs = copy.deepcopy(kwargs)
        
        config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
        if "_commit_hash" in config_dict:
            original_kwargs["_commit_hash"] = config_dict["_commit_hash"]

        
        if "configuration_files" in config_dict:
            configuration_file = get_configuration_file(config_dict["configuration_files"])
            config_dict, kwargs = cls._get_config_dict(
                pretrained_model_name_or_path, _configuration_file=configuration_file, **original_kwargs
            )

        return config_dict, kwargs

    @classmethod
    def _get_config_dict(
        cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
    ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
        cache_dir = kwargs.pop("cache_dir", None)
        force_download = kwargs.pop("force_download", False)
        resume_download = kwargs.pop("resume_download", False)
        proxies = kwargs.pop("proxies", None)
        token = kwargs.pop("token", None)
        local_files_only = kwargs.pop("local_files_only", False)
        revision = kwargs.pop("revision", None)
        trust_remote_code = kwargs.pop("trust_remote_code", None)
        subfolder = kwargs.pop("subfolder", "")
        from_pipeline = kwargs.pop("_from_pipeline", None)
        from_auto_class = kwargs.pop("_from_auto", False)
        commit_hash = kwargs.pop("_commit_hash", None)

        if trust_remote_code is True:
            logger.warning(
                "The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is"
                " ignored."
            )

        user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
        if from_pipeline is not None:
            user_agent["using_pipeline"] = from_pipeline

        pretrained_model_name_or_path = str(pretrained_model_name_or_path)

        is_local = os.path.isdir(pretrained_model_name_or_path)
        if os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
            
            resolved_config_file = pretrained_model_name_or_path
            is_local = True
        elif is_remote_url(pretrained_model_name_or_path):
            configuration_file = pretrained_model_name_or_path
            resolved_config_file = download_url(pretrained_model_name_or_path)
        else:
            configuration_file = kwargs.pop("_configuration_file", CONFIG_NAME)

            try:
                
                resolved_config_file = cached_file(
                    pretrained_model_name_or_path,
                    configuration_file,
                    cache_dir=cache_dir,
                    force_download=force_download,
                    proxies=proxies,
                    resume_download=resume_download,
                    local_files_only=local_files_only,
                    token=token,
                    user_agent=user_agent,
                    revision=revision,
                    subfolder=subfolder,
                    _commit_hash=commit_hash,
                )
                commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
            except EnvironmentError:
                
                
                raise
            except Exception:
                
                raise EnvironmentError(
                    f"Can't load the configuration of '{pretrained_model_name_or_path}'. If you were trying to load it"
                    " from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
                    f" name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory"
                    f" containing a {configuration_file} file"
                )

        try:
            
            config_dict = cls._dict_from_json_file(resolved_config_file)
            config_dict["_commit_hash"] = commit_hash
        except (json.JSONDecodeError, UnicodeDecodeError):
            raise EnvironmentError(
                f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file."
            )

        if is_local:
            logger.info(f"loading configuration file {resolved_config_file}")
        else:
            logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")

        if "auto_map" in config_dict and not is_local:
            config_dict["auto_map"] = add_model_info_to_auto_map(
                config_dict["auto_map"], pretrained_model_name_or_path
            )
        return config_dict, kwargs

    @classmethod
    def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PretrainedConfig":
        
        return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
        
        
        kwargs.pop("_from_auto", None)
        kwargs.pop("_from_pipeline", None)
        
        if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
            kwargs["_commit_hash"] = config_dict["_commit_hash"]

        config = cls(**config_dict)

        if hasattr(config, "pruned_heads"):
            config.pruned_heads = {int(key): value for key, value in config.pruned_heads.items()}

        
        if "num_labels" in kwargs and "id2label" in kwargs:
            num_labels = kwargs["num_labels"]
            id2label = kwargs["id2label"] if kwargs["id2label"] is not None else []
            if len(id2label) != num_labels:
                raise ValueError(
                    f"You passed along `num_labels={num_labels }` with an incompatible id to label map: "
                    f"{kwargs['id2label']}. Since those arguments are inconsistent with each other, you should remove "
                    "one of them."
                )
        to_remove = []
        for key, value in kwargs.items():
            if hasattr(config, key):
                current_attr = getattr(config, key)
                
                if isinstance(current_attr, PretrainedConfig) and isinstance(value, dict):
                    value = current_attr.__class__(**value)
                setattr(config, key, value)
                if key != "torch_dtype":
                    to_remove.append(key)
        for key in to_remove:
            kwargs.pop(key, None)

        logger.info(f"Model config {config}")
        if return_unused_kwargs:
            return config, kwargs
        else:
            return config

    @classmethod
    def from_json_file(cls, json_file: Union[str, os.PathLike]) -> "PretrainedConfig":
        
        config_dict = cls._dict_from_json_file(json_file)
        return cls(**config_dict)

    @classmethod
    def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
        with open(json_file, "r", encoding="utf-8") as reader:
            text = reader.read()
        return json.loads(text)

    def __eq__(self, other):
        return isinstance(other, PretrainedConfig) and (self.__dict__ == other.__dict__)

    def __repr__(self):
        return f"{self.__class__.__name__} {self.to_json_string()}"

    def to_diff_dict(self) -> Dict[str, Any]:
        
        config_dict = self.to_dict()

        
        default_config_dict = PretrainedConfig().to_dict()

        
        class_config_dict = self.__class__().to_dict() if not self.is_composition else {}

        serializable_config_dict = {}

        
        for key, value in config_dict.items():
            if (
                isinstance(getattr(self, key, None), PretrainedConfig)
                and key in class_config_dict
                and isinstance(class_config_dict[key], dict)
            ):
                
                diff = recursive_diff_dict(value, class_config_dict[key], config_obj=getattr(self, key, None))
                if "model_type" in value:
                    
                    diff["model_type"] = value["model_type"]
                if len(diff) > 0:
                    serializable_config_dict[key] = diff
            elif (
                key not in default_config_dict
                or key == "transformers_version"
                or value != default_config_dict[key]
                or (key in class_config_dict and value != class_config_dict[key])
            ):
                serializable_config_dict[key] = value

        if hasattr(self, "quantization_config"):
            serializable_config_dict["quantization_config"] = (
                self.quantization_config.to_dict()
                if not isinstance(self.quantization_config, dict)
                else self.quantization_config
            )

            
            _ = serializable_config_dict.pop("_pre_quantization_dtype", None)

        self.dict_torch_dtype_to_str(serializable_config_dict)

        if "_flash_attn_2_enabled" in serializable_config_dict:
            del serializable_config_dict["_flash_attn_2_enabled"]

        return serializable_config_dict

    def to_dict(self) -> Dict[str, Any]:
        
        output = copy.deepcopy(self.__dict__)
        if hasattr(self.__class__, "model_type"):
            output["model_type"] = self.__class__.model_type
        if "_auto_class" in output:
            del output["_auto_class"]
        if "_commit_hash" in output:
            del output["_commit_hash"]
        if "_flash_attn_2_enabled" in output:
            del output["_flash_attn_2_enabled"]

        
        output["transformers_version"] = __version__

        for key, value in output.items():
            
            if isinstance(value, PretrainedConfig):
                value = value.to_dict()
                del value["transformers_version"]

            output[key] = value

        if hasattr(self, "quantization_config"):
            output["quantization_config"] = (
                self.quantization_config.to_dict()
                if not isinstance(self.quantization_config, dict)
                else self.quantization_config
            )

            
            _ = output.pop("_pre_quantization_dtype", None)

        self.dict_torch_dtype_to_str(output)

        return output

    def to_json_string(self, use_diff: bool = True) -> str:
        
        if use_diff is True:
            config_dict = self.to_diff_dict()
        else:
            config_dict = self.to_dict()
        return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"

    def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
        
        with open(json_file_path, "w", encoding="utf-8") as writer:
            writer.write(self.to_json_string(use_diff=use_diff))

    def update(self, config_dict: Dict[str, Any]):
        
        for key, value in config_dict.items():
            setattr(self, key, value)

    def update_from_string(self, update_str: str):
        

        d = dict(x.split("=") for x in update_str.split(","))
        for k, v in d.items():
            if not hasattr(self, k):
                raise ValueError(f"key {k} isn't in the original config dict")

            old_v = getattr(self, k)
            if isinstance(old_v, bool):
                if v.lower() in ["true", "1", "y", "yes"]:
                    v = True
                elif v.lower() in ["false", "0", "n", "no"]:
                    v = False
                else:
                    raise ValueError(f"can't derive true or false from {v} (key {k})")
            elif isinstance(old_v, int):
                v = int(v)
            elif isinstance(old_v, float):
                v = float(v)
            elif not isinstance(old_v, str):
                raise ValueError(
                    f"You can only update int, float, bool or string values in the config, got {v} for key {k}"
                )

            setattr(self, k, v)

    def dict_torch_dtype_to_str(self, d: Dict[str, Any]) -> None:
        
        if d.get("torch_dtype", None) is not None and not isinstance(d["torch_dtype"], str):
            d["torch_dtype"] = str(d["torch_dtype"]).split(".")[1]
        for value in d.values():
            if isinstance(value, dict):
                self.dict_torch_dtype_to_str(value)

    @classmethod
    def register_for_auto_class(cls, auto_class="AutoConfig"):
        
        if not isinstance(auto_class, str):
            auto_class = auto_class.__name__

        import transformers.models.auto as auto_module

        if not hasattr(auto_module, auto_class):
            raise ValueError(f"{auto_class} is not a valid auto class.")

        cls._auto_class = auto_class


def get_configuration_file(configuration_files: List[str]) -> str:
    
    configuration_files_map = {}
    for file_name in configuration_files:
        search = _re_configuration_file.search(file_name)
        if search is not None:
            v = search.groups()[0]
            configuration_files_map[v] = file_name
    available_versions = sorted(configuration_files_map.keys())

    
    configuration_file = CONFIG_NAME
    transformers_version = version.parse(__version__)
    for v in available_versions:
        if version.parse(v) <= transformers_version:
            configuration_file = configuration_files_map[v]
        else:
            
            break

    return configuration_file


def recursive_diff_dict(dict_a, dict_b, config_obj=None):
    
    diff = {}
    default = config_obj.__class__().to_dict() if config_obj is not None else {}
    for key, value in dict_a.items():
        obj_value = getattr(config_obj, str(key), None)
        if isinstance(obj_value, PretrainedConfig) and key in dict_b and isinstance(dict_b[key], dict):
            diff_value = recursive_diff_dict(value, dict_b[key], config_obj=obj_value)
            if len(diff_value) > 0:
                diff[key] = diff_value
        elif key not in dict_b or value != dict_b[key] or key not in default or value != default[key]:
            diff[key] = value
    return diff


PretrainedConfig.push_to_hub = copy_func(PretrainedConfig.push_to_hub)
if PretrainedConfig.push_to_hub.__doc__ is not None:
    PretrainedConfig.push_to_hub.__doc__ = PretrainedConfig.push_to_hub.__doc__.format(
        object="config", object_class="AutoConfig", object_files="configuration file"
    )