Configuration¶

The base class PretrainedConfig implements the common methods for loading/saving a configuration either from a local file or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace’s AWS S3 repository).

PretrainedConfig¶

class transformers.PretrainedConfig(**kwargs)[source]¶

Base class for all configuration classes. Handles a few parameters common to all models’ configurations as well as methods for loading/downloading/saving configurations.

Note

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.

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 AutoConfig.

Parameters
  • 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.

  • use_cache (bool, optional, defaults to True) – Whether or not the model should return the last key/values attentions (not used by all models).

  • return_dict (bool, optional, defaults to False) – Whether or not the model should return a 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).

  • 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 :class:~transformers.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.

  • xla_device (bool, optional) – A flag to indicate if TPU are available or not.

  • 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? .

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 10) – 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.

  • temperature (float, optional, defaults to 1) – 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.

  • 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 will be used by default in the generate method of the model.

  • 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.

  • 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.

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 (List[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.

Parameters linked to the tokenizer
  • 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.

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).

classmethod from_dict(config_dict: Dict[str, Any], **kwargs) → transformers.configuration_utils.PretrainedConfig[source]¶

Instantiates a PretrainedConfig from a Python dictionary of parameters.

Parameters
  • 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 get_config_dict() method.

  • kwargs (Dict[str, Any]) – Additional parameters from which to initialize the configuration object.

Returns

The configuration object instantiated from those parameters.

Return type

PretrainedConfig

classmethod from_json_file(json_file: str) → transformers.configuration_utils.PretrainedConfig[source]¶

Instantiates a PretrainedConfig from the path to a JSON file of parameters.

Parameters

json_file (str) – Path to the JSON file containing the parameters.

Returns

The configuration object instantiated from that JSON file.

Return type

PretrainedConfig

classmethod from_pretrained(pretrained_model_name_or_path: str, **kwargs) → transformers.configuration_utils.PretrainedConfig[source]¶

Instantiate a PretrainedConfig (or a derived class) from a pretrained model configuration.

Parameters
  • pretrained_model_name_or_path (str) –

    This can be either:

    • the shortcut name of a pretrained model configuration to load from cache or download, e.g., bert-base-uncased.

    • the identifier name of a pretrained model configuration that was uploaded to our S3 by any user, e.g., dbmdz/bert-base-german-cased.

    • a path to a directory containing a configuration file saved using the 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, 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) – Wheter 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.

  • 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.

  • 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

The configuration object instantiated from this pretrained model.

Return type

PretrainedConfig

Examples:

# 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 S3 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}
classmethod get_config_dict(pretrained_model_name_or_path: str, **kwargs) → Tuple[Dict[str, Any], Dict[str, Any]][source]¶

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) – The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.

Returns

The dictionary(ies) that will be used to instantiate the configuration object.

Return type

Tuple[Dict, Dict]

property num_labels¶

The number of labels for classification models.

Type

int

save_pretrained(save_directory: str)[source]¶

Save a configuration object to the directory save_directory, so that it can be re-loaded using the from_pretrained() class method.

Parameters

save_directory (str) – Directory where the configuration JSON file will be saved (will be created if it does not exist).

to_dict() → Dict[str, Any][source]¶

Serializes this instance to a Python dictionary.

Returns

Dictionary of all the attributes that make up this configuration instance.

Return type

Dict[str, Any]

to_diff_dict() → Dict[str, Any][source]¶

Removes all attributes from config which correspond to the default config attributes for better readability and serializes to a Python dictionary.

Returns

Dictionary of all the attributes that make up this configuration instance,

Return type

Dict[str, Any]

to_json_file(json_file_path: str, use_diff: bool = True)[source]¶

Save this instance to a JSON file.

Parameters
  • json_file_path (str) – 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.

to_json_string(use_diff: bool = True) → str[source]¶

Serializes this instance to a JSON string.

Parameters

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

String containing all the attributes that make up this configuration instance in JSON format.

Return type

str

update(config_dict: Dict[str, Any])[source]¶

Updates attributes of this class with attributes from config_dict.

Parameters

config_dict (Dict[str, Any]) – Dictionary of attributes that shall be updated for this class.

property use_return_dict¶

Whether or not return ModelOutput instead of tuples.

Type

bool