# Models¶

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

PreTrainedModel also implements a few methods which are common among all the models to:

• resize the input token embeddings when new tokens are added to the vocabulary

• prune the attention heads of the model.

## PreTrainedModel¶

class transformers.PreTrainedModel(config, *inputs, **kwargs)[source]

Base class for all models.

PreTrainedModel takes care of storing the configuration of the models and handles methods for loading/downloading/saving models as well as a few methods common to all models to (i) resize the input embeddings and (ii) prune heads in the self-attention heads.

Class attributes (overridden by derived classes):
• config_class: a class derived from PretrainedConfig to use as configuration class for this model architecture.

• pretrained_model_archive_map: a python dict of with short-cut-names (string) as keys and url (string) of associated pretrained weights as values.

• load_tf_weights: a python method for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments:

• base_model_prefix: a string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.

property dummy_inputs

Dummy inputs to do a forward pass in the network.

Returns

torch.Tensor with dummy inputs

enforce_repetition_penalty_(lprobs, batch_size, num_beams, prev_output_tokens, repetition_penalty)[source]

repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858).

classmethod from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)[source]

Instantiate a pretrained pytorch model from a pre-trained model configuration.

The model is set in evaluation mode by default using model.eval() (Dropout modules are deactivated) To train the model, you should first set it back in training mode with model.train()

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pre-trained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

Parameters
• pretrained_model_name_or_path – either: - a string with the shortcut name of a pre-trained model to load from cache or download, e.g.: bert-base-uncased. - a string with the identifier name of a pre-trained model that was user-uploaded to our S3, e.g.: dbmdz/bert-base-german-cased. - a path to a directory containing model weights saved using save_pretrained(), e.g.: ./my_model_directory/. - a path or url to a tensorflow index checkpoint file (e.g. ./tf_model/model.ckpt.index). In this case, from_tf should be set to True and a configuration object should be provided as config argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. - None if you are both providing the configuration and state dictionary (resp. with keyword arguments config and state_dict)

• model_args – (optional) Sequence of positional arguments: All remaning positional arguments will be passed to the underlying model’s __init__ method

• config

(optional) one of: - an instance of a class derived from PretrainedConfig, or - a string valid as input to from_pretrained() Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when:

• the model is a model provided by the library (loaded with the shortcut-name string of a pretrained model), or

• the model was saved using save_pretrained() and is reloaded by suppling the save directory.

• the model is loaded by suppling a local directory as pretrained_model_name_or_path and a configuration JSON file named config.json is found in the directory.

• state_dict – (optional) dict: an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.

• cache_dir – (optional) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used.

• force_download – (optional) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists.

• resume_download – (optional) boolean, default False: Do not delete incompletely recieved file. Attempt to resume the download if such a file exists.

• proxies – (optional) dict, default None: 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.

• output_loading_info – (optional) boolean: Set to True to also return a dictionnary containing missing keys, unexpected keys and error messages.

• kwargs

(optional) Remaining dictionary of keyword arguments: Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. output_attention=True). Behave differently depending on whether a config is provided or automatically loaded:

• If a configuration is provided with config, **kwargs will be directly passed to the underlying model’s __init__ method (we assume all relevant updates to the configuration have already been done)

• If a configuration is not provided, kwargs will be first passed to the configuration class initialization function (from_pretrained()). Each key of kwargs that corresponds to a configuration attribute will be used to override said attribute with the supplied kwargs value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s __init__ function.

Examples:

# For example purposes. Not runnable.
model = BertModel.from_pretrained('bert-base-uncased')    # Download model and configuration from S3 and cache.
model = BertModel.from_pretrained('./test/saved_model/')  # E.g. model was saved using save_pretrained('./test/saved_model/')
assert model.config.output_attention == True
config = BertConfig.from_json_file('./tf_model/my_tf_model_config.json')
model = BertModel.from_pretrained('./tf_model/my_tf_checkpoint.ckpt.index', from_tf=True, config=config)

generate(**kwargs)[source]

Generates sequences for models with a LM head. The method currently supports greedy decoding, beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.

Parameters
• input_ids – (optional) torch.LongTensor of shape (batch_size, sequence_length) The sequence used as a prompt for the generation. If None the method initializes it as an empty torch.LongTensor of shape (1,).

• max_length – (optional) int The max length of the sequence to be generated. Between min_length and infinity. Default to 20.

• min_length – (optional) int The min length of the sequence to be generated. Between 0 and infinity. Default to 0.

• do_sample – (optional) bool If set to False greedy decoding is used. Otherwise sampling is used. Defaults to False as defined in configuration_utils.PretrainedConfig.

• early_stopping – (optional) bool if set to True beam search is stopped when at least num_beams sentences finished per batch. Defaults to False as defined in configuration_utils.PretrainedConfig.

• num_beams – (optional) int Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.

• temperature – (optional) float The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.

• top_k – (optional) int The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.

• top_p – (optional) float The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.

• repetition_penalty – (optional) float The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.

• pad_token_id – (optional) int Padding token. Default to specicic model pad_token_id or None if it does not exist.

• bos_token_id – (optional) int BOS token. Defaults to bos_token_id as defined in the models config.

• eos_token_id – (optional) int EOS token. Defaults to eos_token_id as defined in the models config.

• length_penalty – (optional) float Exponential penalty to the length. Default to 1.

• no_repeat_ngram_size – (optional) int If set to int > 0, all ngrams of size no_repeat_ngram_size can only occur once.

• bad_words_ids – (optional) list of lists of int bad_words_ids contains tokens that are not allowed to be generated. 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 – (optional) int The number of independently computed returned sequences for each element in the batch. Default to 1.

torch.LongTensor of same shape as input_ids Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]: 1 for tokens that are NOT MASKED, 0 for MASKED tokens. Defaults to None.

• decoder_start_token_id=None – (optional) int If an encoder-decoder model starts decoding with a different token than BOS. Defaults to None and is changed to BOS later.

• use_cache – (optional) bool If use_cache is True, past key values are used to speed up decoding if applicable to model. Defaults to True.

• model_specific_kwargs – (optional) dict Additional model specific kwargs will be forwarded to the forward function of the model.

Returns

torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

sequence_length is either equal to max_length or shorter if all batches finished early due to the eos_token_id

Return type

output

Examples:

tokenizer = AutoTokenizer.from_pretrained('distilgpt2')   # Initialize tokenizer
outputs = model.generate(max_length=40)  # do greedy decoding
print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('openai-gpt')   # Initialize tokenizer
input_context = 'The dog'
input_ids = tokenizer.encode(input_context, return_tensors='pt')  # encode input context
outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5)  # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'
for i in range(3): #  3 output sequences were generated
print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('distilgpt2')   # Initialize tokenizer
input_context = 'The dog'
input_ids = tokenizer.encode(input_context, return_tensors='pt')  # encode input context
outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3)  # 3 generate sequences using by sampling
for i in range(3): #  3 output sequences were generated
print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('ctrl')   # Initialize tokenizer
input_context = 'Legal My neighbor is'  # "Legal" is one of the control codes for ctrl
input_ids = tokenizer.encode(input_context, return_tensors='pt')  # encode input context
outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2)  # generate sequences
print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('gpt2')   # Initialize tokenizer
input_context = 'My cute dog'  # "Legal" is one of the control codes for ctrl
input_ids = tokenizer.encode(input_context, return_tensors='pt')  # encode input context

get_input_embeddings()[source]

Returns the model’s input embeddings.

Returns

A torch module mapping vocabulary to hidden states.

Return type

nn.Module

get_output_embeddings()[source]

Returns the model’s output embeddings.

Returns

A torch module mapping hidden states to vocabulary.

Return type

nn.Module

init_weights()[source]

Initialize and prunes weights if needed.

prune_heads(heads_to_prune)[source]

Prunes heads of the base model.

Parameters
• heads_to_prune – dict with keys being selected layer indices (int) and associated values being the list of heads to prune in said layer (list of int).

• {1 (E.g.) – [0, 2], 2: [2, 3]} will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2.

resize_token_embeddings(new_num_tokens=None)[source]

Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying weights embeddings afterwards if the model class has a tie_weights() method.

Parameters

new_num_tokens – (optional) int: New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and just returns a pointer to the input tokens torch.nn.Embeddings Module of the model.

Return: torch.nn.Embeddings

Pointer to the input tokens Embeddings Module of the model

save_pretrained(save_directory)[source]

Save a model and its configuration file to a directory, so that it can be re-loaded using the :func:~transformers.PreTrainedModel.from_pretrained class method.

Parameters

save_directory – directory to which to save.

set_input_embeddings(value)[source]

Set model’s input embeddings

Parameters

value (nn.Module) – A module mapping vocabulary to hidden states.

tie_weights()[source]

Tie the weights between the input embeddings and the output embeddings. If the torchscript flag is set in the configuration, can’t handle parameter sharing so we are cloning the weights instead.

## Helper Functions¶

transformers.apply_chunking_to_forward(chunk_size: int, chunk_dim: int, forward_fn: Callable[…, torch.Tensor], *input_tensors) → torch.Tensor[source]

This function chunks the input_tensors into smaller input tensor parts of size chunk_size over the dimension chunk_dim. It then applies a layer forward_fn to each chunk independently to save memory. If the forward_fn is independent across the chunk_dim this function will yield the same result as not applying it.

Parameters
• chunk_size – int - the chunk size of a chunked tensor. num_chunks = len(input_tensors[0]) / chunk_size

• chunk_dim – int - the dimension over which the input_tensors should be chunked

• forward_fn – fn - the forward fn of the model

• input_tensors – tuple(torch.Tensor) - the input tensors of forward_fn which are chunked

Returns

a Tensor with the same shape the foward_fn would have given if applied

Examples:

# rename the usual forward() fn to forward_chunk()
def forward_chunk(self, hidden_states):
hidden_states = self.decoder(hidden_states)
return hidden_states

# implement a chunked forward function
def forward(self, hidden_states):


## TFPreTrainedModel¶

class transformers.TFPreTrainedModel(*args, **kwargs)[source]

Base class for all TF models.

TFPreTrainedModel takes care of storing the configuration of the models and handles methods for loading/downloading/saving models as well as a few methods common to all models to (i) resize the input embeddings and (ii) prune heads in the self-attention heads.

Class attributes (overridden by derived classes):
• config_class: a class derived from PretrainedConfig to use as configuration class for this model architecture.

• pretrained_model_archive_map: a python dict of with short-cut-names (string) as keys and url (string) of associated pretrained weights as values.

• load_tf_weights: a python method for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments:

• base_model_prefix: a string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.

property dummy_inputs

Dummy inputs to build the network.

Returns

tf.Tensor with dummy inputs

classmethod from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)[source]

Instantiate a pretrained TF 2.0 model from a pre-trained model configuration.

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pre-trained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

Parameters
• pretrained_model_name_or_path

either:

• a string with the shortcut name of a pre-trained model to load from cache or download, e.g.: bert-base-uncased.

• a string with the identifier name of a pre-trained model that was user-uploaded to our S3, e.g.: dbmdz/bert-base-german-cased.

• a path to a directory containing model weights saved using save_pretrained(), e.g.: ./my_model_directory/.

• a path or url to a PyTorch state_dict save file (e.g. ./pt_model/pytorch_model.bin). In this case, from_pt should be set to True and a configuration object should be provided as config argument. This loading path is slower than converting the PyTorch checkpoint in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.

• model_args – (optional) Sequence of positional arguments: All remaning positional arguments will be passed to the underlying model’s __init__ method

• config

(optional) one of:

Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when:

• the model is a model provided by the library (loaded with the shortcut-name string of a pretrained model), or

• the model was saved using save_pretrained() and is reloaded by suppling the save directory.

• the model is loaded by suppling a local directory as pretrained_model_name_or_path and a configuration JSON file named config.json is found in the directory.

• from_pt – (optional) boolean, default False: Load the model weights from a PyTorch state_dict save file (see docstring of pretrained_model_name_or_path argument).

• cache_dir – (optional) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used.

• force_download – (optional) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists.

• resume_download – (optional) boolean, default False: Do not delete incompletely recieved file. Attempt to resume the download if such a file exists.

• proxies – (optional) dict, default None: 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.

• output_loading_info – (optional) boolean: Set to True to also return a dictionnary containing missing keys, unexpected keys and error messages.

• kwargs

(optional) Remaining dictionary of keyword arguments: Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. output_attention=True). Behave differently depending on whether a config is provided or automatically loaded:

• If a configuration is provided with config, **kwargs will be directly passed to the underlying model’s __init__ method (we assume all relevant updates to the configuration have already been done)

• If a configuration is not provided, kwargs will be first passed to the configuration class initialization function (from_pretrained()). Each key of kwargs that corresponds to a configuration attribute will be used to override said attribute with the supplied kwargs value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s __init__ function.

Examples:

# For example purposes. Not runnable.
model = BertModel.from_pretrained('bert-base-uncased')    # Download model and configuration from S3 and cache.
model = BertModel.from_pretrained('./test/saved_model/')  # E.g. model was saved using save_pretrained('./test/saved_model/')
assert model.config.output_attention == True
config = BertConfig.from_json_file('./tf_model/my_tf_model_config.json')
model = BertModel.from_pretrained('./tf_model/my_tf_checkpoint.ckpt.index', from_pt=True, config=config)

generate(input_ids=None, max_length=None, min_length=None, do_sample=None, early_stopping=None, num_beams=None, temperature=None, top_k=None, top_p=None, repetition_penalty=None, bad_words_ids=None, bos_token_id=None, pad_token_id=None, eos_token_id=None, length_penalty=None, no_repeat_ngram_size=None, num_return_sequences=None, attention_mask=None, decoder_start_token_id=None, use_cache=None)[source]

Generates sequences for models with a LM head. The method currently supports greedy or penalized greedy decoding, sampling with top-k or nucleus sampling and beam-search.

Parameters
• input_ids – (optional) tf.Tensor of dtype=tf.int32 of shape (batch_size, sequence_length) The sequence used as a prompt for the generation. If None the method initializes it as an empty tf.Tensor of shape (1,).

• max_length – (optional) int The max length of the sequence to be generated. Between 1 and infinity. Default to 20.

• min_length – (optional) int The min length of the sequence to be generated. Between 0 and infinity. Default to 0.

• do_sample – (optional) bool If set to False greedy decoding is used. Otherwise sampling is used. Defaults to False as defined in configuration_utils.PretrainedConfig.

• early_stopping – (optional) bool if set to True beam search is stopped when at least num_beams sentences finished per batch. Defaults to False as defined in configuration_utils.PretrainedConfig.

• num_beams – (optional) int Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.

• temperature – (optional) float The value used to module the next token probabilities. Must be strictely positive. Default to 1.0.

• top_k – (optional) int The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.

• top_p – (optional) float The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.

• repetition_penalty – (optional) float The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.

• bos_token_id – (optional) int Beginning of sentence token if no prompt is provided. Default to specicic model bos_token_id or None if it does not exist.

• eos_token_id – (optional) int EOS token. Defaults to eos_token_id as defined in the models config.

• length_penalty – (optional) float Exponential penalty to the length. Default to 1.

• no_repeat_ngram_size – (optional) int If set to int > 0, all ngrams of size no_repeat_ngram_size can only occur once.

• bad_words_ids – (optional) list of lists of int bad_words_ids contains tokens that are not allowed to be generated. 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 – (optional) int The number of independently computed returned sequences for each element in the batch. Default to 1.

tf.Tensor with dtype=tf.int32 of same shape as input_ids Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]: 1 for tokens that are NOT MASKED, 0 for MASKED tokens. Defaults to None.

• decoder_start_token_id=None – (optional) int If an encoder-decoder model starts decoding with a different token than BOS. Defaults to None and is changed to BOS later.

• use_cache – (optional) bool If use_cache is True, past key values are used to speed up decoding if applicable to model. Defaults to True.

Returns

tf.Tensor of dtype=tf.int32 shape (batch_size * num_return_sequences, sequence_length)

sequence_length is either equal to max_length or shorter if all batches finished early due to the eos_token_id

Return type

output

Examples:

tokenizer = AutoTokenizer.from_pretrained('distilgpt2')   # Initialize tokenizer
outputs = model.generate(max_length=40)  # do greedy decoding
print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('openai-gpt')   # Initialize tokenizer
input_context = 'The dog'
input_ids = tokenizer.encode(input_context, return_tensors='tf')  # encode input context
outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5)  # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'
for i in range(3): #  3 output sequences were generated
print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('distilgpt2')   # Initialize tokenizer
input_context = 'The dog'
input_ids = tokenizer.encode(input_context, return_tensors='tf')  # encode input context
outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3)  # 3 generate sequences using by sampling
for i in range(3): #  3 output sequences were generated
print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('ctrl')   # Initialize tokenizer
input_context = 'Legal My neighbor is'  # "Legal" is one of the control codes for ctrl
input_ids = tokenizer.encode(input_context, return_tensors='tf')  # encode input context
outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2)  # generate sequences
print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))

tokenizer = AutoTokenizer.from_pretrained('gpt2')   # Initialize tokenizer
input_context = 'My cute dog'  # "Legal" is one of the control codes for ctrl
input_ids = tokenizer.encode(input_context, return_tensors='tf')  # encode input context

get_input_embeddings()[source]

Returns the model’s input embeddings.

Returns

A torch module mapping vocabulary to hidden states.

Return type

tf.keras.layers.Layer

get_output_embeddings()[source]

Returns the model’s output embeddings.

Returns

A torch module mapping hidden states to vocabulary.

Return type

tf.keras.layers.Layer

prune_heads(heads_to_prune)[source]

Prunes heads of the base model.

Parameters

heads_to_prune – dict with keys being selected layer indices (int) and associated values being the list of heads to prune in said layer (list of int).

resize_token_embeddings(new_num_tokens=None)[source]

Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying weights embeddings afterwards if the model class has a tie_weights() method.

Parameters

new_num_tokens – (optional) int: New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and just returns a pointer to the input tokens tf.Variable Module of the model.

Return: tf.Variable

Pointer to the input tokens Embeddings Module of the model

save_pretrained(save_directory)[source]

Save a model and its configuration file to a directory, so that it can be re-loaded using the from_pretrained() class method.