Transformers
  • 🌍GET STARTED
    • Transformers
    • Quick tour
    • Installation
  • 🌍TUTORIALS
    • Run inference with pipelines
    • Write portable code with AutoClass
    • Preprocess data
    • Fine-tune a pretrained model
    • Train with a script
    • Set up distributed training with BOINC AI Accelerate
    • Load and train adapters with BOINC AI PEFT
    • Share your model
    • Agents
    • Generation with LLMs
  • 🌍TASK GUIDES
    • 🌍NATURAL LANGUAGE PROCESSING
      • Text classification
      • Token classification
      • Question answering
      • Causal language modeling
      • Masked language modeling
      • Translation
      • Summarization
      • Multiple choice
    • 🌍AUDIO
      • Audio classification
      • Automatic speech recognition
    • 🌍COMPUTER VISION
      • Image classification
      • Semantic segmentation
      • Video classification
      • Object detection
      • Zero-shot object detection
      • Zero-shot image classification
      • Depth estimation
    • 🌍MULTIMODAL
      • Image captioning
      • Document Question Answering
      • Visual Question Answering
      • Text to speech
    • 🌍GENERATION
      • Customize the generation strategy
    • 🌍PROMPTING
      • Image tasks with IDEFICS
  • 🌍DEVELOPER GUIDES
    • Use fast tokenizers from BOINC AI Tokenizers
    • Run inference with multilingual models
    • Use model-specific APIs
    • Share a custom model
    • Templates for chat models
    • Run training on Amazon SageMaker
    • Export to ONNX
    • Export to TFLite
    • Export to TorchScript
    • Benchmarks
    • Notebooks with examples
    • Community resources
    • Custom Tools and Prompts
    • Troubleshoot
  • 🌍PERFORMANCE AND SCALABILITY
    • Overview
    • 🌍EFFICIENT TRAINING TECHNIQUES
      • Methods and tools for efficient training on a single GPU
      • Multiple GPUs and parallelism
      • Efficient training on CPU
      • Distributed CPU training
      • Training on TPUs
      • Training on TPU with TensorFlow
      • Training on Specialized Hardware
      • Custom hardware for training
      • Hyperparameter Search using Trainer API
    • 🌍OPTIMIZING INFERENCE
      • Inference on CPU
      • Inference on one GPU
      • Inference on many GPUs
      • Inference on Specialized Hardware
    • Instantiating a big model
    • Troubleshooting
    • XLA Integration for TensorFlow Models
    • Optimize inference using `torch.compile()`
  • 🌍CONTRIBUTE
    • How to contribute to transformers?
    • How to add a model to BOINC AI Transformers?
    • How to convert a BOINC AI Transformers model to TensorFlow?
    • How to add a pipeline to BOINC AI Transformers?
    • Testing
    • Checks on a Pull Request
  • 🌍CONCEPTUAL GUIDES
    • Philosophy
    • Glossary
    • What BOINC AI Transformers can do
    • How BOINC AI Transformers solve tasks
    • The Transformer model family
    • Summary of the tokenizers
    • Attention mechanisms
    • Padding and truncation
    • BERTology
    • Perplexity of fixed-length models
    • Pipelines for webserver inference
    • Model training anatomy
  • 🌍API
    • 🌍MAIN CLASSES
      • Agents and Tools
      • 🌍Auto Classes
        • Extending the Auto Classes
        • AutoConfig
        • AutoTokenizer
        • AutoFeatureExtractor
        • AutoImageProcessor
        • AutoProcessor
        • Generic model classes
          • AutoModel
          • TFAutoModel
          • FlaxAutoModel
        • Generic pretraining classes
          • AutoModelForPreTraining
          • TFAutoModelForPreTraining
          • FlaxAutoModelForPreTraining
        • Natural Language Processing
          • AutoModelForCausalLM
          • TFAutoModelForCausalLM
          • FlaxAutoModelForCausalLM
          • AutoModelForMaskedLM
          • TFAutoModelForMaskedLM
          • FlaxAutoModelForMaskedLM
          • AutoModelForMaskGenerationge
          • TFAutoModelForMaskGeneration
          • AutoModelForSeq2SeqLM
          • TFAutoModelForSeq2SeqLM
          • FlaxAutoModelForSeq2SeqLM
          • AutoModelForSequenceClassification
          • TFAutoModelForSequenceClassification
          • FlaxAutoModelForSequenceClassification
          • AutoModelForMultipleChoice
          • TFAutoModelForMultipleChoice
          • FlaxAutoModelForMultipleChoice
          • AutoModelForNextSentencePrediction
          • TFAutoModelForNextSentencePrediction
          • FlaxAutoModelForNextSentencePrediction
          • AutoModelForTokenClassification
          • TFAutoModelForTokenClassification
          • FlaxAutoModelForTokenClassification
          • AutoModelForQuestionAnswering
          • TFAutoModelForQuestionAnswering
          • FlaxAutoModelForQuestionAnswering
          • AutoModelForTextEncoding
          • TFAutoModelForTextEncoding
        • Computer vision
          • AutoModelForDepthEstimation
          • AutoModelForImageClassification
          • TFAutoModelForImageClassification
          • FlaxAutoModelForImageClassification
          • AutoModelForVideoClassification
          • AutoModelForMaskedImageModeling
          • TFAutoModelForMaskedImageModeling
          • AutoModelForObjectDetection
          • AutoModelForImageSegmentation
          • AutoModelForImageToImage
          • AutoModelForSemanticSegmentation
          • TFAutoModelForSemanticSegmentation
          • AutoModelForInstanceSegmentation
          • AutoModelForUniversalSegmentation
          • AutoModelForZeroShotImageClassification
          • TFAutoModelForZeroShotImageClassification
          • AutoModelForZeroShotObjectDetection
        • Audio
          • AutoModelForAudioClassification
          • AutoModelForAudioFrameClassification
          • TFAutoModelForAudioFrameClassification
          • AutoModelForCTC
          • AutoModelForSpeechSeq2Seq
          • TFAutoModelForSpeechSeq2Seq
          • FlaxAutoModelForSpeechSeq2Seq
          • AutoModelForAudioXVector
          • AutoModelForTextToSpectrogram
          • AutoModelForTextToWaveform
        • Multimodal
          • AutoModelForTableQuestionAnswering
          • TFAutoModelForTableQuestionAnswering
          • AutoModelForDocumentQuestionAnswering
          • TFAutoModelForDocumentQuestionAnswering
          • AutoModelForVisualQuestionAnswering
          • AutoModelForVision2Seq
          • TFAutoModelForVision2Seq
          • FlaxAutoModelForVision2Seq
      • Callbacks
      • Configuration
      • Data Collator
      • Keras callbacks
      • Logging
      • Models
      • Text Generation
      • ONNX
      • Optimization
      • Model outputs
      • Pipelines
      • Processors
      • Quantization
      • Tokenizer
      • Trainer
      • DeepSpeed Integration
      • Feature Extractor
      • Image Processor
    • 🌍MODELS
      • 🌍TEXT MODELS
        • ALBERT
        • BART
        • BARThez
        • BARTpho
        • BERT
        • BertGeneration
        • BertJapanese
        • Bertweet
        • BigBird
        • BigBirdPegasus
        • BioGpt
        • Blenderbot
        • Blenderbot Small
        • BLOOM
        • BORT
        • ByT5
        • CamemBERT
        • CANINE
        • CodeGen
        • CodeLlama
        • ConvBERT
        • CPM
        • CPMANT
        • CTRL
        • DeBERTa
        • DeBERTa-v2
        • DialoGPT
        • DistilBERT
        • DPR
        • ELECTRA
        • Encoder Decoder Models
        • ERNIE
        • ErnieM
        • ESM
        • Falcon
        • FLAN-T5
        • FLAN-UL2
        • FlauBERT
        • FNet
        • FSMT
        • Funnel Transformer
        • GPT
        • GPT Neo
        • GPT NeoX
        • GPT NeoX Japanese
        • GPT-J
        • GPT2
        • GPTBigCode
        • GPTSAN Japanese
        • GPTSw3
        • HerBERT
        • I-BERT
        • Jukebox
        • LED
        • LLaMA
        • LLama2
        • Longformer
        • LongT5
        • LUKE
        • M2M100
        • MarianMT
        • MarkupLM
        • MBart and MBart-50
        • MEGA
        • MegatronBERT
        • MegatronGPT2
        • Mistral
        • mLUKE
        • MobileBERT
        • MPNet
        • MPT
        • MRA
        • MT5
        • MVP
        • NEZHA
        • NLLB
        • NLLB-MoE
        • Nyströmformer
        • Open-Llama
        • OPT
        • Pegasus
        • PEGASUS-X
        • Persimmon
        • PhoBERT
        • PLBart
        • ProphetNet
        • QDQBert
        • RAG
        • REALM
        • Reformer
        • RemBERT
        • RetriBERT
        • RoBERTa
        • RoBERTa-PreLayerNorm
        • RoCBert
        • RoFormer
        • RWKV
        • Splinter
        • SqueezeBERT
        • SwitchTransformers
        • T5
        • T5v1.1
        • TAPEX
        • Transformer XL
        • UL2
        • UMT5
        • X-MOD
        • XGLM
        • XLM
        • XLM-ProphetNet
        • XLM-RoBERTa
        • XLM-RoBERTa-XL
        • XLM-V
        • XLNet
        • YOSO
      • 🌍VISION MODELS
        • BEiT
        • BiT
        • Conditional DETR
        • ConvNeXT
        • ConvNeXTV2
        • CvT
        • Deformable DETR
        • DeiT
        • DETA
        • DETR
        • DiNAT
        • DINO V2
        • DiT
        • DPT
        • EfficientFormer
        • EfficientNet
        • FocalNet
        • GLPN
        • ImageGPT
        • LeViT
        • Mask2Former
        • MaskFormer
        • MobileNetV1
        • MobileNetV2
        • MobileViT
        • MobileViTV2
        • NAT
        • PoolFormer
        • Pyramid Vision Transformer (PVT)
        • RegNet
        • ResNet
        • SegFormer
        • SwiftFormer
        • Swin Transformer
        • Swin Transformer V2
        • Swin2SR
        • Table Transformer
        • TimeSformer
        • UperNet
        • VAN
        • VideoMAE
        • Vision Transformer (ViT)
        • ViT Hybrid
        • ViTDet
        • ViTMAE
        • ViTMatte
        • ViTMSN
        • ViViT
        • YOLOS
      • 🌍AUDIO MODELS
        • Audio Spectrogram Transformer
        • Bark
        • CLAP
        • EnCodec
        • Hubert
        • MCTCT
        • MMS
        • MusicGen
        • Pop2Piano
        • SEW
        • SEW-D
        • Speech2Text
        • Speech2Text2
        • SpeechT5
        • UniSpeech
        • UniSpeech-SAT
        • VITS
        • Wav2Vec2
        • Wav2Vec2-Conformer
        • Wav2Vec2Phoneme
        • WavLM
        • Whisper
        • XLS-R
        • XLSR-Wav2Vec2
      • 🌍MULTIMODAL MODELS
        • ALIGN
        • AltCLIP
        • BLIP
        • BLIP-2
        • BridgeTower
        • BROS
        • Chinese-CLIP
        • CLIP
        • CLIPSeg
        • Data2Vec
        • DePlot
        • Donut
        • FLAVA
        • GIT
        • GroupViT
        • IDEFICS
        • InstructBLIP
        • LayoutLM
        • LayoutLMV2
        • LayoutLMV3
        • LayoutXLM
        • LiLT
        • LXMERT
        • MatCha
        • MGP-STR
        • Nougat
        • OneFormer
        • OWL-ViT
        • Perceiver
        • Pix2Struct
        • Segment Anything
        • Speech Encoder Decoder Models
        • TAPAS
        • TrOCR
        • TVLT
        • ViLT
        • Vision Encoder Decoder Models
        • Vision Text Dual Encoder
        • VisualBERT
        • X-CLIP
      • 🌍REINFORCEMENT LEARNING MODELS
        • Decision Transformer
        • Trajectory Transformer
      • 🌍TIME SERIES MODELS
        • Autoformer
        • Informer
        • Time Series Transformer
      • 🌍GRAPH MODELS
        • Graphormer
  • 🌍INTERNAL HELPERS
    • Custom Layers and Utilities
    • Utilities for pipelines
    • Utilities for Tokenizers
    • Utilities for Trainer
    • Utilities for Generation
    • Utilities for Image Processors
    • Utilities for Audio processing
    • General Utilities
    • Utilities for Time Series
Powered by GitBook
On this page
  • XLNet
  • Overview
  • Documentation resources
  • XLNetConfig
  • XLNetTokenizer
  • XLNetTokenizerFast
  • XLNet specific outputs
  • XLNetModel
  • XLNetLMHeadModel
  • XLNetForSequenceClassification
  • XLNetForMultipleChoice
  • XLNetForTokenClassification
  • XLNetForQuestionAnsweringSimple
  • XLNetForQuestionAnswering
  • TFXLNetModel
  • TFXLNetLMHeadModel
  • TFXLNetForSequenceClassification
  • TFLNetForMultipleChoice
  • TFXLNetForTokenClassification
  • TFXLNetForQuestionAnsweringSimple
  1. API
  2. MODELS
  3. TEXT MODELS

XLNet

PreviousXLM-VNextYOSO

Last updated 1 year ago

XLNet

Overview

The XLNet model was proposed in 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_mask input.

  • 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_mapping input.

  • To use XLNet for sequential decoding (i.e. not in fully bi-directional setting), use the perm_mask and target_mapping inputs to control the attention span and outputs (see examples in examples/pytorch/text-generation/run_generation.py)

  • XLNet is one of the few models that has no sequence length limit.

  • XLNet is not a traditional autoregressive model but uses a training strategy that builds on that. It permutes the tokens in the sentence, then allows the model to use the last n tokens to predict the token n+1. Since this is all done with a mask, the sentence is actually fed in the model in the right order, but instead of masking the first n tokens for n+1, XLNet uses a mask that hides the previous tokens in some given permutation of 1,…,sequence length.

  • XLNet also uses the same recurrence mechanism as Transformer-XL to build long-term dependencies.

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

Documentation resources

XLNetConfig

class transformers.XLNetConfig

( vocab_size = 32000d_model = 1024n_layer = 24n_head = 16d_inner = 4096ff_activation = 'gelu'untie_r = Trueattn_type = 'bi'initializer_range = 0.02layer_norm_eps = 1e-12dropout = 0.1mem_len = 512reuse_len = Noneuse_mems_eval = Trueuse_mems_train = Falsebi_data = Falseclamp_len = -1same_length = Falsesummary_type = 'last'summary_use_proj = Truesummary_activation = 'tanh'summary_last_dropout = 0.1start_n_top = 5end_n_top = 5pad_token_id = 5bos_token_id = 1eos_token_id = 2**kwargs )

Parameters

  • 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 (str or 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.

  • 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 True during pretraining and False during 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_labels or config.hidden_size classes.

  • 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.

Examples:

Copied

>>> from transformers import XLNetConfig, XLNetModel

>>> # Initializing a XLNet configuration
>>> configuration = XLNetConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = XLNetModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

XLNetTokenizer

class transformers.XLNetTokenizer

( vocab_filedo_lower_case = Falseremove_space = Truekeep_accents = Falsebos_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>']sp_model_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = None**kwargs )

Parameters

  • 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.

    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.

    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.

    • enable_sampling: Enable subword regularization.

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

      • nbest_size = {0,1}: No sampling is performed.

      • nbest_size > 1: samples from the nbest_size results.

      • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.

    • alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.

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

build_inputs_with_special_tokens

( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs to which the special tokens will be added.

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

Returns

List[int]

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>

get_special_tokens_mask

( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = Nonealready_has_special_tokens: bool = False ) → List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs.

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

  • already_has_special_tokens (bool, optional, defaults to False) — Whether or not the token list is already formatted with special tokens for the model.

Returns

List[int]

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

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

create_token_type_ids_from_sequences

( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs.

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

Returns

List[int]

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:

Copied

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

If token_ids_1 is None, this method only returns the first portion of the mask (0s).

save_vocabulary

( save_directory: strfilename_prefix: typing.Optional[str] = None )

XLNetTokenizerFast

class transformers.XLNetTokenizerFast

( vocab_file = Nonetokenizer_file = Nonedo_lower_case = Falseremove_space = Truekeep_accents = Falsebos_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 )

Parameters

  • 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.

    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.

    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 (SentencePieceProcessor) — The SentencePiece processor that is used for every conversion (string, tokens and IDs).

build_inputs_with_special_tokens

( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs to which the special tokens will be added.

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

Returns

List[int]

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>

create_token_type_ids_from_sequences

( token_ids_0: typing.List[int]token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]

Parameters

  • token_ids_0 (List[int]) — List of IDs.

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

Returns

List[int]

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:

Copied

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

If token_ids_1 is None, this method only returns the first portion of the mask (0s).

XLNet specific outputs

class transformers.models.xlnet.modeling_xlnet.XLNetModelOutput

( last_hidden_state: FloatTensormems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • last_hidden_state (torch.FloatTensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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: typing.Optional[torch.FloatTensor] = Nonelogits: FloatTensor = Nonemems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction).

  • logits (torch.FloatTensor of shape (batch_size, num_predict, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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: typing.Optional[torch.FloatTensor] = Nonelogits: FloatTensor = Nonemems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned when label is provided) — Classification (or regression if config.num_labels==1) loss.

  • logits (torch.FloatTensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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: typing.Optional[torch.FloatTensor] = Nonelogits: FloatTensor = Nonemems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (torch.FloatTensor of shape (batch_size, num_choices)) — num_choices is the second dimension of the input tensors. (see input_ids above).

    Classification scores (before SoftMax).

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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: typing.Optional[torch.FloatTensor] = Nonelogits: FloatTensor = Nonemems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (torch.FloatTensor of 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 mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Output type of XLNetForTokenClassificationOutput.

class transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput

( loss: typing.Optional[torch.FloatTensor] = Nonestart_logits: FloatTensor = Noneend_logits: FloatTensor = Nonemems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.

  • start_logits (torch.FloatTensor of shape (batch_size, sequence_length,)) — Span-start scores (before SoftMax).

  • end_logits (torch.FloatTensor of shape (batch_size, sequence_length,)) — Span-end scores (before SoftMax).

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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: typing.Optional[torch.FloatTensor] = Nonestart_top_log_probs: typing.Optional[torch.FloatTensor] = Nonestart_top_index: typing.Optional[torch.LongTensor] = Noneend_top_log_probs: typing.Optional[torch.FloatTensor] = Noneend_top_index: typing.Optional[torch.LongTensor] = Nonecls_logits: typing.Optional[torch.FloatTensor] = Nonemems: typing.Optional[typing.List[torch.FloatTensor]] = Nonehidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Noneattentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned if both start_positions and end_positions are provided) — Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.

  • start_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top), optional, returned if start_positions or end_positions is not provided) — Log probabilities for the top config.start_n_top start token possibilities (beam-search).

  • start_top_index (torch.LongTensor of shape (batch_size, config.start_n_top), optional, returned if start_positions or end_positions is not provided) — Indices for the top config.start_n_top start token possibilities (beam-search).

  • end_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top * config.end_n_top), optional, returned if start_positions or end_positions is not provided) — Log probabilities for the top config.start_n_top * config.end_n_top end token possibilities (beam-search).

  • end_top_index (torch.LongTensor of shape (batch_size, config.start_n_top * config.end_n_top), optional, returned if start_positions or end_positions is not provided) — Indices for the top config.start_n_top * config.end_n_top end token possibilities (beam-search).

  • cls_logits (torch.FloatTensor of shape (batch_size,), optional, returned if start_positions or end_positions is not provided) — Log probabilities for the is_impossible label of the answers.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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: tf.Tensor = Nonemems: List[tf.Tensor] | None = Nonehidden_states: Tuple[tf.Tensor] | None = Noneattentions: Tuple[tf.Tensor] | None = None )

Parameters

  • last_hidden_state (tf.Tensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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: tf.Tensor | None = Nonelogits: tf.Tensor = Nonemems: List[tf.Tensor] | None = Nonehidden_states: Tuple[tf.Tensor] | None = Noneattentions: Tuple[tf.Tensor] | None = None )

Parameters

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction).

  • logits (tf.Tensor of shape (batch_size, num_predict, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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: tf.Tensor | None = Nonelogits: tf.Tensor = Nonemems: List[tf.Tensor] | None = Nonehidden_states: Tuple[tf.Tensor] | None = Noneattentions: Tuple[tf.Tensor] | None = None )

Parameters

  • loss (tf.Tensor of shape (1,), optional, returned when label is provided) — Classification (or regression if config.num_labels==1) loss.

  • logits (tf.Tensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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: tf.Tensor | None = Nonelogits: tf.Tensor = Nonemems: List[tf.Tensor] | None = Nonehidden_states: Tuple[tf.Tensor] | None = Noneattentions: Tuple[tf.Tensor] | None = None )

Parameters

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (tf.Tensor of shape (batch_size, num_choices)) — num_choices is the second dimension of the input tensors. (see input_ids above).

    Classification scores (before SoftMax).

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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: tf.Tensor | None = Nonelogits: tf.Tensor = Nonemems: List[tf.Tensor] | None = Nonehidden_states: Tuple[tf.Tensor] | None = Noneattentions: Tuple[tf.Tensor] | None = None )

Parameters

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (tf.Tensor of 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 mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Output type of TFXLNetForTokenClassificationOutput.

class transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput

( loss: tf.Tensor | None = Nonestart_logits: tf.Tensor = Noneend_logits: tf.Tensor = Nonemems: List[tf.Tensor] | None = Nonehidden_states: Tuple[tf.Tensor] | None = Noneattentions: Tuple[tf.Tensor] | None = None )

Parameters

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.

  • start_logits (tf.Tensor of shape (batch_size, sequence_length,)) — Span-start scores (before SoftMax).

  • end_logits (tf.Tensor of shape (batch_size, sequence_length,)) — Span-end scores (before SoftMax).

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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 )

Parameters

The bare XLNet Model transformer outputting raw hidden-states without any specific head on top.

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

Returns

  • last_hidden_state (torch.FloatTensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, XLNetModel
>>> import torch

>>> tokenizer = AutoTokenizer.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 )

Parameters

XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (torch.LongTensor of shape (batch_size, num_predict), optional) — Labels for masked language modeling. num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds 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 token has to be added to the input_ids (see the prepare_inputs_for_generation function and examples below)

    Indices are selected in [-100, 0, ..., config.vocab_size] All labels set to -100 are ignored, the loss is only computed for labels in [0, ..., config.vocab_size]

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) Language modeling loss (for next-token prediction).

  • logits (torch.FloatTensor of shape (batch_size, num_predict, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

Copied

>>> from transformers import AutoTokenizer, XLNetLMHeadModel
>>> import torch

>>> tokenizer = AutoTokenizer.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]

XLNetForSequenceClassification

class transformers.XLNetForSequenceClassification

( config )

Parameters

XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when label is provided) — Classification (or regression if config.num_labels==1) loss.

  • logits (torch.FloatTensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example of single-label classification:

Copied

>>> import torch
>>> from transformers import AutoTokenizer, XLNetForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
>>> model = XLNetForSequenceClassification.from_pretrained("xlnet-base-cased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_id = logits.argmax().item()

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = XLNetForSequenceClassification.from_pretrained("xlnet-base-cased", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss

Example of multi-label classification:

Copied

>>> import torch
>>> from transformers import AutoTokenizer, XLNetForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
>>> model = XLNetForSequenceClassification.from_pretrained("xlnet-base-cased", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = XLNetForSequenceClassification.from_pretrained(
...     "xlnet-base-cased", num_labels=num_labels, problem_type="multi_label_classification"
... )

>>> labels = torch.sum(
...     torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).loss

XLNetForMultipleChoice

class transformers.XLNetForMultipleChoice

( config )

Parameters

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.

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, num_choices, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, num_choices, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices-1] where num_choices is the size of the second dimension of the input tensors. (See input_ids above)

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (torch.FloatTensor of shape (batch_size, num_choices)) — num_choices is the second dimension of the input tensors. (see input_ids above).

    Classification scores (before SoftMax).

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, XLNetForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.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 )

Parameters

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.

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (torch.LongTensor of shape (batch_size,), optional) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices] where num_choices is the size of the second dimension of the input tensors. (see input_ids above)

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (torch.FloatTensor of 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 mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, XLNetForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
>>> model = XLNetForTokenClassification.from_pretrained("xlnet-base-cased")

>>> inputs = tokenizer(
...     "BOINCAI is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_token_class_ids = logits.argmax(-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]

>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss

XLNetForQuestionAnsweringSimple

class transformers.XLNetForQuestionAnsweringSimple

( config )

Parameters

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).

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • start_positions (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

  • end_positions (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.

  • start_logits (torch.FloatTensor of shape (batch_size, sequence_length,)) — Span-start scores (before SoftMax).

  • end_logits (torch.FloatTensor of shape (batch_size, sequence_length,)) — Span-end scores (before SoftMax).

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, XLNetForQuestionAnsweringSimple
>>> import torch

>>> tokenizer = AutoTokenizer.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")
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]

>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss

XLNetForQuestionAnswering

class transformers.XLNetForQuestionAnswering

( config )

Parameters

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).

forward

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • start_positions (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

  • end_positions (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

  • is_impossible (torch.LongTensor of shape (batch_size,), optional) — Labels whether a question has an answer or no answer (SQuAD 2.0)

  • cls_index (torch.LongTensor of shape (batch_size,), optional) — Labels for position (index) of the classification token to use as input for computing plausibility of the answer.

  • p_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Optional mask of tokens which can’t be in answers (e.g. [CLS], [PAD], …). 1.0 means token should be masked. 0.0 mean token is not masked.

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned if both start_positions and end_positions are provided) — Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.

  • start_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top), optional, returned if start_positions or end_positions is not provided) — Log probabilities for the top config.start_n_top start token possibilities (beam-search).

  • start_top_index (torch.LongTensor of shape (batch_size, config.start_n_top), optional, returned if start_positions or end_positions is not provided) — Indices for the top config.start_n_top start token possibilities (beam-search).

  • end_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top * config.end_n_top), optional, returned if start_positions or end_positions is not provided) — Log probabilities for the top config.start_n_top * config.end_n_top end token possibilities (beam-search).

  • end_top_index (torch.LongTensor of shape (batch_size, config.start_n_top * config.end_n_top), optional, returned if start_positions or end_positions is not provided) — Indices for the top config.start_n_top * config.end_n_top end token possibilities (beam-search).

  • cls_logits (torch.FloatTensor of shape (batch_size,), optional, returned if start_positions or end_positions is not provided) — Log probabilities for the is_impossible label of the answers.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, XLNetForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.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

TFXLNetModel

class transformers.TFXLNetModel

( *args**kwargs )

Parameters

The bare XLNet Model transformer outputting raw hidden-states without any specific head on top.

TensorFlow models and layers in transformers accept two formats as input:

  • having all inputs as keyword arguments (like PyTorch models), or

  • having all inputs as a list, tuple or dict in the first positional argument.

The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like model.fit() things should “just work” for you - just pass your inputs and labels in any format that model.fit() supports! If, however, you want to use the second format outside of Keras methods like fit() and predict(), such as when creating your own layers or models with the Keras Functional API, there are three possibilities you can use to gather all the input Tensors in the first positional argument:

  • a single Tensor with input_ids only and nothing else: model(input_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})

call

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

Returns

  • last_hidden_state (tf.Tensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, TFXLNetModel
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.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_state

TFXLNetLMHeadModel

class transformers.TFXLNetLMHeadModel

( *args**kwargs )

Parameters

XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).

TensorFlow models and layers in transformers accept two formats as input:

  • having all inputs as keyword arguments (like PyTorch models), or

  • having all inputs as a list, tuple or dict in the first positional argument.

The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like model.fit() things should “just work” for you - just pass your inputs and labels in any format that model.fit() supports! If, however, you want to use the second format outside of Keras methods like fit() and predict(), such as when creating your own layers or models with the Keras Functional API, there are three possibilities you can use to gather all the input Tensors in the first positional argument:

  • a single Tensor with input_ids only and nothing else: model(input_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})

call

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — Labels for computing the cross entropy classification loss. Indices should be in [0, ..., config.vocab_size - 1].

Returns

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) Language modeling loss (for next-token prediction).

  • logits (tf.Tensor of shape (batch_size, num_predict, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

Copied

>>> import tensorflow as tf
>>> import numpy as np
>>> from transformers import AutoTokenizer, TFXLNetLMHeadModel

>>> tokenizer = AutoTokenizer.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]

TFXLNetForSequenceClassification

class transformers.TFXLNetForSequenceClassification

( *args**kwargs )

Parameters

XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.

TensorFlow models and layers in transformers accept two formats as input:

  • having all inputs as keyword arguments (like PyTorch models), or

  • having all inputs as a list, tuple or dict in the first positional argument.

The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like model.fit() things should “just work” for you - just pass your inputs and labels in any format that model.fit() supports! If, however, you want to use the second format outside of Keras methods like fit() and predict(), such as when creating your own layers or models with the Keras Functional API, there are three possibilities you can use to gather all the input Tensors in the first positional argument:

  • a single Tensor with input_ids only and nothing else: model(input_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})

call

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (tf.Tensor of shape (batch_size,), optional) — Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

Returns

  • loss (tf.Tensor of shape (1,), optional, returned when label is provided) — Classification (or regression if config.num_labels==1) loss.

  • logits (tf.Tensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, TFXLNetForSequenceClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
>>> model = TFXLNetForSequenceClassification.from_pretrained("xlnet-base-cased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")

>>> logits = model(**inputs).logits

>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])

Copied

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = TFXLNetForSequenceClassification.from_pretrained("xlnet-base-cased", num_labels=num_labels)

>>> labels = tf.constant(1)
>>> loss = model(**inputs, labels=labels).loss

TFLNetForMultipleChoice

class transformers.TFXLNetForMultipleChoice

( *args**kwargs )

Parameters

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.

TensorFlow models and layers in transformers accept two formats as input:

  • having all inputs as keyword arguments (like PyTorch models), or

  • having all inputs as a list, tuple or dict in the first positional argument.

The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like model.fit() things should “just work” for you - just pass your inputs and labels in any format that model.fit() supports! If, however, you want to use the second format outside of Keras methods like fit() and predict(), such as when creating your own layers or models with the Keras Functional API, there are three possibilities you can use to gather all the input Tensors in the first positional argument:

  • a single Tensor with input_ids only and nothing else: model(input_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})

call

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, num_choices, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, num_choices, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (tf.Tensor of shape (batch_size,), optional) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices] where num_choices is the size of the second dimension of the input tensors. (See input_ids above)

Returns

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (tf.Tensor of shape (batch_size, num_choices)) — num_choices is the second dimension of the input tensors. (see input_ids above).

    Classification scores (before SoftMax).

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, TFXLNetForMultipleChoice
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.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 )

Parameters

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.

TensorFlow models and layers in transformers accept two formats as input:

  • having all inputs as keyword arguments (like PyTorch models), or

  • having all inputs as a list, tuple or dict in the first positional argument.

The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like model.fit() things should “just work” for you - just pass your inputs and labels in any format that model.fit() supports! If, however, you want to use the second format outside of Keras methods like fit() and predict(), such as when creating your own layers or models with the Keras Functional API, there are three possibilities you can use to gather all the input Tensors in the first positional argument:

  • a single Tensor with input_ids only and nothing else: model(input_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})

call

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — Labels for computing the token classification loss. Indices should be in [0, ..., config.num_labels - 1].

Returns

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Classification loss.

  • logits (tf.Tensor of 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 mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, TFXLNetForTokenClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
>>> model = TFXLNetForTokenClassification.from_pretrained("xlnet-base-cased")

>>> inputs = tokenizer(
...     "BOINCAI is a company based in Paris and New York", add_special_tokens=False, return_tensors="tf"
... )

>>> logits = model(**inputs).logits
>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]

Copied

>>> labels = predicted_token_class_ids
>>> loss = tf.math.reduce_mean(model(**inputs, labels=labels).loss)

TFXLNetForQuestionAnsweringSimple

class transformers.TFXLNetForQuestionAnsweringSimple

( *args**kwargs )

Parameters

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).

TensorFlow models and layers in transformers accept two formats as input:

  • having all inputs as keyword arguments (like PyTorch models), or

  • having all inputs as a list, tuple or dict in the first positional argument.

The reason the second format is supported is that Keras methods prefer this format when passing inputs to models and layers. Because of this support, when using methods like model.fit() things should “just work” for you - just pass your inputs and labels in any format that model.fit() supports! If, however, you want to use the second format outside of Keras methods like fit() and predict(), such as when creating your own layers or models with the Keras Functional API, there are three possibilities you can use to gather all the input Tensors in the first positional argument:

  • a single Tensor with input_ids only and nothing else: model(input_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})

call

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output 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_ids as they have already been computed.

    use_mems has to be set to True to make use of mems.

  • perm_mask (torch.FloatTensor of 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.FloatTensor of 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.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

  • input_mask (torch.FloatTensor of 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_mask and attention_mask.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • start_positions (tf.Tensor of shape (batch_size,), optional) — Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

  • end_positions (tf.Tensor of shape (batch_size,), optional) — Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

Returns

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.

  • start_logits (tf.Tensor of shape (batch_size, sequence_length,)) — Span-start scores (before SoftMax).

  • end_logits (tf.Tensor of shape (batch_size, sequence_length,)) — Span-end scores (before SoftMax).

  • mems (List[tf.Tensor] of length config.n_layers) — Contains pre-computed hidden-states. Can be used (see mems input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is 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=True is 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.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Example:

Copied

>>> from transformers import AutoTokenizer, TFXLNetForQuestionAnsweringSimple
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
>>> model = TFXLNetForQuestionAnsweringSimple.from_pretrained("xlnet-base-cased")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

>>> inputs = tokenizer(question, text, return_tensors="tf")
>>> outputs = model(**inputs)

>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]

Copied

>>> # target is "nice puppet"
>>> target_start_index = tf.constant([14])
>>> target_end_index = tf.constant([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = tf.math.reduce_mean(outputs.loss)

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_ids passed when calling or .

mem_len (int or 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 for more information.

For pretraining, it is recommended to set use_mems_train to True. For fine-tuning, it is recommended to set use_mems_train to False as discussed . If use_mems_train is 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.

This is the configuration class to store the configuration of a or a . 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 architecture.

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

vocab_file (str) — file (generally has a .spm extension) that contains the vocabulary necessary to instantiate a tokenizer.

sp_model_kwargs (dict, optional) — Will be passed to the SentencePieceProcessor.__init__() method. The can be used, among other things, to set:

Construct an XLNet tokenizer. Based on .

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

List of with the appropriate special tokens.

List of according to the given sequence(s).

vocab_file (str) — file (generally has a .spm extension) that contains the vocabulary necessary to instantiate a tokenizer.

Construct a “fast” XLNet tokenizer (backed by BOINCAI’s tokenizers library). Based on .

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

List of with the appropriate special tokens.

List of according to the given sequence(s).

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

Output type of .

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonestart_positions: typing.Optional[torch.Tensor] = Noneend_positions: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonemems: typing.Optional[torch.Tensor] = Noneperm_mask: typing.Optional[torch.Tensor] = Nonetarget_mapping: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneinput_mask: typing.Optional[torch.Tensor] = Nonehead_mask: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonestart_positions: typing.Optional[torch.Tensor] = Noneend_positions: typing.Optional[torch.Tensor] = Noneis_impossible: typing.Optional[torch.Tensor] = Nonecls_index: typing.Optional[torch.Tensor] = Nonep_mask: typing.Optional[torch.Tensor] = Noneuse_mems: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None**kwargs ) → or tuple(torch.FloatTensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 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 that when creating models and layers with then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonemems: np.ndarray | tf.Tensor | None = Noneperm_mask: np.ndarray | tf.Tensor | None = Nonetarget_mapping: np.ndarray | tf.Tensor | None = Nonetoken_type_ids: np.ndarray | tf.Tensor | None = Noneinput_mask: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Noneinputs_embeds: np.ndarray | tf.Tensor | None = Noneuse_mems: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False ) → or tuple(tf.Tensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(tf.Tensor)

A or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 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 that when creating models and layers with then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonemems: np.ndarray | tf.Tensor | None = Noneperm_mask: np.ndarray | tf.Tensor | None = Nonetarget_mapping: np.ndarray | tf.Tensor | None = Nonetoken_type_ids: np.ndarray | tf.Tensor | None = Noneinput_mask: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Noneinputs_embeds: np.ndarray | tf.Tensor | None = Noneuse_mems: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonelabels: np.ndarray | tf.Tensor | None = Nonetraining: bool = False ) → or tuple(tf.Tensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(tf.Tensor)

A or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 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 that when creating models and layers with then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonemems: np.ndarray | tf.Tensor | None = Noneperm_mask: np.ndarray | tf.Tensor | None = Nonetarget_mapping: np.ndarray | tf.Tensor | None = Nonetoken_type_ids: np.ndarray | tf.Tensor | None = Noneinput_mask: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Noneinputs_embeds: np.ndarray | tf.Tensor | None = Noneuse_mems: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonelabels: np.ndarray | tf.Tensor | None = Nonetraining: bool = False ) → or tuple(tf.Tensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(tf.Tensor)

A or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 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 that when creating models and layers with then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!

( input_ids: TFModelInputType | None = Nonetoken_type_ids: np.ndarray | tf.Tensor | None = Noneinput_mask: np.ndarray | tf.Tensor | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonemems: np.ndarray | tf.Tensor | None = Noneperm_mask: np.ndarray | tf.Tensor | None = Nonetarget_mapping: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Noneinputs_embeds: np.ndarray | tf.Tensor | None = Noneuse_mems: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonelabels: np.ndarray | tf.Tensor | None = Nonetraining: bool = False ) → or tuple(tf.Tensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(tf.Tensor)

A or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 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 that when creating models and layers with then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonemems: np.ndarray | tf.Tensor | None = Noneperm_mask: np.ndarray | tf.Tensor | None = Nonetarget_mapping: np.ndarray | tf.Tensor | None = Nonetoken_type_ids: np.ndarray | tf.Tensor | None = Noneinput_mask: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Noneinputs_embeds: np.ndarray | tf.Tensor | None = Noneuse_mems: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonelabels: np.ndarray | tf.Tensor | None = Nonetraining: bool = False ) → or tuple(tf.Tensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(tf.Tensor)

A or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — 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 method to load the model weights.

This model inherits from . 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 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 that when creating models and layers with then you don’t need to worry about any of this, as you can just pass inputs like you would to any other Python function!

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonemems: np.ndarray | tf.Tensor | None = Noneperm_mask: np.ndarray | tf.Tensor | None = Nonetarget_mapping: np.ndarray | tf.Tensor | None = Nonetoken_type_ids: np.ndarray | tf.Tensor | None = Noneinput_mask: np.ndarray | tf.Tensor | None = Nonehead_mask: np.ndarray | tf.Tensor | None = Noneinputs_embeds: np.ndarray | tf.Tensor | None = Noneuse_mems: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonestart_positions: np.ndarray | tf.Tensor | None = Noneend_positions: np.ndarray | tf.Tensor | None = Nonetraining: bool = False ) → or tuple(tf.Tensor)

Indices can be obtained using . See and for details.

return_dict (bool, optional) — Whether or not to return a instead of a plain tuple.

or tuple(tf.Tensor)

A or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

🌍
🌍
🌍
Text classification task guide
Token classification task guide
Question answering task guide
Causal language modeling task guide
Multiple choice task guide
<source>
XLNetModel
TFXLNetModel
quickstart
here
XLNetModel
TFXLNetModel
xlnet-large-cased
PretrainedConfig
PretrainedConfig
<source>
SentencePiece
Python wrapper for SentencePiece
SentencePiece
PreTrainedTokenizer
<source>
input IDs
<source>
<source>
token type IDs
<source>
<source>
SentencePiece
Unigram
PreTrainedTokenizerFast
<source>
input IDs
<source>
token type IDs
<source>
XLNetModel
<source>
XLNetLMHeadModel
<source>
XLNetForSequenceClassification
<source>
XLNetForMultipleChoice
<source>
<source>
XLNetForQuestionAnsweringSimple
<source>
XLNetForQuestionAnswering
<source>
TFXLNetModel
<source>
TFXLNetLMHeadModel
<source>
TFXLNetForSequenceClassification
<source>
TFXLNetForMultipleChoice
<source>
<source>
TFXLNetForQuestionAnsweringSimple
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetModelOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetModelOutput
XLNetConfig
XLNetModel
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutput
XLNetConfig
XLNetLMHeadModel
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutput
transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutput
XLNetConfig
XLNetForSequenceClassification
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutput
transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutput
XLNetConfig
XLNetForMultipleChoice
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutput
transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutput
XLNetConfig
XLNetForTokenClassification
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput
transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput
XLNetConfig
XLNetForQuestionAnsweringSimple
<source>
XLNetConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutput
transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutput
XLNetConfig
XLNetForQuestionAnswering
<source>
XLNetConfig
from_pretrained()
TFPreTrainedModel
tf.keras.Model
subclassing
<source>
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput
XLNetConfig
TFXLNetModel
<source>
XLNetConfig
from_pretrained()
TFPreTrainedModel
tf.keras.Model
subclassing
<source>
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput
XLNetConfig
TFXLNetLMHeadModel
<source>
XLNetConfig
from_pretrained()
TFPreTrainedModel
tf.keras.Model
subclassing
<source>
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput
XLNetConfig
TFXLNetForSequenceClassification
<source>
XLNetConfig
from_pretrained()
TFPreTrainedModel
tf.keras.Model
subclassing
<source>
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutput
XLNetConfig
TFXLNetForMultipleChoice
<source>
XLNetConfig
from_pretrained()
TFPreTrainedModel
tf.keras.Model
subclassing
<source>
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput
XLNetConfig
TFXLNetForTokenClassification
<source>
XLNetConfig
from_pretrained()
TFPreTrainedModel
tf.keras.Model
subclassing
<source>
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
What are token type IDs?
ModelOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput
transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput
XLNetConfig
TFXLNetForQuestionAnsweringSimple
XLNet: Generalized Autoregressive Pretraining for Language Understanding
thomwolf
here