XLMΒΆ
OverviewΒΆ
The XLM model was proposed in Cross-lingual Language Model Pretraining by Guillaume Lample*, Alexis Conneau*. Itβs a transformer pre-trained using one of the following objectives:
a causal language modeling (CLM) objective (next token prediction),
a masked language modeling (MLM) objective (Bert-like), or
a Translation Language Modeling (TLM) object (extension of Bertβs MLM to multiple language inputs)
The abstract from the paper is the following:
Recent studies have demonstrated the efficiency of generative pretraining for English natural language understanding. In this work, we extend this approach to multiple languages and show the effectiveness of cross-lingual pretraining. We propose two methods to learn cross-lingual language models (XLMs): one unsupervised that only relies on monolingual data, and one supervised that leverages parallel data with a new cross-lingual language model objective. We obtain state-of-the-art results on cross-lingual classification, unsupervised and supervised machine translation. On XNLI, our approach pushes the state of the art by an absolute gain of 4.9% accuracy. On unsupervised machine translation, we obtain 34.3 BLEU on WMTβ16 German-English, improving the previous state of the art by more than 9 BLEU. On supervised machine translation, we obtain a new state of the art of 38.5 BLEU on WMTβ16 Romanian-English, outperforming the previous best approach by more than 4 BLEU. Our code and pretrained models will be made publicly available.
Tips:
XLM has many different checkpoints, which were trained using different objectives: CLM, MLM or TLM. Make sure to select the correct objective for your task (e.g. MLM checkpoints are not suitable for generation).
XLM has multilingual checkpoints which leverage a specific lang parameter. Check out the multi-lingual page for more information.
The original code can be found here.
XLMConfigΒΆ
-
class
transformers.
XLMConfig
(vocab_size=30145, emb_dim=2048, n_layers=12, n_heads=16, dropout=0.1, attention_dropout=0.1, gelu_activation=True, sinusoidal_embeddings=False, causal=False, asm=False, n_langs=1, use_lang_emb=True, max_position_embeddings=512, embed_init_std=0.02209708691207961, layer_norm_eps=1e-12, init_std=0.02, bos_index=0, eos_index=1, pad_index=2, unk_index=3, mask_index=5, is_encoder=True, summary_type='first', summary_use_proj=True, summary_activation=None, summary_proj_to_labels=True, summary_first_dropout=0.1, start_n_top=5, end_n_top=5, mask_token_id=0, lang_id=0, pad_token_id=2, bos_token_id=0, **kwargs)[source]ΒΆ This is the configuration class to store the configuration of a
XLMModel
. It is used to instantiate an XLM 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 xlm-mlm-en-2048 architecture.Configuration objects inherit from
PretrainedConfig
and can be used to control the model outputs. Read the documentation fromPretrainedConfig
for more information.- Parameters
vocab_size (
int
, optional, defaults to 30145) β Vocabulary size of the XLM model. Defines the different tokens that can be represented by the inputs_ids passed to the forward method ofXLMModel
.emb_dim (
int
, optional, defaults to 2048) β Dimensionality of the encoder layers and the pooler layer.n_layer (
int
, optional, defaults to 12) β Number of hidden layers in the Transformer encoder.n_head (
int
, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer encoder.dropout (
float
, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.attention_dropout (
float
, optional, defaults to 0.1) β The dropout probability for the attention mechanismgelu_activation (
boolean
, optional, defaults toTrue
) β The non-linear activation function (function or string) in the encoder and pooler. If set to True, βgeluβ will be used instead of βreluβ.sinusoidal_embeddings (
boolean
, optional, defaults toFalse
) β Whether to use sinusoidal positional embeddings instead of absolute positional embeddings.causal (
boolean
, optional, defaults toFalse
) β Set this to True for the model to behave in a causal manner. Causal models use a triangular attention mask in order to only attend to the left-side context instead if a bidirectional context.asm (
boolean
, optional, defaults toFalse
) β Whether to use an adaptive log softmax projection layer instead of a linear layer for the prediction layer.n_langs (
int
, optional, defaults to 1) β The number of languages the model handles. Set to 1 for monolingual models.use_lang_emb (
boolean
, optional, defaults toTrue
) β Whether to use language embeddings. Some models use additional language embeddings, see the multilingual models page for information on how to use them.max_position_embeddings (
int
, optional, defaults to 512) β The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).embed_init_std (
float
, optional, defaults to 2048^-0.5) β The standard deviation of the truncated_normal_initializer for initializing the embedding matrices.init_std (
int
, optional, defaults to 50257) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices except the embedding matrices.layer_norm_eps (
float
, optional, defaults to 1e-12) β The epsilon used by the layer normalization layers.bos_index (
int
, optional, defaults to 0) β The index of the beginning of sentence token in the vocabulary.eos_index (
int
, optional, defaults to 1) β The index of the end of sentence token in the vocabulary.pad_index (
int
, optional, defaults to 2) β The index of the padding token in the vocabulary.unk_index (
int
, optional, defaults to 3) β The index of the unknown token in the vocabulary.mask_index (
int
, optional, defaults to 5) β The index of the masking token in the vocabulary.is_encoder (
boolean
, optional, defaults toTrue
) β Whether the initialized model should be a transformer encoder or decoder as seen in Vaswani et al.summary_type (
string
, optional, defaults to βfirstβ) βArgument used when doing sequence summary. Used in for the multiple choice head in
XLMForSequenceClassification
. Is one of the following options:βlastβ => take the last token hidden state (like XLNet)
βfirstβ => take the first token hidden state (like Bert)
βmeanβ => take the mean of all tokens hidden states
βcls_indexβ => supply a Tensor of classification token position (GPT/GPT-2)
βattnβ => Not implemented now, use multi-head attention
summary_use_proj (
boolean
, optional, defaults toTrue
) β Argument used when doing sequence summary. Used in for the multiple choice head inXLMForSequenceClassification
. Add a projection after the vector extractionsummary_activation (
string
orNone
, optional) β Argument used when doing sequence summary. Used in for the multiple choice head inXLMForSequenceClassification
. βtanhβ => add a tanh activation to the output, Other => no activation.summary_proj_to_labels (
boolean
, optional, defaults toTrue
) β Argument used when doing sequence summary. Used in for the multiple choice head inXLMForSequenceClassification
. If True, the projection outputs to config.num_labels classes (otherwise to hidden_size). Default: False.summary_first_dropout (
float
, optional, defaults to 0.1) β Argument used when doing sequence summary. Used in for the multiple choice head inXLMForSequenceClassification
. Add a dropout before the projection and activationstart_n_top (
int
, optional, defaults to 5) β Used in the SQuAD evaluation script for XLM and XLNet.end_n_top (
int
, optional, defaults to 5) β Used in the SQuAD evaluation script for XLM and XLNet.mask_token_id (
int
, optional, defaults to 0) β Model agnostic parameter to identify masked tokens when generating text in an MLM context.lang_id (
int
, optional, defaults to 1) β The ID of the language used by the model. This parameter is used when generating text in a given language.
Example:
>>> from transformers import XLMConfig, XLMModel >>> # Initializing a XLM configuration >>> configuration = XLMConfig() >>> # Initializing a model from the configuration >>> model = XLMModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config
XLMTokenizerΒΆ
-
class
transformers.
XLMTokenizer
(vocab_file, merges_file, unk_token='<unk>', bos_token='<s>', sep_token='</s>', pad_token='<pad>', cls_token='</s>', mask_token='<special1>', additional_special_tokens=['<special0>', '<special1>', '<special2>', '<special3>', '<special4>', '<special5>', '<special6>', '<special7>', '<special8>', '<special9>'], lang2id=None, id2lang=None, do_lowercase_and_remove_accent=True, **kwargs)[source]ΒΆ BPE tokenizer for XLM
Moses preprocessing & tokenization for most supported languages
Language specific tokenization for Chinese (Jieba), Japanese (KyTea) and Thai (PyThaiNLP)
(optionally) lower case & normalize all inputs text
argument
special_tokens
and functionset_special_tokens
, can be used to add additional symbols (ex: β__classify__β) to a vocabularylang2id attribute maps the languages supported by the model with their ids if provided (automatically set for pretrained vocabularies)
id2lang attributes does reverse mapping if provided (automatically set for pretrained vocabularies)
This tokenizer inherits from
PreTrainedTokenizer
which contains most of the methods. Users should refer to the superclass for more information regarding methods.- Parameters
vocab_file (
string
) β Vocabulary file.merges_file (
string
) β Merges file.do_lower_case (
bool
, optional, defaults toTrue
) β Whether to lowercase the input when tokenizing.remove_space (
bool
, optional, defaults toTrue
) β Whether to strip the text when tokenizing (removing excess spaces before and after the string).keep_accents (
bool
, optional, defaults toFalse
) β Whether to keep accents when tokenizing.unk_token (
string
, 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.bos_token (
string
, optional, defaults to β<s>β) βThe beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
Note
When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the
cls_token
.sep_token (
string
, optional, defaults to β</s>β) β The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.pad_token (
string
, optional, defaults to β<pad>β) β The token used for padding, for example when batching sequences of different lengths.cls_token (
string
, optional, defaults to β</s>β) β The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.mask_token (
string
, optional, defaults to β<special1>β) β The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict.additional_special_tokens (
List[str]
, optional, defaults to["<special0>","<special1>","<special2>","<special3>","<special4>","<special5>","<special6>","<special7>","<special8>","<special9>"]
) β List of additional special tokens.lang2id (
Dict[str, int]
, optional) β Dictionary mapping languages string identifiers to their IDs.id2lang (
Dict[int, str
, optional) β Dictionary mapping language IDs to their string identifiers.do_lowercase_and_remove_accent (
bool
, optional, defaults toTrue
) β Whether to lowercase and remove accents when tokenizing.
-
build_inputs_with_special_tokens
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int][source]ΒΆ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A XLM sequence has the following format:
single sequence:
<s> X </s>
pair of sequences:
<s> A </s> B </s>
- Parameters
token_ids_0 (
List[int]
) β List of IDs to which the special tokens will be addedtoken_ids_1 (
List[int]
, optional) β Optional second list of IDs for sequence pairs.
- Returns
list of input IDs with the appropriate special tokens.
- Return type
List[int]
-
create_token_type_ids_from_sequences
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int][source]ΒΆ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An XLM sequence pair mask has the following format:
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence |
if token_ids_1 is None, only returns the first portion of the mask (0s).
- 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 of token type IDs according to the given sequence(s).
- Return type
List[int]
-
get_special_tokens_mask
(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int][source]ΒΆ Retrieves 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
methods.- 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 toFalse
) β Set to True if the token list is already formatted with special tokens for the model
- Returns
A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
- Return type
List[int]
XLM specific outputsΒΆ
-
class
transformers.modeling_xlm.
XLMForQuestionAnsweringOutput
(loss: Optional[torch.FloatTensor] = None, start_top_log_probs: Optional[torch.FloatTensor] = None, start_top_index: Optional[torch.LongTensor] = None, end_top_log_probs: Optional[torch.FloatTensor] = None, end_top_index: Optional[torch.LongTensor] = None, cls_logits: Optional[torch.FloatTensor] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Base class for outputs of question answering models using a
SquadHead
.- Parameters
loss (
torch.FloatTensor
of shape(1,)
, optional, returned if bothstart_positions
andend_positions
are provided) β Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.start_top_log_probs (
torch.FloatTensor
of shape(batch_size, config.start_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Log probabilities for the top config.start_n_top start token possibilities (beam-search).start_top_index (
torch.LongTensor
of shape(batch_size, config.start_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Indices for the top config.start_n_top start token possibilities (beam-search).end_top_log_probs (
torch.FloatTensor
of shape(batch_size, config.start_n_top * config.end_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Log probabilities for the topconfig.start_n_top * config.end_n_top
end token possibilities (beam-search).end_top_index (
torch.LongTensor
of shape(batch_size, config.start_n_top * config.end_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Indices for the topconfig.start_n_top * config.end_n_top
end token possibilities (beam-search).cls_logits (
torch.FloatTensor
of shape(batch_size,)
, optional, returned ifstart_positions
orend_positions
is not provided) β Log probabilities for theis_impossible
label of the answers.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) βTuple of
torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) βTuple of
torch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
XLMModelΒΆ
-
class
transformers.
XLMModel
(config)[source]ΒΆ The bare XLM Model transformer outputting raw hidden-states without any specific head on top.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMModel
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.
- Returns
A
BaseModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
BaseModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import XLMTokenizer, XLMModel >>> import torch >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMModel.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
XLMWithLMHeadModelΒΆ
-
class
transformers.
XLMWithLMHeadModel
(config)[source]ΒΆ The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMWithLMHeadModel
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can setlabels = input_ids
Indices are selected in[-100, 0, ..., config.vocab_size]
All labels set to-100
are ignored (masked), the loss is only computed for labels in[0, ..., config.vocab_size]
- Returns
A
MaskedLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Masked languaged modeling (MLM) loss.logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) β Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
MaskedLMOutput
ortuple(torch.FloatTensor)
Example:
>>> import torch >>> from transformers import XLMTokenizer, XLMWithLMHeadModel >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs, labels=inputs["input_ids"]) >>> loss = outputs.loss >>> logits = outputs.logits
XLMForSequenceClassificationΒΆ
-
class
transformers.
XLMForSequenceClassification
(config)[source]ΒΆ XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMForSequenceClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size,)
, optional) β Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]
. Ifconfig.num_labels == 1
a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1
a classification loss is computed (Cross-Entropy).
- Returns
A
SequenceClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensor
of shape(batch_size, config.num_labels)
) β Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
SequenceClassifierOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import XLMTokenizer, XLMForSequenceClassification >>> import torch >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMForSequenceClassification.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits
XLMForMultipleChoiceΒΆ
-
class
transformers.
XLMForMultipleChoice
(config, *inputs, **kwargs)[source]ΒΆ XLM Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMForMultipleChoice
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.Tensor
of shape(batch_size,)
, optional) β Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices]
where num_choices is the size of the second dimension of the input tensors. (see input_ids above)
- Returns
A
MultipleChoiceModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
torch.FloatTensor
of shape (1,), optional, returned whenlabels
is provided) β Classification loss.logits (
torch.FloatTensor
of shape(batch_size, num_choices)
) β num_choices is the second dimension of the input tensors. (see input_ids above).Classification scores (before SoftMax).
hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
MultipleChoiceModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import XLMTokenizer, XLMForMultipleChoice >>> import torch >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMForMultipleChoice.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> choice0 = "It is eaten with a fork and a knife." >>> choice1 = "It is eaten while held in the hand." >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1 >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='pt', padding=True) >>> outputs = model(**{k: v.unsqueeze(0) for k,v in encoding.items()}, labels=labels) # batch size is 1 >>> # the linear classifier still needs to be trained >>> loss = outputs.loss >>> logits = outputs.logits
XLMForTokenClassificationΒΆ
-
class
transformers.
XLMForTokenClassification
(config)[source]ΒΆ XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMForTokenClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1]
.
- Returns
A
TokenClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Classification loss.logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.num_labels)
) β Classification scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TokenClassifierOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import XLMTokenizer, XLMForTokenClassification >>> import torch >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMForTokenClassification.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> labels = torch.tensor([1] * inputs["input_ids"].size(1)).unsqueeze(0) # Batch size 1 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits
XLMForQuestionAnsweringSimpleΒΆ
-
class
transformers.
XLMForQuestionAnsweringSimple
(config)[source]ΒΆ XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits).
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMForQuestionAnsweringSimple
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) β Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) β Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
- Returns
A
QuestionAnsweringModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.start_logits (
torch.FloatTensor
of shape(batch_size, sequence_length,)
) β Span-start scores (before SoftMax).end_logits (
torch.FloatTensor
of shape(batch_size, sequence_length,)
) β Span-end scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
QuestionAnsweringModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import XLMTokenizer, XLMForQuestionAnsweringSimple >>> import torch >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMForQuestionAnsweringSimple.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> inputs = tokenizer(question, text, return_tensors='pt') >>> start_positions = torch.tensor([1]) >>> end_positions = torch.tensor([3]) >>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions) >>> loss = outputs.loss >>> start_scores = outputs.start_logits >>> end_scores = outputs.end_logits
XLMForQuestionAnsweringΒΆ
-
class
transformers.
XLMForQuestionAnswering
(config)[source]ΒΆ XLM Model with a beam-search span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits).
This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, is_impossible=None, cls_index=None, p_mask=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
XLMForQuestionAnswering
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β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.langs (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
torch.LongTensor
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, torch.FloatTensor]
, optional) β dictionary withtorch.FloatTensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) βIf set to
True
, the model will return aModelOutput
instead of a plain tuple.- start_positions (
torch.LongTensor
of shape(batch_size,)
, optional): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
- end_positions (
torch.LongTensor
of shape(batch_size,)
, optional): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
- is_impossible (
torch.LongTensor
of shape(batch_size,)
, optional): Labels whether a question has an answer or no answer (SQuAD 2.0)
- cls_index (
torch.LongTensor
of shape(batch_size,)
, optional): Labels for position (index) of the classification token to use as input for computing plausibility of the answer.
- p_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional): Optional mask of tokens which canβt be in answers (e.g. [CLS], [PAD], β¦). 1.0 means token should be masked. 0.0 mean token is not masked.
- start_positions (
- Returns
A
XLMForQuestionAnsweringOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned if bothstart_positions
andend_positions
are provided) β Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.start_top_log_probs (
torch.FloatTensor
of shape(batch_size, config.start_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Log probabilities for the top config.start_n_top start token possibilities (beam-search).start_top_index (
torch.LongTensor
of shape(batch_size, config.start_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Indices for the top config.start_n_top start token possibilities (beam-search).end_top_log_probs (
torch.FloatTensor
of shape(batch_size, config.start_n_top * config.end_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Log probabilities for the topconfig.start_n_top * config.end_n_top
end token possibilities (beam-search).end_top_index (
torch.LongTensor
of shape(batch_size, config.start_n_top * config.end_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) β Indices for the topconfig.start_n_top * config.end_n_top
end token possibilities (beam-search).cls_logits (
torch.FloatTensor
of shape(batch_size,)
, optional, returned ifstart_positions
orend_positions
is not provided) β Log probabilities for theis_impossible
label of the answers.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> from transformers import XLMTokenizer, XLMForQuestionAnswering >>> import torch >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = XLMForQuestionAnswering.from_pretrained('xlm-mlm-en-2048', return_dict=True) >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 >>> start_positions = torch.tensor([1]) >>> end_positions = torch.tensor([3]) >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) >>> loss = outputs.loss
- Return type
XLMForQuestionAnsweringOutput
ortuple(torch.FloatTensor)
TFXLMModelΒΆ
-
class
transformers.
TFXLMModel
(*args, **kwargs)[source]ΒΆ The bare XLM Model transformer outputing raw hidden-states without any specific head on top.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs, **kwargs)[source]ΒΆ The
TFXLMModel
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) β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.langs (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
tf.Tensor
orNumpy array
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, tf.Tensor]
, optional) β dictionary withtf.Tensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
tf.Tensor
orNumpy array
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.
- Returns
A
TFBaseModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple(tf.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TFBaseModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import XLMTokenizer, TFXLMModel >>> import tensorflow as tf >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = TFXLMModel.from_pretrained('xlm-mlm-en-2048') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> outputs = model(inputs) >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
TFXLMWithLMHeadModelΒΆ
-
class
transformers.
TFXLMWithLMHeadModel
(*args, **kwargs)[source]ΒΆ The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs, **kwargs)[source]ΒΆ The
TFXLMWithLMHeadModel
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) β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.langs (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
tf.Tensor
orNumpy array
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, tf.Tensor]
, optional) β dictionary withtf.Tensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
tf.Tensor
orNumpy array
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.
- Returns
A
TFXLMWithLMHeadModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.logits (
tf.Tensor
of shape(batch_size, sequence_length, config.vocab_size)
) β Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TFXLMWithLMHeadModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import XLMTokenizer, TFXLMWithLMHeadModel >>> import tensorflow as tf >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = TFXLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> outputs = model(inputs) >>> logits = outputs[0]
TFXLMForSequenceClassificationΒΆ
-
class
transformers.
TFXLMForSequenceClassification
(*args, **kwargs)[source]ΒΆ XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]ΒΆ The
TFXLMForSequenceClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) β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.langs (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
tf.Tensor
orNumpy array
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, tf.Tensor]
, optional) β dictionary withtf.Tensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
tf.Tensor
orNumpy array
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size,)
, optional) β Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]
. Ifconfig.num_labels == 1
a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1
a classification loss is computed (Cross-Entropy).
- Returns
A
TFSequenceClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) β Classification (or regression if config.num_labels==1) loss.logits (
tf.Tensor
of shape(batch_size, config.num_labels)
) β Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TFSequenceClassifierOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import XLMTokenizer, TFXLMForSequenceClassification >>> import tensorflow as tf >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = TFXLMForSequenceClassification.from_pretrained('xlm-mlm-en-2048') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> inputs["labels"] = tf.reshape(tf.constant(1), (-1, 1)) # Batch size 1 >>> outputs = model(inputs) >>> loss, logits = outputs[:2]
TFXLMForMultipleChoiceΒΆ
-
class
transformers.
TFXLMForMultipleChoice
(*args, **kwargs)[source]ΒΆ XLM Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]ΒΆ The
TFXLMForMultipleChoice
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) β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.langs (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
tf.Tensor
orNumpy array
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, tf.Tensor]
, optional) β dictionary withtf.Tensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
tf.Tensor
orNumpy array
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size,)
, optional) β Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices]
where num_choices is the size of the second dimension of the input tensors. (see input_ids above)
- Returns
A
TFMultipleChoiceModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
tf.Tensor
of shape (1,), optional, returned whenlabels
is provided) β Classification loss.logits (
tf.Tensor
of shape(batch_size, num_choices)
) β num_choices is the second dimension of the input tensors. (see input_ids above).Classification scores (before SoftMax).
hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TFMultipleChoiceModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import XLMTokenizer, TFXLMForMultipleChoice >>> import tensorflow as tf >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = TFXLMForMultipleChoice.from_pretrained('xlm-mlm-en-2048') >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> choice0 = "It is eaten with a fork and a knife." >>> choice1 = "It is eaten while held in the hand." >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='tf', padding=True) >>> inputs = {k: tf.expand_dims(v, 0) for k, v in encoding.items()} >>> outputs = model(inputs) # batch size is 1 >>> # the linear classifier still needs to be trained >>> logits = outputs[0]
-
property
dummy_inputs
ΒΆ Dummy inputs to build the network.
- Returns
tf.Tensor with dummy inputs
TFXLMForTokenClassificationΒΆ
-
class
transformers.
TFXLMForTokenClassification
(*args, **kwargs)[source]ΒΆ XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]ΒΆ The
TFXLMForTokenClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) β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.langs (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
tf.Tensor
orNumpy array
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, tf.Tensor]
, optional) β dictionary withtf.Tensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
tf.Tensor
orNumpy array
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) β Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1]
.
- Returns
A
TFTokenClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) β Classification loss.logits (
tf.Tensor
of shape(batch_size, sequence_length, config.num_labels)
) β Classification scores (before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TFTokenClassifierOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import XLMTokenizer, TFXLMForTokenClassification >>> import tensorflow as tf >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = TFXLMForTokenClassification.from_pretrained('xlm-mlm-en-2048') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> input_ids = inputs["input_ids"] >>> inputs["labels"] = tf.reshape(tf.constant([1] * tf.size(input_ids).numpy()), (-1, tf.size(input_ids))) # Batch size 1 >>> outputs = model(inputs) >>> loss, scores = outputs[:2]
TFXLMForQuestionAnsweringSimpleΒΆ
-
class
transformers.
TFXLMForQuestionAnsweringSimple
(*args, **kwargs)[source]ΒΆ XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits).
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
ormodel([input_ids, attention_mask, token_type_ids])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids, 'token_type_ids': token_type_ids})
- Parameters
config (
XLMConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, start_positions=None, end_positions=None, training=False)[source]ΒΆ The
TFXLMForQuestionAnsweringSimple
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) β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.langs (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βA parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are languages ids which can be obtained from the language names by using two conversion mappings provided in the configuration of the model (only provided for multilingual models). More precisely, the language name -> language id mapping is in model.config.lang2id (dict str -> int) and the language id -> language name mapping is model.config.id2lang (dict int -> str).
See usage examples detailed in the multilingual documentation.
token_type_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0
corresponds to a sentence A token,1
corresponds to a sentence B tokenposition_ids (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length)
, optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1]
.lengths (
tf.Tensor
orNumpy array
of shape(batch_size,)
, optional) β Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in[0, ..., input_ids.size(-1)]
:cache (
Dict[str, tf.Tensor]
, optional) β dictionary withtf.Tensor
that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.head_mask (
tf.Tensor
orNumpy array
of shape(num_heads,)
or(num_layers, num_heads)
, optional) β Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
tf.Tensor
orNumpy array
of shape(batch_size, sequence_length, hidden_size)
, optional) β Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β If set toTrue
, the model will return aModelOutput
instead of a plain tuple.start_positions (
tf.Tensor
of shape(batch_size,)
, optional) β Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.end_positions (
tf.Tensor
of shape(batch_size,)
, optional) β Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.
- Returns
A
TFQuestionAnsweringModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (XLMConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) β Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.start_logits (
tf.Tensor
of shape(batch_size, sequence_length,)
) β Span-start scores (before SoftMax).end_logits (
tf.Tensor
of shape(batch_size, sequence_length,)
) β Span-end scores (before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
- Return type
TFQuestionAnsweringModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import XLMTokenizer, TFXLMForQuestionAnsweringSimple >>> import tensorflow as tf >>> tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048') >>> model = TFXLMForQuestionAnsweringSimple.from_pretrained('xlm-mlm-en-2048') >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> input_dict = tokenizer(question, text, return_tensors='tf') >>> start_scores, end_scores = model(input_dict) >>> all_tokens = tokenizer.convert_ids_to_tokens(input_dict["input_ids"].numpy()[0]) >>> answer = ' '.join(all_tokens[tf.math.argmax(start_scores, 1)[0] : tf.math.argmax(end_scores, 1)[0]+1])