Transformers documentation

mT5

You are viewing v4.15.0 version. A newer version v4.46.2 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

mT5

Overview

The mT5 model was presented in mT5: A massively multilingual pre-trained text-to-text transformer by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.

The abstract from the paper is the following:

The recent β€œText-to-Text Transfer Transformer” (T5) leveraged a unified text-to-text format and scale to attain state-of-the-art results on a wide variety of English-language NLP tasks. In this paper, we introduce mT5, a multilingual variant of T5 that was pre-trained on a new Common Crawl-based dataset covering 101 languages. We detail the design and modified training of mT5 and demonstrate its state-of-the-art performance on many multilingual benchmarks. We also describe a simple technique to prevent β€œaccidental translation” in the zero-shot setting, where a generative model chooses to (partially) translate its prediction into the wrong language. All of the code and model checkpoints used in this work are publicly available.

Note: mT5 was only pre-trained on mC4 excluding any supervised training. Therefore, this model has to be fine-tuned before it is useable on a downstream task, unlike the original T5 model. Since mT5 was pre-trained unsupervisedly, there’s no real advantage to using a task prefix during single-task fine-tuning. If you are doing multi-task fine-tuning, you should use a prefix.

Google has released the following variants:

This model was contributed by patrickvonplaten. The original code can be found here.

MT5Config

class transformers.MT5Config < >

( vocab_size = 250112 d_model = 512 d_kv = 64 d_ff = 1024 num_layers = 8 num_decoder_layers = None num_heads = 6 relative_attention_num_buckets = 32 dropout_rate = 0.1 layer_norm_epsilon = 1e-06 initializer_factor = 1.0 feed_forward_proj = 'gated-gelu' is_encoder_decoder = True use_cache = True tokenizer_class = 'T5Tokenizer' tie_word_embeddings = False pad_token_id = 0 eos_token_id = 1 decoder_start_token_id = 0 **kwargs )

Parameters

  • vocab_size (int, optional, defaults to 250112) — Vocabulary size of the T5 model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling T5Model or TFT5Model.
  • d_model (int, optional, defaults to 512) — Size of the encoder layers and the pooler layer.
  • d_kv (int, optional, defaults to 64) — Size of the key, query, value projections per attention head. d_kv has to be equal to d_model // num_heads.
  • d_ff (int, optional, defaults to 1024) — Size of the intermediate feed forward layer in each T5Block.
  • num_layers (int, optional, defaults to 8) — Number of hidden layers in the Transformer encoder.
  • num_decoder_layers (int, optional) — Number of hidden layers in the Transformer decoder. Will use the same value as num_layers if not set.
  • num_heads (int, optional, defaults to 6) — Number of attention heads for each attention layer in the Transformer encoder.
  • relative_attention_num_buckets (int, optional, defaults to 32) — The number of buckets to use for each attention layer.
  • dropout_rate (float, optional, defaults to 0.1) — The ratio for all dropout layers.
  • layer_norm_eps (float, optional, defaults to 1e-6) — The epsilon used by the layer normalization layers.
  • initializer_factor (float, optional, defaults to 1) — A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing).
  • feed_forward_proj (string, optional, defaults to "gated-gelu") — Type of feed forward layer to be used. Should be one of "relu" or "gated-gelu".
  • use_cache (bool, optional, defaults to True) — Whether or not the model should return the last key/values attentions (not used by all models).

This is the configuration class to store the configuration of a MT5Model or a TFMT5Model. It is used to instantiate a mT5 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the mT5 google/mt5-small architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

MT5Tokenizer

class transformers.T5Tokenizer < >

( vocab_file eos_token = '</s>' unk_token = '<unk>' pad_token = '<pad>' extra_ids = 100 additional_special_tokens = None sp_model_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = None **kwargs )

Parameters

  • vocab_file (str) — SentencePiece file (generally has a .spm extension) that contains the vocabulary necessary to instantiate a tokenizer.
  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the sep_token.

  • unk_token (str, optional, defaults to "<unk>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.
  • pad_token (str, optional, defaults to "<pad>") — The token used for padding, for example when batching sequences of different lengths.
  • extra_ids (int, optional, defaults to 100) — Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are accessible as “id{%d}>” where ”{%d}” is a number between 0 and extra_ids-1. Extra tokens are indexed from the end of the vocabulary up to beginning (“” is the last token in the vocabulary like in T5 preprocessing see here).
  • additional_special_tokens (List[str], optional) — Additional special tokens used by the tokenizer.
  • sp_model_kwargs (dict, optional) — Will be passed to the SentencePieceProcessor.__init__() method. The Python wrapper for SentencePiece can be used, among other things, to set:

    • enable_sampling: Enable subword regularization.

    • nbest_size: Sampling parameters for unigram. Invalid for BPE-Dropout.

      • nbest_size = {0,1}: No sampling is performed.
      • nbest_size > 1: samples from the nbest_size results.
      • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
    • alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.

Construct a T5 tokenizer. Based on SentencePiece.

This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

Attributes: sp_model (SentencePieceProcessor): The SentencePiece processor that is used for every conversion (string, tokens and IDs).

build_inputs_with_special_tokens < >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) β†’ List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs to which the special tokens will be added.
  • token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs.

Returns

List[int]

List of input IDs with the appropriate special tokens.

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A sequence has the following format:

  • single sequence: X </s>
  • pair of sequences: A </s> B </s>
convert_tokens_to_string < >

( tokens )

Converts a sequence of tokens (string) in a single string.

create_token_type_ids_from_sequences < >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) β†’ List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs.
  • token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs.

Returns

List[int]

List of zeros.

Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make use of token type ids, therefore a list of zeros is returned.

get_special_tokens_mask < >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) β†’ List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs.
  • token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs.
  • already_has_special_tokens (bool, optional, defaults to False) — Whether or not the token list is already formatted with special tokens for the model.

Returns

List[int]

A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.

Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model method.

See T5Tokenizer for all details.

MT5TokenizerFast

class transformers.T5TokenizerFast < >

( vocab_file = None tokenizer_file = None eos_token = '</s>' unk_token = '<unk>' pad_token = '<pad>' extra_ids = 100 additional_special_tokens = None **kwargs )

Parameters

  • vocab_file (str) — SentencePiece file (generally has a .spm extension) that contains the vocabulary necessary to instantiate a tokenizer.
  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the sep_token.

  • unk_token (str, optional, defaults to "<unk>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.
  • pad_token (str, optional, defaults to "<pad>") — The token used for padding, for example when batching sequences of different lengths.
  • extra_ids (int, optional, defaults to 100) — Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are accessible as “id{%d}>” where ”{%d}” is a number between 0 and extra_ids-1. Extra tokens are indexed from the end of the vocabulary up to beginning (“” is the last token in the vocabulary like in T5 preprocessing see here).
  • additional_special_tokens (List[str], optional) — Additional special tokens used by the tokenizer.

Construct a β€œfast” T5 tokenizer (backed by HuggingFace’s tokenizers library). Based on Unigram.

This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

build_inputs_with_special_tokens < >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) β†’ List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs to which the special tokens will be added.
  • token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs.

Returns

List[int]

List of input IDs with the appropriate special tokens.

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A sequence has the following format:

  • single sequence: X </s>
  • pair of sequences: A </s> B </s>
create_token_type_ids_from_sequences < >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) β†’ List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs.
  • token_ids_1 (List[int], optional) — Optional second list of IDs for sequence pairs.

Returns

List[int]

List of zeros.

Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make use of token type ids, therefore a list of zeros is returned.

See T5TokenizerFast for all details.

MT5Model

class transformers.MT5Model < >

( config: T5Config )

This class overrides T5Model. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import MT5Model, T5Tokenizer
>>> model = MT5Model.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> summary = "Weiter Verhandlung in Syrien."
>>> inputs = tokenizer(article, return_tensors="pt")
>>> with tokenizer.as_target_tokenizer():
...     labels = tokenizer(summary, return_tensors="pt")

>>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
>>> hidden_states = outputs.last_hidden_state

MT5ForConditionalGeneration

class transformers.MT5ForConditionalGeneration < >

( config )

This class overrides T5ForConditionalGeneration. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import MT5ForConditionalGeneration, T5Tokenizer
>>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> summary = "Weiter Verhandlung in Syrien."
>>> inputs = tokenizer(article, return_tensors="pt")
>>> with tokenizer.as_target_tokenizer():
...     labels = tokenizer(summary, return_tensors="pt")

>>> outputs = model(**inputs,labels=labels["input_ids"])
>>> loss = outputs.loss

MT5EncoderModel

class transformers.MT5EncoderModel < >

( config: T5Config )

This class overrides T5EncoderModel. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import MT5EncoderModel, T5Tokenizer
>>> model = MT5EncoderModel.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> input_ids = tokenizer(article, return_tensors="pt").input_ids
>>> outputs = model(input_ids)
>>> hidden_state = outputs.last_hidden_state

TFMT5Model

class transformers.TFMT5Model < >

( *args **kwargs )

This class overrides TFT5Model. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import TFMT5Model, T5Tokenizer
>>> model = TFMT5Model.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> summary = "Weiter Verhandlung in Syrien."
>>> inputs = tokenizer(article, return_tensors="tf")
>>> with tokenizer.as_target_tokenizer():
...     labels = tokenizer(summary, return_tensors="tf")

>>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
>>> hidden_states = outputs.last_hidden_state

TFMT5ForConditionalGeneration

class transformers.TFMT5ForConditionalGeneration < >

( *args **kwargs )

This class overrides TFT5ForConditionalGeneration. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import TFMT5ForConditionalGeneration, T5Tokenizer
>>> model = TFMT5ForConditionalGeneration.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> summary = "Weiter Verhandlung in Syrien."
>>> inputs = tokenizer(article, return_tensors="tf")
>>> with tokenizer.as_target_tokenizer():
...     labels = tokenizer(summary, return_tensors="tf")

>>> outputs = model(**inputs,labels=labels["input_ids"])
>>> loss = outputs.loss

TFMT5EncoderModel

class transformers.TFMT5EncoderModel < >

( *args **kwargs )

This class overrides TFT5EncoderModel. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import TFMT5EncoderModel, T5Tokenizer
>>> model = TFMT5EncoderModel.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")
>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> input_ids = tokenizer(article, return_tensors="tf").input_ids
>>> outputs = model(input_ids)
>>> hidden_state = outputs.last_hidden_state

FlaxMT5Model

class transformers.FlaxMT5Model < >

( config: T5Config input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = <class 'jax._src.numpy.lax_numpy.float32'> **kwargs )

This class overrides FlaxT5Model. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import FlaxMT5Model, T5Tokenizer

>>> model = FlaxMT5Model.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")

>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> summary = "Weiter Verhandlung in Syrien."
>>> inputs = tokenizer(article, return_tensors="np")

>>> with tokenizer.as_target_tokenizer():
...     decoder_input_ids = tokenizer(summary, return_tensors="np").input_ids

>>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=decoder_input_ids)
>>> hidden_states = outputs.last_hidden_state

FlaxMT5ForConditionalGeneration

class transformers.FlaxMT5ForConditionalGeneration < >

( config: T5Config input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = <class 'jax._src.numpy.lax_numpy.float32'> **kwargs )

This class overrides FlaxT5ForConditionalGeneration. Please check the superclass for the appropriate documentation alongside usage examples.

Examples:

>>> from transformers import FlaxMT5ForConditionalGeneration, T5Tokenizer

>>> model = FlaxMT5ForConditionalGeneration.from_pretrained("google/mt5-small")
>>> tokenizer = T5Tokenizer.from_pretrained("google/mt5-small")

>>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
>>> summary = "Weiter Verhandlung in Syrien."
>>> inputs = tokenizer(article, return_tensors="np")

>>> with tokenizer.as_target_tokenizer():
...     decoder_input_ids = tokenizer(summary, return_tensors="np").input_ids

>>> outputs = model(**inputs, decoder_input_ids=decoder_input_ids)
>>> logits = outputs.logits