XLNetΒΆ
OverviewΒΆ
The XLNet model was proposed in XLNet: Generalized Autoregressive Pretraining for Language Understanding by Zhilin Yang, Zihang Dai, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le. XLnet is an extension of the Transformer-XL model pre-trained using an autoregressive method to learn bidirectional contexts by maximizing the expected likelihood over all permutations of the input sequence factorization order.
The abstract from the paper is the following:
With the capability of modeling bidirectional contexts, denoising autoencoding based pretraining like BERT achieves better performance than pretraining approaches based on autoregressive language modeling. However, relying on corrupting the input with masks, BERT neglects dependency between the masked positions and suffers from a pretrain-finetune discrepancy. In light of these pros and cons, we propose XLNet, a generalized autoregressive pretraining method that (1) enables learning bidirectional contexts by maximizing the expected likelihood over all permutations of the factorization order and (2) overcomes the limitations of BERT thanks to its autoregressive formulation. Furthermore, XLNet integrates ideas from Transformer-XL, the state-of-the-art autoregressive model, into pretraining. Empirically, under comparable experiment settings, XLNet outperforms BERT on 20 tasks, often by a large margin, including question answering, natural language inference, sentiment analysis, and document ranking.
Tips:
- The specific attention pattern can be controlled at training and test time using the - perm_maskinput.
- Due to the difficulty of training a fully auto-regressive model over various factorization order, XLNet is pretrained using only a sub-set of the output tokens as target which are selected with the - target_mappinginput.
- To use XLNet for sequential decoding (i.e. not in fully bi-directional setting), use the - perm_maskand- target_mappinginputs to control the attention span and outputs (see examples in examples/text-generation/run_generation.py)
- XLNet is one of the few models that has no sequence length limit. 
The original code can be found here.
XLNetConfigΒΆ
- 
class transformers.XLNetConfig(vocab_size=32000, d_model=1024, n_layer=24, n_head=16, d_inner=4096, ff_activation='gelu', untie_r=True, attn_type='bi', initializer_range=0.02, layer_norm_eps=1e-12, dropout=0.1, mem_len=512, reuse_len=None, use_mems_eval=True, use_mems_train=False, bi_data=False, clamp_len=- 1, same_length=False, summary_type='last', summary_use_proj=True, summary_activation='tanh', summary_last_dropout=0.1, start_n_top=5, end_n_top=5, pad_token_id=5, bos_token_id=1, eos_token_id=2, **kwargs)[source]ΒΆ
- This is the configuration class to store the configuration of a - XLNetModelor a- TFXLNetModel. It is used to instantiate a XLNet model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the xlnet-large-cased architecture.- Configuration objects inherit from - PretrainedConfigand can be used to control the model outputs. Read the documentation from- PretrainedConfigfor more information.- Parameters
- vocab_size ( - int, optional, defaults to 32000) β Vocabulary size of the XLNet model. Defines the number of different tokens that can be represented by the- inputs_idspassed when calling- XLNetModelor- TFXLNetModel.
- d_model ( - int, optional, defaults to 1024) β Dimensionality of the encoder layers and the pooler layer.
- n_layer ( - int, optional, defaults to 24) β Number of hidden layers in the Transformer encoder.
- n_head ( - int, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer encoder.
- d_inner ( - int, optional, defaults to 4096) β Dimensionality of the βintermediateβ (often named feed-forward) layer in the Transformer encoder.
- ff_activation ( - stror- Callable, optional, defaults to- "gelu") β The non-linear activation function (function or string) in the If string,- "gelu",- "relu",- "silu"and- "gelu_new"are supported.
- untie_r ( - bool, optional, defaults to- True) β Whether or not to untie relative position biases
- attn_type ( - str, optional, defaults to- "bi") β The attention type used by the model. Set- "bi"for XLNet,- "uni"for Transformer-XL.
- initializer_range ( - float, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- layer_norm_eps ( - float, optional, defaults to 1e-12) β The epsilon used by the layer normalization layers.
- dropout ( - float, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
- mem_len ( - intor- None, optional) β The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous forward pass wonβt be re-computed. See the quickstart for more information.
- reuse_len ( - int, optional) β The number of tokens in the current batch to be cached and reused in the future.
- bi_data ( - bool, optional, defaults to- False) β Whether or not to use bidirectional input pipeline. Usually set to- Trueduring pretraining and- Falseduring finetuning.
- clamp_len ( - int, optional, defaults to -1) β Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping.
- same_length ( - bool, optional, defaults to- False) β Whether or not to use the same attention length for each token.
- summary_type ( - str, optional, defaults to βlastβ) β- Argument used when doing sequence summary. Used in the sequence classification and multiple choice models. - Has to be one of the following options: - "last": Take the last token hidden state (like XLNet).
- "first": Take the first token hidden state (like BERT).
- "mean": Take the mean of all tokens hidden states.
- "cls_index": Supply a Tensor of classification token position (like GPT/GPT-2).
- "attn": Not implemented now, use multi-head attention.
 
- summary_use_proj ( - bool, optional, defaults to- True) β- Argument used when doing sequence summary. Used in the sequence classification and multiple choice models. - Whether or not to add a projection after the vector extraction. 
- summary_activation ( - str, optional) β- Argument used when doing sequence summary. Used in the sequence classification and multiple choice models. - Pass - "tanh"for a tanh activation to the output, any other value will result in no activation.
- summary_proj_to_labels ( - boo, optional, defaults to- True) β- Used in the sequence classification and multiple choice models. - Whether the projection outputs should have - config.num_labelsor- config.hidden_sizeclasses.
- summary_last_dropout ( - float, optional, defaults to 0.1) β- Used in the sequence classification and multiple choice models. - The dropout ratio to be used after the projection and activation. 
- start_n_top ( - int, optional, defaults to 5) β Used in the SQuAD evaluation script.
- end_n_top ( - int, optional, defaults to 5) β Used in the SQuAD evaluation script.
- use_mems_eval ( - bool, optional, defaults to- True) β Whether or not the model should make use of the recurrent memory mechanism in evaluation mode.
- use_mems_train ( - bool, optional, defaults to- False) β- Whether or not the model should make use of the recurrent memory mechanism in train mode. - Note - For pretraining, it is recommended to set - use_mems_trainto- True. For fine-tuning, it is recommended to set- use_mems_trainto- Falseas discussed here. If- use_mems_trainis set to- True, one has to make sure that the train batches are correctly pre-processed, e.g.- batch_1 = [[This line is], [This is the]]and- batch_2 = [[ the first line], [ second line]]and that all batches are of equal size.
 
 - Examples: - >>> from transformers import XLNetConfig, XLNetModel >>> # Initializing a XLNet configuration >>> configuration = XLNetConfig() >>> # Initializing a model from the configuration >>> model = XLNetModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config 
XLNetTokenizerΒΆ
- 
class transformers.XLNetTokenizer(vocab_file, do_lower_case=False, remove_space=True, keep_accents=False, bos_token='<s>', eos_token='</s>', unk_token='<unk>', sep_token='<sep>', pad_token='<pad>', cls_token='<cls>', mask_token='<mask>', additional_special_tokens=['<eop>', '<eod>'], **kwargs)[source]ΒΆ
- Construct an XLNet tokenizer. Based on SentencePiece. - This tokenizer inherits from - PreTrainedTokenizerwhich contains most of the main methods. Users should refer to this superclass for more information regarding those methods.- Parameters
- vocab_file ( - str) β SentencePiece file (generally has a .spm extension) that contains the vocabulary necessary to instantiate a tokenizer.
- do_lower_case ( - bool, optional, defaults to- True) β Whether to lowercase the input when tokenizing.
- remove_space ( - bool, optional, defaults to- True) β Whether to strip the text when tokenizing (removing excess spaces before and after the string).
- keep_accents ( - bool, optional, defaults to- False) β Whether to keep accents when tokenizing.
- 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.
- 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.
- sep_token ( - str, optional, defaults to- "<sep>") β The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.
- pad_token ( - str, optional, defaults to- "<pad>") β The token used for padding, for example when batching sequences of different lengths.
- cls_token ( - str, optional, defaults to- "<cls>") β The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.
- mask_token ( - 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- ["<eop>", "<eod>"]) β Additional special tokens used by the tokenizer.
 
 - 
sp_modelΒΆ
- The SentencePiece processor that is used for every conversion (string, tokens and IDs). - Type
- SentencePieceProcessor
 
 - 
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 XLNet sequence has the following format: - single sequence: - X <sep> <cls>
- pair of sequences: - A <sep> B <sep> <cls>
 - 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. An XLNet sequence pair mask has the following format: - 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | - If - token_ids_1is- None, this method only returns the first portion of the mask (0s).- Parameters
- token_ids_0 ( - List[int]) β List of IDs.
- token_ids_1 ( - List[int], optional) β Optional second list of IDs for sequence pairs.
 
- Returns
- List of token type IDs according to the given sequence(s). 
- Return type
- List[int]
 
 - 
get_special_tokens_mask(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int][source]ΒΆ
- 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_modelmethod.- Parameters
- token_ids_0 ( - List[int]) β List of IDs.
- token_ids_1 ( - List[int], optional) β Optional second list of IDs for sequence pairs.
- already_has_special_tokens ( - bool, optional, defaults to- False) β Whether or not the token list is already formatted with special tokens for the model.
 
- Returns
- 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)
 
 
XLNetTokenizerFastΒΆ
- 
class transformers.XLNetTokenizerFast(vocab_file, tokenizer_file=None, do_lower_case=False, remove_space=True, keep_accents=False, bos_token='<s>', eos_token='</s>', unk_token='<unk>', sep_token='<sep>', pad_token='<pad>', cls_token='<cls>', mask_token='<mask>', additional_special_tokens=['<eop>', '<eod>'], **kwargs)[source]ΒΆ
- Construct a βfastβ XLNet tokenizer (backed by HuggingFaceβs tokenizers library). Based on Unigram. - This tokenizer inherits from - PreTrainedTokenizerFastwhich contains most of the main methods. Users should refer to this superclass for more information regarding those methods.- Parameters
- vocab_file ( - str) β SentencePiece file (generally has a .spm extension) that contains the vocabulary necessary to instantiate a tokenizer.
- do_lower_case ( - bool, optional, defaults to- True) β Whether to lowercase the input when tokenizing.
- remove_space ( - bool, optional, defaults to- True) β Whether to strip the text when tokenizing (removing excess spaces before and after the string).
- keep_accents ( - bool, optional, defaults to- False) β Whether to keep accents when tokenizing.
- 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.
- 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.
- sep_token ( - str, optional, defaults to- "<sep>") β The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.
- pad_token ( - str, optional, defaults to- "<pad>") β The token used for padding, for example when batching sequences of different lengths.
- cls_token ( - str, optional, defaults to- "<cls>") β The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.
- mask_token ( - 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- ["<eop>", "<eod>"]) β Additional special tokens used by the tokenizer.
 
 - 
sp_modelΒΆ
- The SentencePiece processor that is used for every conversion (string, tokens and IDs). - Type
- SentencePieceProcessor
 
 - 
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 XLNet sequence has the following format: - single sequence: - X <sep> <cls>
- pair of sequences: - A <sep> B <sep> <cls>
 - 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. An XLNet sequence pair mask has the following format: - 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | - If - token_ids_1is- None, this method only returns the first portion of the mask (0s).- Parameters
- token_ids_0 ( - List[int]) β List of IDs.
- token_ids_1 ( - List[int], optional) β Optional second list of IDs for sequence pairs.
 
- Returns
- List of token type IDs according to the given sequence(s). 
- Return type
- List[int]
 
 - 
get_special_tokens_mask(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int][source]ΒΆ
- 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_modelmethod.- Parameters
- token_ids_0 ( - List[int]) β List of IDs.
- token_ids_1 ( - List[int], optional) β Optional second list of IDs for sequence pairs.
- already_has_special_tokens ( - bool, optional, defaults to- False) β Whether or not the token list is already formatted with special tokens for the model.
 
- Returns
- 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)
 
 - 
slow_tokenizer_classΒΆ
- alias of - transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer
 
XLNet specific outputsΒΆ
- 
class transformers.models.xlnet.modeling_xlnet.XLNetModelOutput(last_hidden_state: torch.FloatTensor, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetModel.- Parameters
- last_hidden_state ( - torch.FloatTensorof shape- (batch_size, num_predict, hidden_size)) β- Sequence of hidden-states at the last layer of the model. - num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutput(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetLMHeadModel.- Parameters
- loss ( - torch.FloatTensorof shape (1,), optional, returned when- labelsis provided) β Language modeling loss (for next-token prediction).
- logits ( - torch.FloatTensorof shape- (batch_size, num_predict, config.vocab_size)) β- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutput(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetForSequenceClassification.- Parameters
- loss ( - torch.FloatTensorof shape- (1,), optional, returned when- labelis provided) β Classification (or regression if config.num_labels==1) loss.
- logits ( - torch.FloatTensorof shape- (batch_size, config.num_labels)) β Classification (or regression if config.num_labels==1) scores (before SoftMax).
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutput(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetForMultipleChoice.- Parameters
- loss ( - torch.FloatTensorof shape (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - torch.FloatTensorof shape- (batch_size, num_choices)) β- num_choices is the second dimension of the input tensors. (see input_ids above). - Classification scores (before SoftMax). 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutput(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetForTokenClassificationOutput.- Parameters
- loss ( - torch.FloatTensorof shape- (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - torch.FloatTensorof shape- (batch_size, sequence_length, config.num_labels)) β Classification scores (before SoftMax).
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput(loss: Optional[torch.FloatTensor] = None, start_logits: torch.FloatTensor = None, end_logits: torch.FloatTensor = None, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetForQuestionAnsweringSimple.- Parameters
- loss ( - torch.FloatTensorof shape- (1,), optional, returned when- labelsis provided) β Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
- start_logits ( - torch.FloatTensorof shape- (batch_size, sequence_length,)) β Span-start scores (before SoftMax).
- end_logits ( - torch.FloatTensorof shape- (batch_size, sequence_length,)) β Span-end scores (before SoftMax).
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutput(loss: Optional[torch.FloatTensor] = None, start_top_log_probs: Optional[torch.FloatTensor] = None, start_top_index: Optional[torch.LongTensor] = None, end_top_log_probs: Optional[torch.FloatTensor] = None, end_top_index: Optional[torch.LongTensor] = None, cls_logits: Optional[torch.FloatTensor] = None, mems: Optional[List[torch.FloatTensor]] = None, hidden_states: Optional[Tuple[torch.FloatTensor]] = None, attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ
- Output type of - XLNetForQuestionAnswering.- Parameters
- loss ( - torch.FloatTensorof shape- (1,), optional, returned if both- start_positionsand- end_positionsare provided) β Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.
- start_top_log_probs ( - torch.FloatTensorof shape- (batch_size, config.start_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Log probabilities for the top config.start_n_top start token possibilities (beam-search).
- start_top_index ( - torch.LongTensorof shape- (batch_size, config.start_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Indices for the top config.start_n_top start token possibilities (beam-search).
- end_top_log_probs ( - torch.FloatTensorof shape- (batch_size, config.start_n_top * config.end_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Log probabilities for the top- config.start_n_top * config.end_n_topend token possibilities (beam-search).
- end_top_index ( - torch.LongTensorof shape- (batch_size, config.start_n_top * config.end_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Indices for the top- config.start_n_top * config.end_n_topend token possibilities (beam-search).
- cls_logits ( - torch.FloatTensorof shape- (batch_size,), optional, returned if- start_positionsor- end_positionsis not provided) β Log probabilities for the- is_impossiblelabel of the answers.
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
 
- 
class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput(last_hidden_state: tensorflow.python.framework.ops.Tensor = None, mems: Optional[List[tensorflow.python.framework.ops.Tensor]] = None, hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ
- Output type of - TFXLNetModel.- Parameters
- last_hidden_state ( - tf.Tensorof shape- (batch_size, num_predict, hidden_size)) β- Sequence of hidden-states at the last layer of the model. - num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - tf.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. 
 
 
- 
class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput(loss: Optional[tensorflow.python.framework.ops.Tensor] = None, logits: tensorflow.python.framework.ops.Tensor = None, mems: Optional[List[tensorflow.python.framework.ops.Tensor]] = None, hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ
- Output type of - TFXLNetLMHeadModel.- Parameters
- loss ( - tf.Tensorof shape (1,), optional, returned when- labelsis provided) β Language modeling loss (for next-token prediction).
- logits ( - tf.Tensorof shape- (batch_size, num_predict, config.vocab_size)) β- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - tf.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. 
 
 
- 
class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput(loss: Optional[tensorflow.python.framework.ops.Tensor] = None, logits: tensorflow.python.framework.ops.Tensor = None, mems: Optional[List[tensorflow.python.framework.ops.Tensor]] = None, hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ
- Output type of - TFXLNetForSequenceClassification.- Parameters
- loss ( - tf.Tensorof shape- (1,), optional, returned when- labelis provided) β Classification (or regression if config.num_labels==1) loss.
- logits ( - tf.Tensorof shape- (batch_size, config.num_labels)) β Classification (or regression if config.num_labels==1) scores (before SoftMax).
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - tf.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. 
 
 
- 
class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutput(loss: Optional[tensorflow.python.framework.ops.Tensor] = None, logits: tensorflow.python.framework.ops.Tensor = None, mems: Optional[List[tensorflow.python.framework.ops.Tensor]] = None, hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ
- Output type of - TFXLNetForMultipleChoice.- Parameters
- loss ( - tf.Tensorof shape (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - tf.Tensorof shape- (batch_size, num_choices)) β- num_choices is the second dimension of the input tensors. (see input_ids above). - Classification scores (before SoftMax). 
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - tf.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. 
 
 
- 
class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput(loss: Optional[tensorflow.python.framework.ops.Tensor] = None, logits: tensorflow.python.framework.ops.Tensor = None, mems: Optional[List[tensorflow.python.framework.ops.Tensor]] = None, hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ
- Output type of - TFXLNetForTokenClassificationOutput.- Parameters
- loss ( - tf.Tensorof shape- (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - tf.Tensorof shape- (batch_size, sequence_length, config.num_labels)) β Classification scores (before SoftMax).
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - tf.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. 
 
 
- 
class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput(loss: Optional[tensorflow.python.framework.ops.Tensor] = None, start_logits: tensorflow.python.framework.ops.Tensor = None, end_logits: tensorflow.python.framework.ops.Tensor = None, mems: Optional[List[tensorflow.python.framework.ops.Tensor]] = None, hidden_states: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None, attentions: Optional[Tuple[tensorflow.python.framework.ops.Tensor]] = None)[source]ΒΆ
- Output type of - TFXLNetForQuestionAnsweringSimple.- Parameters
- loss ( - tf.Tensorof shape- (1,), optional, returned when- labelsis provided) β Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
- start_logits ( - tf.Tensorof shape- (batch_size, sequence_length,)) β Span-start scores (before SoftMax).
- end_logits ( - tf.Tensorof shape- (batch_size, sequence_length,)) β Span-end scores (before SoftMax).
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β- Tuple of - tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β- Tuple of - tf.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. 
 
 
XLNetModelΒΆ
- 
class transformers.XLNetModel(config)[source]ΒΆ
- The bare XLNet 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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetModelforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
 
- Returns
- A - XLNetModelOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- last_hidden_state ( - torch.FloatTensorof shape- (batch_size, num_predict, hidden_size)) β Sequence of hidden-states at the last layer of the model.- num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
- Return type
- XLNetModelOutputor- tuple(torch.FloatTensor)
 - Example: - >>> from transformers import XLNetTokenizer, XLNetModel >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = XLNetModel.from_pretrained('xlnet-base-cased') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state 
 
XLNetLMHeadModelΒΆ
- 
class transformers.XLNetLMHeadModel(config)[source]ΒΆ
- XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings). - 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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, labels=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetLMHeadModelforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- labels ( - torch.LongTensorof shape- (batch_size, num_predict), optional) β- Labels for masked language modeling. - num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis :obj`None`, then- num_predictcorresponds to- sequence_length.- The labels should correspond to the masked input words that should be predicted and depends on - target_mapping. Note in order to perform standard auto-regressive language modeling a <mask> token has to be added to the- input_ids(see the- prepare_inputs_for_generationfunction and examples below)- Indices are selected in - [-100, 0, ..., config.vocab_size]All labels set to- -100are ignored, the loss is only computed for labels in- [0, ..., config.vocab_size]
 
- Returns
- A - XLNetLMHeadModelOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - torch.FloatTensorof shape (1,), optional, returned when- labelsis provided) Language modeling loss (for next-token prediction).
- logits ( - torch.FloatTensorof shape- (batch_size, num_predict, config.vocab_size)) β Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).- num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 - Examples: - >>> from transformers import XLNetTokenizer, XLNetLMHeadModel >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') >>> model = XLNetLMHeadModel.from_pretrained('xlnet-large-cased') >>> # We show how to setup inputs to predict a next token using a bi-directional context. >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)).unsqueeze(0) # We will predict the masked token >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float) >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token >>> target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float) # Shape [1, 1, seq_length] => let's predict one token >>> target_mapping[0, 0, -1] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token) >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping) >>> next_token_logits = outputs[0] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size] >>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling. >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)).unsqueeze(0) # We will predict the masked token >>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0) >>> assert labels.shape[0] == 1, 'only one word will be predicted' >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float) >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token as is done in standard auto-regressive lm training >>> target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float) # Shape [1, 1, seq_length] => let's predict one token >>> target_mapping[0, 0, -1] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token) >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels) >>> loss = outputs.loss >>> next_token_logits = outputs.logits # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size] 
- Return type
- XLNetLMHeadModelOutputor- tuple(torch.FloatTensor)
 
 
XLNetForSequenceClassificationΒΆ
- 
class transformers.XLNetForSequenceClassification(config)[source]ΒΆ
- XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. - This model 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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, labels=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetForSequenceClassificationforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- labels ( - torch.LongTensorof shape- (batch_size,), optional) β Labels for computing the sequence classification/regression loss. Indices should be in- [0, ..., config.num_labels - 1]. If- config.num_labels == 1a regression loss is computed (Mean-Square loss), If- config.num_labels > 1a classification loss is computed (Cross-Entropy).
 
- Returns
- A - XLNetForSequenceClassificationOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - torch.FloatTensorof shape- (1,), optional, returned when- labelis provided) β Classification (or regression if config.num_labels==1) loss.
- logits ( - torch.FloatTensorof shape- (batch_size, config.num_labels)) β Classification (or regression if config.num_labels==1) scores (before SoftMax).
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
- Return type
- XLNetForSequenceClassificationOutputor- tuple(torch.FloatTensor)
 - Example: - >>> from transformers import XLNetTokenizer, XLNetForSequenceClassification >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = XLNetForSequenceClassification.from_pretrained('xlnet-base-cased') >>> 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 
 
XLNetForMultipleChoiceΒΆ
- 
class transformers.XLNetForMultipleChoice(config)[source]ΒΆ
- XLNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RACE/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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, token_type_ids=None, input_mask=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, head_mask=None, inputs_embeds=None, labels=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetForMultipleChoiceforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, num_choices, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, num_choices, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, num_choices, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- labels ( - torch.LongTensorof shape- (batch_size,), optional) β Labels for computing the multiple choice classification loss. Indices should be in- [0, ..., num_choices-1]where- num_choicesis the size of the second dimension of the input tensors. (See- input_idsabove)
 
- Returns
- A - XLNetForMultipleChoiceOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - torch.FloatTensorof shape (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - torch.FloatTensorof shape- (batch_size, num_choices)) β num_choices is the second dimension of the input tensors. (see input_ids above).- Classification scores (before SoftMax). 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
- Return type
- XLNetForMultipleChoiceOutputor- tuple(torch.FloatTensor)
 - Example: - >>> from transformers import XLNetTokenizer, XLNetForMultipleChoice >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = XLNetForMultipleChoice.from_pretrained('xlnet-base-cased') >>> 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 
 
XLNetForTokenClassificationΒΆ
- 
class transformers.XLNetForTokenClassification(config)[source]ΒΆ
- XLNet 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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, labels=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetForTokenClassificationforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- labels ( - torch.LongTensorof shape- (batch_size,), optional) β Labels for computing the multiple choice classification loss. Indices should be in- [0, ..., num_choices]where num_choices is the size of the second dimension of the input tensors. (see input_ids above)
 
- Returns
- A - XLNetForTokenClassificationOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - torch.FloatTensorof shape- (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - torch.FloatTensorof shape- (batch_size, sequence_length, config.num_labels)) β Classification scores (before SoftMax).
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
- Return type
- XLNetForTokenClassificationOutputor- tuple(torch.FloatTensor)
 - Example: - >>> from transformers import XLNetTokenizer, XLNetForTokenClassification >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = XLNetForTokenClassification.from_pretrained('xlnet-base-cased') >>> 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 
 
XLNetForQuestionAnsweringSimpleΒΆ
- 
class transformers.XLNetForQuestionAnsweringSimple(config)[source]ΒΆ
- XLNet 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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetForQuestionAnsweringSimpleforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- start_positions ( - torch.LongTensorof 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.LongTensorof 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 - XLNetForQuestionAnsweringSimpleOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - torch.FloatTensorof shape- (1,), optional, returned when- labelsis provided) β Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
- start_logits ( - torch.FloatTensorof shape- (batch_size, sequence_length,)) β Span-start scores (before SoftMax).
- end_logits ( - torch.FloatTensorof shape- (batch_size, sequence_length,)) β Span-end scores (before SoftMax).
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 
- Return type
- XLNetForQuestionAnsweringSimpleOutputor- tuple(torch.FloatTensor)
 - Example: - >>> from transformers import XLNetTokenizer, XLNetForQuestionAnsweringSimple >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = XLNetForQuestionAnsweringSimple.from_pretrained('xlnet-base-cased') >>> 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 
 
XLNetForQuestionAnsweringΒΆ
- 
class transformers.XLNetForQuestionAnswering(config)[source]ΒΆ
- XLNet 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 ( - XLNetConfig) β 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.
 - 
forward(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, is_impossible=None, cls_index=None, p_mask=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]ΒΆ
- The - XLNetForQuestionAnsweringforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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.LongTensorof shape- batch_size, sequence_length) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - transformers.XLNetTokenizer. See- transformers.PreTrainedTokenizer.encode()and- transformers.PreTrainedTokenizer.__call__()for details.
- attention_mask ( - torch.FloatTensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - torch.FloatTensorof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token. Only used during pretraining for partial prediction or for sequential decoding (generation).
- token_type_ids ( - torch.LongTensorof 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. 
 
- input_mask ( - torch.FloatTensorof shape- batch_size, sequence_length, optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not masked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - torch.FloatTensorof 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.FloatTensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- start_positions ( - torch.LongTensorof 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.LongTensorof shape- (batch_size,), optional) β Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (- sequence_length). Position outside of the sequence are not taken into account for computing the loss.
- is_impossible ( - torch.LongTensorof shape- (batch_size,), optional) β Labels whether a question has an answer or no answer (SQuAD 2.0)
- cls_index ( - torch.LongTensorof shape- (batch_size,), optional) β Labels for position (index) of the classification token to use as input for computing plausibility of the answer.
- p_mask ( - torch.FloatTensorof shape- (batch_size, sequence_length), optional) β Optional mask of tokens which canβt be in answers (e.g. [CLS], [PAD], β¦). 1.0 means token should be masked. 0.0 mean token is not masked.
 
- Returns
- A - XLNetForQuestionAnsweringOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- torch.FloatTensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - torch.FloatTensorof shape- (1,), optional, returned if both- start_positionsand- end_positionsare provided) β Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.
- start_top_log_probs ( - torch.FloatTensorof shape- (batch_size, config.start_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Log probabilities for the top config.start_n_top start token possibilities (beam-search).
- start_top_index ( - torch.LongTensorof shape- (batch_size, config.start_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Indices for the top config.start_n_top start token possibilities (beam-search).
- end_top_log_probs ( - torch.FloatTensorof shape- (batch_size, config.start_n_top * config.end_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Log probabilities for the top- config.start_n_top * config.end_n_topend token possibilities (beam-search).
- end_top_index ( - torch.LongTensorof shape- (batch_size, config.start_n_top * config.end_n_top), optional, returned if- start_positionsor- end_positionsis not provided) β Indices for the top- config.start_n_top * config.end_n_topend token possibilities (beam-search).
- cls_logits ( - torch.FloatTensorof shape- (batch_size,), optional, returned if- start_positionsor- end_positionsis not provided) β Log probabilities for the- is_impossiblelabel of the answers.
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(torch.FloatTensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- torch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape- (batch_size, sequence_length, hidden_size).- Hidden-states of the model at the output of each layer plus the initial embedding outputs. 
- attentions ( - tuple(torch.FloatTensor), optional, returned when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- torch.FloatTensor(one for each layer) of shape- (batch_size, num_heads, sequence_length, sequence_length).- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 
 - Example: - >>> from transformers import XLNetTokenizer, XLNetForQuestionAnswering >>> import torch >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = XLNetForQuestionAnswering.from_pretrained('xlnet-base-cased') >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 >>> start_positions = torch.tensor([1]) >>> end_positions = torch.tensor([3]) >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) >>> loss = outputs.loss 
- Return type
- XLNetForQuestionAnsweringOutputor- tuple(torch.FloatTensor)
 
 
TFXLNetModelΒΆ
- 
class transformers.TFXLNetModel(*args, **kwargs)[source]ΒΆ
- The bare XLNet 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_idsonly 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])or- model([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 ( - XLNetConfig) β 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.
 - 
call(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, training=False, **kwargs)[source]ΒΆ
- The - TFXLNetModelforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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 arrayor- tf.Tensorof shape- (batch_size, sequence_length)) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - BertTokenizer. See- transformers.PreTrainedTokenizer.__call__()and- transformers.PreTrainedTokenizer.encode()for details.
- attention_mask ( - Numpy arrayor- tf.Tensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- :obj: - use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token.
- token_type_ids ( - Numpy arrayor- tf.Tensorof 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. 
 
- input_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length), optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not maked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - Numpy arrayor- tf.Tensorof 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.Tensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- training ( - bool, optional, defaults to- False) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
 
- Returns
- A - TFXLNetModelOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- tf.Tensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- last_hidden_state ( - tf.Tensorof shape- (batch_size, num_predict, hidden_size)) β Sequence of hidden-states at the last layer of the model.- num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- tf.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
- TFXLNetModelOutputor- tuple(tf.Tensor)
 - Example: - >>> from transformers import XLNetTokenizer, TFXLNetModel >>> import tensorflow as tf >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = TFXLNetModel.from_pretrained('xlnet-base-cased') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> outputs = model(inputs) >>> last_hidden_states = outputs.last_hidden_states 
 
TFXLNetLMHeadModelΒΆ
- 
class transformers.TFXLNetLMHeadModel(*args, **kwargs)[source]ΒΆ
- XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings). - 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_idsonly 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])or- model([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 ( - XLNetConfig) β 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.
 - 
call(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False, **kwargs)[source]ΒΆ
- The - TFXLNetLMHeadModelforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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 arrayor- tf.Tensorof shape- (batch_size, sequence_length)) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - BertTokenizer. See- transformers.PreTrainedTokenizer.__call__()and- transformers.PreTrainedTokenizer.encode()for details.
- attention_mask ( - Numpy arrayor- tf.Tensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- :obj: - use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token.
- token_type_ids ( - Numpy arrayor- tf.Tensorof 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. 
 
- input_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length), optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not maked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - Numpy arrayor- tf.Tensorof 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.Tensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- training ( - bool, optional, defaults to- False) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
- labels ( - tf.Tensorof shape- (batch_size, sequence_length), optional) β Labels for computing the cross entropy classification loss. Indices should be in- [0, ..., config.vocab_size - 1].
 
- Returns
- A - TFXLNetLMHeadModelOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- tf.Tensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - tf.Tensorof shape (1,), optional, returned when- labelsis provided) Language modeling loss (for next-token prediction).
- logits ( - tf.Tensorof shape- (batch_size, num_predict, config.vocab_size)) β Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).- num_predictcorresponds to- target_mapping.shape[1]. If- target_mappingis- None, then- num_predictcorresponds to- sequence_length.
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- tf.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. 
 - Examples: - >>> import tensorflow as tf >>> import numpy as np >>> from transformers import XLNetTokenizer, TFXLNetLMHeadModel >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') >>> model = TFXLNetLMHeadModel.from_pretrained('xlnet-large-cased') >>> # We show how to setup inputs to predict a next token using a bi-directional context. >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=True))[None, :] # We will predict the masked token >>> perm_mask = np.zeros((1, input_ids.shape[1], input_ids.shape[1])) >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token >>> target_mapping = np.zeros((1, 1, input_ids.shape[1])) # Shape [1, 1, seq_length] => let's predict one token >>> target_mapping[0, 0, -1] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token) >>> outputs = model(input_ids, perm_mask=tf.constant(perm_mask, dtype=tf.float32), target_mapping=tf.constant(target_mapping, dtype=tf.float32)) >>> next_token_logits = outputs[0] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size] 
- Return type
- TFXLNetLMHeadModelOutputor- tuple(tf.Tensor)
 
 
TFXLNetForSequenceClassificationΒΆ
- 
class transformers.TFXLNetForSequenceClassification(*args, **kwargs)[source]ΒΆ
- XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. - This model 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_idsonly 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])or- model([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 ( - XLNetConfig) β 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.
 - 
call(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False, **kwargs)[source]ΒΆ
- The - TFXLNetForSequenceClassificationforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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 arrayor- tf.Tensorof shape- (batch_size, sequence_length)) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - BertTokenizer. See- transformers.PreTrainedTokenizer.__call__()and- transformers.PreTrainedTokenizer.encode()for details.
- attention_mask ( - Numpy arrayor- tf.Tensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- :obj: - use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token.
- token_type_ids ( - Numpy arrayor- tf.Tensorof 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. 
 
- input_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length), optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not maked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - Numpy arrayor- tf.Tensorof 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.Tensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- training ( - bool, optional, defaults to- False) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
- labels ( - tf.Tensorof shape- (batch_size,), optional) β Labels for computing the sequence classification/regression loss. Indices should be in- [0, ..., config.num_labels - 1]. If- config.num_labels == 1a regression loss is computed (Mean-Square loss), If- config.num_labels > 1a classification loss is computed (Cross-Entropy).
 
- Returns
- A - TFXLNetForSequenceClassificationOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- tf.Tensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - tf.Tensorof shape- (1,), optional, returned when- labelis provided) β Classification (or regression if config.num_labels==1) loss.
- logits ( - tf.Tensorof shape- (batch_size, config.num_labels)) β Classification (or regression if config.num_labels==1) scores (before SoftMax).
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- tf.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
- TFXLNetForSequenceClassificationOutputor- tuple(tf.Tensor)
 - Example: - >>> from transformers import XLNetTokenizer, TFXLNetForSequenceClassification >>> import tensorflow as tf >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = TFXLNetForSequenceClassification.from_pretrained('xlnet-base-cased') >>> 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 
 
TFLNetForMultipleChoiceΒΆ
- 
class transformers.TFXLNetForMultipleChoice(*args, **kwargs)[source]ΒΆ
- XLNET 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_idsonly 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])or- model([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 ( - XLNetConfig) β 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.
 - 
call(input_ids=None, token_type_ids=None, input_mask=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False, **kwargs)[source]ΒΆ
- The - TFXLNetForMultipleChoiceforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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 arrayor- tf.Tensorof shape- (batch_size, num_choices, sequence_length)) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - BertTokenizer. See- transformers.PreTrainedTokenizer.__call__()and- transformers.PreTrainedTokenizer.encode()for details.
- attention_mask ( - Numpy arrayor- tf.Tensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- :obj: - use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token.
- token_type_ids ( - Numpy arrayor- tf.Tensorof 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. 
 
- input_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_choices, sequence_length), optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not maked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - Numpy arrayor- tf.Tensorof 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.Tensorof shape- (batch_size, num_choices, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- training ( - bool, optional, defaults to- False) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
- labels ( - tf.Tensorof shape- (batch_size,), optional) β Labels for computing the multiple choice classification loss. Indices should be in- [0, ..., num_choices]where- num_choicesis the size of the second dimension of the input tensors. (See- input_idsabove)
 
- Returns
- A - TFXLNetForMultipleChoiceOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- tf.Tensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - tf.Tensorof shape (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - tf.Tensorof shape- (batch_size, num_choices)) β num_choices is the second dimension of the input tensors. (see input_ids above).- Classification scores (before SoftMax). 
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- tf.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
- TFXLNetForMultipleChoiceOutputor- tuple(tf.Tensor)
 - Example: - >>> from transformers import XLNetTokenizer, TFXLNetForMultipleChoice >>> import tensorflow as tf >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = TFXLNetForMultipleChoice.from_pretrained('xlnet-base-cased') >>> 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 
 
TFXLNetForTokenClassificationΒΆ
- 
class transformers.TFXLNetForTokenClassification(*args, **kwargs)[source]ΒΆ
- XLNet 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_idsonly 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])or- model([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 ( - XLNetConfig) β 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.
 - 
call(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False, **kwargs)[source]ΒΆ
- The - TFXLNetForTokenClassificationforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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 arrayor- tf.Tensorof shape- (batch_size, sequence_length)) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - BertTokenizer. See- transformers.PreTrainedTokenizer.__call__()and- transformers.PreTrainedTokenizer.encode()for details.
- attention_mask ( - Numpy arrayor- tf.Tensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- :obj: - use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token.
- token_type_ids ( - Numpy arrayor- tf.Tensorof 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. 
 
- input_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length), optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not maked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - Numpy arrayor- tf.Tensorof 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.Tensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- training ( - bool, optional, defaults to- False) β Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
- labels ( - tf.Tensorof shape- (batch_size, sequence_length), optional) β Labels for computing the token classification loss. Indices should be in- [0, ..., config.num_labels - 1].
 
- Returns
- A - TFXLNetForTokenClassificationOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- tf.Tensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - tf.Tensorof shape- (1,), optional, returned when- labelsis provided) β Classification loss.
- logits ( - tf.Tensorof shape- (batch_size, sequence_length, config.num_labels)) β Classification scores (before SoftMax).
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- tf.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
- TFXLNetForTokenClassificationOutputor- tuple(tf.Tensor)
 - Example: - >>> from transformers import XLNetTokenizer, TFXLNetForTokenClassification >>> import tensorflow as tf >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = TFXLNetForTokenClassification.from_pretrained('xlnet-base-cased') >>> 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 
 
TFXLNetForQuestionAnsweringSimpleΒΆ
- 
class transformers.TFXLNetForQuestionAnsweringSimple(*args, **kwargs)[source]ΒΆ
- XLNet 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_idsonly 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])or- model([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 ( - XLNetConfig) β 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.
 - 
call(input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_mems=None, output_attentions=None, output_hidden_states=None, return_dict=None, start_positions=None, end_positions=None, training=False, **kwargs)[source]ΒΆ
- The - TFXLNetForQuestionAnsweringSimpleforward method, overrides the- __call__()special method.- Note - Although the recipe for forward pass needs to be defined within this function, one should call the - Moduleinstance 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 arrayor- tf.Tensorof shape- (batch_size, sequence_length)) β- Indices of input sequence tokens in the vocabulary. - Indices can be obtained using - BertTokenizer. See- transformers.PreTrainedTokenizer.__call__()and- transformers.PreTrainedTokenizer.encode()for details.
- attention_mask ( - Numpy arrayor- tf.Tensorof 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. 
 
- mems ( - List[torch.FloatTensor]of length- config.n_layers) β- Contains pre-computed hidden-states (see - memsoutput below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.- :obj: - use_memshas to be set to- Trueto make use of- mems.
- perm_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length, sequence_length), optional) β- Mask to indicate the attention pattern for each input token with values selected in - [0, 1]:- if - perm_mask[k, i, j] = 0, i attend to j in batch k;
- if - perm_mask[k, i, j] = 1, i does not attend to j in batch k.
 - If not set, each token attends to all the others (full bidirectional attention). Only used during pretraining (to define factorization order) or for sequential decoding (generation). 
- target_mapping ( - tf.Tensoror- Numpy arrayof shape- (batch_size, num_predict, sequence_length), optional) β Mask to indicate the output tokens to use. If- target_mapping[k, i, j] = 1, the i-th predict in batch k is on the j-th token.
- token_type_ids ( - Numpy arrayor- tf.Tensorof 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. 
 
- input_mask ( - tf.Tensoror- Numpy arrayof shape- (batch_size, sequence_length), optional) β- Mask to avoid performing attention on padding token indices. Negative of - attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.- Mask values selected in - [0, 1]:- 1 for tokens that are masked, 
- 0 for tokens that are not maked. 
 - You can only uses one of - input_maskand- attention_mask.
- head_mask ( - Numpy arrayor- tf.Tensorof 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.Tensorof shape- (batch_size, sequence_length, hidden_size), optional) β Optionally, instead of passing- input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convert- input_idsindices 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. See- attentionsunder returned tensors for more detail.
- output_hidden_states ( - bool, optional) β Whether or not to return the hidden states of all layers. See- hidden_statesunder returned tensors for more detail.
- return_dict ( - bool, optional) β Whether or not to return a- ModelOutputinstead of a plain tuple.
- training ( - bool, optional, defaults to- False) β 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.Tensorof 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.Tensorof 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 - TFXLNetForQuestionAnsweringSimpleOutput(if- return_dict=Trueis passed or when- config.return_dict=True) or a tuple of- tf.Tensorcomprising various elements depending on the configuration (- XLNetConfig) and inputs.- loss ( - tf.Tensorof shape- (1,), optional, returned when- labelsis provided) β Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
- start_logits ( - tf.Tensorof shape- (batch_size, sequence_length,)) β Span-start scores (before SoftMax).
- end_logits ( - tf.Tensorof shape- (batch_size, sequence_length,)) β Span-end scores (before SoftMax).
- mems ( - List[tf.Tensor]of length- config.n_layers) β Contains pre-computed hidden-states. Can be used (see- memsinput) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as- input_idsas they have already been computed.
- hidden_states ( - tuple(tf.Tensor), optional, returned when- output_hidden_states=Trueis passed or when- config.output_hidden_states=True) β Tuple of- tf.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 when- output_attentions=Trueis passed or when- config.output_attentions=True) β Tuple of- tf.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
- TFXLNetForQuestionAnsweringSimpleOutputor- tuple(tf.Tensor)
 - Example: - >>> from transformers import XLNetTokenizer, TFXLNetForQuestionAnsweringSimple >>> import tensorflow as tf >>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') >>> model = TFXLNetForQuestionAnsweringSimple.from_pretrained('xlnet-base-cased') >>> 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])