XLM-RoBERTaΒΆ
OverviewΒΆ
The XLM-RoBERTa model was proposed in Unsupervised Cross-lingual Representation Learning at Scale by Alexis Conneau, Kartikay Khandelwal, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco GuzmΓ‘n, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov. It is based on Facebookβs RoBERTa model released in 2019. It is a large multi-lingual language model, trained on 2.5TB of filtered CommonCrawl data.
The abstract from the paper is the following:
This paper shows that pretraining multilingual language models at scale leads to significant performance gains for a wide range of cross-lingual transfer tasks. We train a Transformer-based masked language model on one hundred languages, using more than two terabytes of filtered CommonCrawl data. Our model, dubbed XLM-R, significantly outperforms multilingual BERT (mBERT) on a variety of cross-lingual benchmarks, including +13.8% average accuracy on XNLI, +12.3% average F1 score on MLQA, and +2.1% average F1 score on NER. XLM-R performs particularly well on low-resource languages, improving 11.8% in XNLI accuracy for Swahili and 9.2% for Urdu over the previous XLM model. We also present a detailed empirical evaluation of the key factors that are required to achieve these gains, including the trade-offs between (1) positive transfer and capacity dilution and (2) the performance of high and low resource languages at scale. Finally, we show, for the first time, the possibility of multilingual modeling without sacrificing per-language performance; XLM-Ris very competitive with strong monolingual models on the GLUE and XNLI benchmarks. We will make XLM-R code, data, and models publicly available.
Tips:
XLM-RoBERTa is a multilingual model trained on 100 different languages. Unlike some XLM multilingual models, it does not require
lang
tensors to understand which language is used, and should be able to determine the correct language from the input ids.This implementation is the same as RoBERTa. Refer to the documentation of RoBERTa for usage examples as well as the information relative to the inputs and outputs.
The original code can be found here.
XLMRobertaConfigΒΆ
-
class
transformers.
XLMRobertaConfig
(pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs)[source]ΒΆ This class overrides
RobertaConfig
. Please check the superclass for the appropriate documentation alongside usage examples.
XLMRobertaTokenizerΒΆ
-
class
transformers.
XLMRobertaTokenizer
(vocab_file, bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_token='<s>', unk_token='<unk>', pad_token='<pad>', mask_token='<mask>', **kwargs)[source]ΒΆ Adapted from
RobertaTokenizer
and class:~transformers.XLNetTokenizer. Based on SentencePiece.This tokenizer inherits from
PreTrainedTokenizer
which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.- Parameters
vocab_file (
str
) β Path to the vocabulary file.bos_token (
str
, optional, defaults to"<s>"
) βThe beginning of sequence token that was used during pretraining. 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
.eos_token (
str
, optional, defaults to"</s>"
) βThe end of sequence token.
Note
When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the
sep_token
.sep_token (
str
, 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.cls_token (
str
, 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.unk_token (
str
, optional, defaults to"<unk>"
) β The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.pad_token (
str
, optional, defaults to"<pad>"
) β The token used for padding, for example when batching sequences of different lengths.mask_token (
str
, optional, defaults to"<mask>"
) β 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["<s>NOTUSED", "</s>NOTUSED"]
) β Additional special tokens used by the tokenizer.
Attributes: sp_model (
SentencePieceProcessor
): The SentencePiece processor that is used for every conversion (string, tokens and IDs).-
build_inputs_with_special_tokens
(token_ids_0: 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. An XLM-RoBERTa sequence has the following format:
single sequence:
<s> X </s>
pair of sequences:
<s> A </s></s> B </s>
- Parameters
token_ids_0 (
List[int]
) β List of IDs to which the special tokens will be added.token_ids_1 (
List[int]
, optional) β Optional second list of IDs for sequence pairs.
- Returns
List 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]ΒΆ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does not make use of token type ids, therefore a list of zeros is returned.
- 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 zeros.
- 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]ΒΆ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer
prepare_for_model
method.- 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
) β Whether or not 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]
-
save_vocabulary
(save_directory: str, filename_prefix: Optional[str] = None) → Tuple[str][source]ΒΆ Save only the vocabulary of the tokenizer (vocabulary + added tokens).
This method wonβt save the configuration and special token mappings of the tokenizer. Use
_save_pretrained()
to save the whole state of the tokenizer.- Parameters
save_directory (
str
) β The directory in which to save the vocabulary.filename_prefix (
str
, optional) β An optional prefix to add to the named of the saved files.
- Returns
Paths to the files saved.
- Return type
Tuple(str)
XLMRobertaModelΒΆ
-
class
transformers.
XLMRobertaModel
(config, add_pooling_layer=True)[source]ΒΆ The bare XLM-RoBERTa Model transformer outputting raw hidden-states without any specific head on top.
This model inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaModel
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaModel
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
RobertaTokenizer
. 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 tokens that are masked.
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 token.
position_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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.encoder_hidden_states (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder.encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) β Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.
- Returns
A
BaseModelOutputWithPoolingAndCrossAttentions
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (RobertaConfig
) 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.pooler_output (
torch.FloatTensor
of shape(batch_size, hidden_size)
) β Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.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.
cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
andconfig.add_cross_attention=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 of the decoderβs cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
- Return type
BaseModelOutputWithPoolingAndCrossAttentions
ortuple(torch.FloatTensor)
Example:
>>> from transformers import RobertaTokenizer, RobertaModel >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = RobertaModel.from_pretrained('roberta-base') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
XLMRobertaForCausalLMΒΆ
-
class
transformers.
XLMRobertaForCausalLM
(config)[source]ΒΆ XLM-RoBERTa Model with a language modeling head on top for CLM fine-tuning.
This model inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaForCausalLM
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaForCausalLM
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
RobertaTokenizer
. 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 tokens that are masked.
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 token.
position_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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.encoder_hidden_states (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) β Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder.encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) βMask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in
[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in[-100, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
- Returns
A
CausalLMOutputWithCrossAttentions
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (RobertaConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Language modeling loss (for next-token prediction).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.
cross_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)
.Cross attentions weights after the attention softmax, used to compute the weighted average in the cross-attention heads.
Example:
>>> from transformers import RobertaTokenizer, RobertaForCausalLM, RobertaConfig >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> config = RobertaConfig.from_pretrained("roberta-base") >>> config.is_decoder = True >>> model = RobertaForCausalLM.from_pretrained('roberta-base', config=config) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> prediction_logits = outputs.logits
- Return type
CausalLMOutputWithCrossAttentions
ortuple(torch.FloatTensor)
XLMRobertaForMaskedLMΒΆ
-
class
transformers.
XLMRobertaForMaskedLM
(config)[source]ΒΆ XLM-RoBERTa Model with a language modeling head on top.
This model inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaForMaskedLM
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaForMaskedLM
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
RobertaTokenizer
. 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 tokens that are masked.
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 token.
position_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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β Labels for computing the masked language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
kwargs (
Dict[str, any]
, optional, defaults to {}) β Used to hide legacy arguments that have been deprecated.
- 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 (RobertaConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) β Masked language 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:
>>> from transformers import RobertaTokenizer, RobertaForMaskedLM >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = RobertaForMaskedLM.from_pretrained('roberta-base') >>> inputs = tokenizer("The capital of France is <mask>.", return_tensors="pt") >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"] >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits
XLMRobertaForSequenceClassificationΒΆ
-
class
transformers.
XLMRobertaForSequenceClassification
(config)[source]ΒΆ XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
This model inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaForSequenceClassification
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaForSequenceClassification
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
RobertaTokenizer
. 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 tokens that are masked.
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 token.
position_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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to 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 (RobertaConfig
) 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 RobertaTokenizer, RobertaForSequenceClassification >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = RobertaForSequenceClassification.from_pretrained('roberta-base') >>> 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
XLMRobertaForMultipleChoiceΒΆ
-
class
transformers.
XLMRobertaForMultipleChoice
(config)[source]ΒΆ XLM-RoBERTa 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 inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaForMultipleChoice
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, token_type_ids=None, attention_mask=None, labels=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaForMultipleChoice
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, num_choices, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, num_choices, 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 tokens that are masked.
token_type_ids (
torch.LongTensor
of shape(batch_size, num_choices, 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 token.
position_ids (
torch.LongTensor
of shape(batch_size, num_choices, 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]
.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, num_choices, 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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size,)
, optional) β Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices-1]
wherenum_choices
is the size of the second dimension of the input tensors. (Seeinput_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 (RobertaConfig
) 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 RobertaTokenizer, RobertaForMultipleChoice >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = RobertaForMultipleChoice.from_pretrained('roberta-base') >>> 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
XLMRobertaForTokenClassificationΒΆ
-
class
transformers.
XLMRobertaForTokenClassification
(config)[source]ΒΆ XLM-RoBERTa 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 inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaForTokenClassification
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaForTokenClassification
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
RobertaTokenizer
. 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 tokens that are masked.
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 token.
position_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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to 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 (RobertaConfig
) 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 RobertaTokenizer, RobertaForTokenClassification >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = RobertaForTokenClassification.from_pretrained('roberta-base') >>> 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
XLMRobertaForQuestionAnsweringΒΆ
-
class
transformers.
XLMRobertaForQuestionAnswering
(config)[source]ΒΆ XLM-RoBERTa 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 inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
XLMRobertaConfig
) β 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.
This class overrides
RobertaForQuestionAnswering
. Please check the superclass for the appropriate documentation alongside usage examples.-
forward
(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None)ΒΆ The
RobertaForQuestionAnswering
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
RobertaTokenizer
. 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 tokens that are masked.
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 token.
position_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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to 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 (RobertaConfig
) 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 RobertaTokenizer, RobertaForQuestionAnswering >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = RobertaForQuestionAnswering.from_pretrained('roberta-base') >>> 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
TFXLMRobertaModelΒΆ
-
class
transformers.
TFXLMRobertaModel
(*args, **kwargs)[source]ΒΆ The bare XLM-RoBERTa Model transformer outputting raw hidden-states without any specific head on top.
This model inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
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 (
XLMRobertaConfig
) β 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.
This class overrides
TFRobertaModel
. Please check the superclass for the appropriate documentation alongside usage examples.-
call
(inputs, **kwargs)ΒΆ The
TFRobertaModel
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 (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.__call__()
andtransformers.PreTrainedTokenizer.encode()
for details.attention_mask (
Numpy array
ortf.Tensor
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 tokens that are masked.
token_type_ids (
Numpy array
ortf.Tensor
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 token.
position_ids (
Numpy array
ortf.Tensor
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]
.head_mask (
Numpy array
ortf.Tensor
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
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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.training (
bool
, optional, defaults toFalse
) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
- Returns
A
TFBaseModelOutputWithPooling
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (RobertaConfig
) 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.pooler_output (
tf.Tensor
of shape(batch_size, hidden_size)
) β Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.This output is usually not a good summary of the semantic content of the input, youβre often better with averaging or pooling the sequence of hidden-states for the whole input sequence.
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
TFBaseModelOutputWithPooling
ortuple(tf.Tensor)
Example:
>>> from transformers import RobertaTokenizer, TFRobertaModel >>> import tensorflow as tf >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = TFRobertaModel.from_pretrained('roberta-base') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> outputs = model(inputs) >>> last_hidden_states = outputs.last_hidden_states
TFXLMRobertaForMaskedLMΒΆ
-
class
transformers.
TFXLMRobertaForMaskedLM
(*args, **kwargs)[source]ΒΆ XLM-RoBERTa Model with a language modeling head on top.
This model inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
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 (
XLMRobertaConfig
) β 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.
This class overrides
TFRobertaForMaskedLM
. Please check the superclass for the appropriate documentation alongside usage examples.-
call
(inputs=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)ΒΆ The
TFRobertaForMaskedLM
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 (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.__call__()
andtransformers.PreTrainedTokenizer.encode()
for details.attention_mask (
Numpy array
ortf.Tensor
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 tokens that are masked.
token_type_ids (
Numpy array
ortf.Tensor
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 token.
position_ids (
Numpy array
ortf.Tensor
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]
.head_mask (
Numpy array
ortf.Tensor
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
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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.training (
bool
, optional, defaults toFalse
) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).labels (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) β Labels for computing the masked language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
- Returns
A
TFMaskedLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (RobertaConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) β Masked language modeling (MLM) loss.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
TFMaskedLMOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import RobertaTokenizer, TFRobertaForMaskedLM >>> import tensorflow as tf >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = TFRobertaForMaskedLM.from_pretrained('roberta-base') >>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="tf") >>> inputs["labels"] = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"] >>> outputs = model(inputs) >>> loss = outputs.loss >>> logits = outputs.logits
TFXLMRobertaForSequenceClassificationΒΆ
-
class
transformers.
TFXLMRobertaForSequenceClassification
(*args, **kwargs)[source]ΒΆ XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
This model inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
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 (
XLMRobertaConfig
) β 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.
This class overrides
TFRobertaForSequenceClassification
. Please check the superclass for the appropriate documentation alongside usage examples.-
call
(inputs=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)ΒΆ The
TFRobertaForSequenceClassification
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 (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.__call__()
andtransformers.PreTrainedTokenizer.encode()
for details.attention_mask (
Numpy array
ortf.Tensor
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 tokens that are masked.
token_type_ids (
Numpy array
ortf.Tensor
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 token.
position_ids (
Numpy array
ortf.Tensor
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]
.head_mask (
Numpy array
ortf.Tensor
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
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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.training (
bool
, optional, defaults toFalse
) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).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 (RobertaConfig
) 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 RobertaTokenizer, TFRobertaForSequenceClassification >>> import tensorflow as tf >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = TFRobertaForSequenceClassification.from_pretrained('roberta-base') >>> 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 = outputs.loss >>> logits = outputs.logits
TFXLMRobertaForMultipleChoiceΒΆ
-
class
transformers.
TFXLMRobertaForMultipleChoice
(*args, **kwargs)[source]ΒΆ Roberta 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 inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
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 (
XLMRobertaConfig
) β 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.
This class overrides
TFRobertaForMultipleChoice
. Please check the superclass for the appropriate documentation alongside usage examples.-
call
(inputs, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)ΒΆ The
TFRobertaForMultipleChoice
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 (
Numpy array
ortf.Tensor
of shape(batch_size, num_choices, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.__call__()
andtransformers.PreTrainedTokenizer.encode()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, num_choices, 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 tokens that are masked.
token_type_ids (
Numpy array
ortf.Tensor
of shape(batch_size, num_choices, 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 token.
position_ids (
Numpy array
ortf.Tensor
of shape(batch_size, num_choices, 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]
.head_mask (
Numpy array
ortf.Tensor
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
of shape(batch_size, num_choices, 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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.training (
bool
, optional, defaults toFalse
) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).labels (
tf.Tensor
of shape(batch_size,)
, optional) β Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices]
wherenum_choices
is the size of the second dimension of the input tensors. (Seeinput_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 (RobertaConfig
) 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 RobertaTokenizer, TFRobertaForMultipleChoice >>> import tensorflow as tf >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = TFRobertaForMultipleChoice.from_pretrained('roberta-base') >>> 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.logits
TFXLMRobertaForTokenClassificationΒΆ
-
class
transformers.
TFXLMRobertaForTokenClassification
(*args, **kwargs)[source]ΒΆ XLM-RoBERTa 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 inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
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 (
XLMRobertaConfig
) β 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.
This class overrides
TFRobertaForTokenClassification
. Please check the superclass for the appropriate documentation alongside usage examples.-
call
(inputs=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)ΒΆ The
TFRobertaForTokenClassification
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 (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.__call__()
andtransformers.PreTrainedTokenizer.encode()
for details.attention_mask (
Numpy array
ortf.Tensor
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 tokens that are masked.
token_type_ids (
Numpy array
ortf.Tensor
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 token.
position_ids (
Numpy array
ortf.Tensor
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]
.head_mask (
Numpy array
ortf.Tensor
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
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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.training (
bool
, optional, defaults toFalse
) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).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 (RobertaConfig
) 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 RobertaTokenizer, TFRobertaForTokenClassification >>> import tensorflow as tf >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = TFRobertaForTokenClassification.from_pretrained('roberta-base') >>> 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 = outputs.loss >>> logits = outputs.logits
TFXLMRobertaForQuestionAnsweringΒΆ
-
class
transformers.
TFXLMRobertaForQuestionAnswering
(*args, **kwargs)[source]ΒΆ XLM-RoBERTa 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 inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
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 (
XLMRobertaConfig
): 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 the
from_pretrained()
method to load the model weights.
- config (
This class overrides
TFRobertaForQuestionAnsweringSimple
. Please check the superclass for the appropriate documentation alongside usage examples.-
call
(inputs=None, attention_mask=None, token_type_ids=None, position_ids=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)ΒΆ The
TFRobertaForQuestionAnswering
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 (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer
. Seetransformers.PreTrainedTokenizer.__call__()
andtransformers.PreTrainedTokenizer.encode()
for details.attention_mask (
Numpy array
ortf.Tensor
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 tokens that are masked.
token_type_ids (
Numpy array
ortf.Tensor
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 token.
position_ids (
Numpy array
ortf.Tensor
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]
.head_mask (
Numpy array
ortf.Tensor
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
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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.training (
bool
, optional, defaults toFalse
) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).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 (RobertaConfig
) 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 RobertaTokenizer, TFRobertaForQuestionAnswering >>> import tensorflow as tf >>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base') >>> model = TFRobertaForQuestionAnswering.from_pretrained('roberta-base') >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> input_dict = tokenizer(question, text, return_tensors='tf') >>> outputs = model(input_dict) >>> start_logits = outputs.start_logits >>> end_logits = outputs.end_logits >>> all_tokens = tokenizer.convert_ids_to_tokens(input_dict["input_ids"].numpy()[0]) >>> answer = ' '.join(all_tokens[tf.math.argmax(start_logits, 1)[0] : tf.math.argmax(end_logits, 1)[0]+1])