Transformer XL

[![Models](https://img.shields.io/badge/All_model_pages-transfo--xl-blueviolet)](https://huggingface.co/models?filter=transfo-xl) [![Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/docs-demos/transfo-xl-wt103)

## [](#overview)Overview

The Transformer-XL model was proposed in [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) by Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov. It’s a causal (uni-directional) transformer with relative positioning (sinusoïdal) embeddings which can reuse previously computed hidden-states to attend to longer context (memory). This model also uses adaptive softmax inputs and outputs (tied).

The abstract from the paper is the following:

_Transformers have a potential of learning longer-term dependency, but are limited by a fixed-length context in the setting of language modeling. We propose a novel neural architecture Transformer-XL that enables learning dependency beyond a fixed length without disrupting temporal coherence. It consists of a segment-level recurrence mechanism and a novel positional encoding scheme. Our method not only enables capturing longer-term dependency, but also resolves the context fragmentation problem. As a result, Transformer-XL learns dependency that is 80% longer than RNNs and 450% longer than vanilla Transformers, achieves better performance on both short and long sequences, and is up to 1,800+ times faster than vanilla Transformers during evaluation. Notably, we improve the state-of-the-art results of bpc/perplexity to 0.99 on enwiki8, 1.08 on text8, 18.3 on WikiText-103, 21.8 on One Billion Word, and 54.5 on Penn Treebank (without finetuning). When trained only on WikiText-103, Transformer-XL manages to generate reasonably coherent, novel text articles with thousands of tokens._

Tips:

-   Transformer-XL uses relative sinusoidal positional embeddings. Padding can be done on the left or on the right. The original implementation trains on SQuAD with padding on the left, therefore the padding defaults are set to left.
-   Transformer-XL is one of the few models that has no sequence length limit.
-   Same as a regular GPT model, but introduces a recurrence mechanism for two consecutive segments (similar to a regular RNNs with two consecutive inputs). In this context, a segment is a number of consecutive tokens (for instance 512) that may span across multiple documents, and segments are fed in order to the model.
-   Basically, the hidden states of the previous segment are concatenated to the current input to compute the attention scores. This allows the model to pay attention to information that was in the previous segment as well as the current one. By stacking multiple attention layers, the receptive field can be increased to multiple previous segments.
-   This changes the positional embeddings to positional relative embeddings (as the regular positional embeddings would give the same results in the current input and the current hidden state at a given position) and needs to make some adjustments in the way attention scores are computed.

This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://github.com/kimiyoung/transformer-xl).

TransformerXL does **not** work with _torch.nn.DataParallel_ due to a bug in PyTorch, see [issue #36035](https://github.com/pytorch/pytorch/issues/36035)

## [](#documentation-resources)Documentation resources

-   [Text classification task guide](../tasks/sequence_classification)
-   [Causal language modeling task guide](../tasks/language_modeling)

## [](#transformers.TransfoXLConfig)TransfoXLConfig

### class transformers.TransfoXLConfig

[](#transformers.TransfoXLConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/configuration_transfo_xl.py#L29)

( vocab\_size = 267735cutoffs = \[20000, 40000, 200000\]d\_model = 1024d\_embed = 1024n\_head = 16d\_head = 64d\_inner = 4096div\_val = 4pre\_lnorm = Falsen\_layer = 18mem\_len = 1600clamp\_len = 1000same\_length = Trueproj\_share\_all\_but\_first = Trueattn\_type = 0sample\_softmax = -1adaptive = Truedropout = 0.1dropatt = 0.0untie\_r = Trueinit = 'normal'init\_range = 0.01proj\_init\_std = 0.01init\_std = 0.02layer\_norm\_epsilon = 1e-05eos\_token\_id = 0\*\*kwargs )

This is the configuration class to store the configuration of a [TransfoXLModel](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLModel) or a [TFTransfoXLModel](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TFTransfoXLModel). It is used to instantiate a Transformer-XL 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 TransfoXL [transfo-xl-wt103](https://huggingface.co/transfo-xl-wt103) architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/v4.30.0/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Examples:

```
>>> from transformers import TransfoXLConfig, TransfoXLModel

>>> 
>>> configuration = TransfoXLConfig()

>>> 
>>> model = TransfoXLModel(configuration)

>>> 
>>> configuration = model.config```

## [](#transformers.TransfoXLTokenizer)TransfoXLTokenizer

### class transformers.TransfoXLTokenizer

[](#transformers.TransfoXLTokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/tokenization_transfo_xl.py#L123)

( special = Nonemin\_freq = 0max\_size = Nonelower\_case = Falsedelimiter = Nonevocab\_file = Nonepretrained\_vocab\_file: str = Nonenever\_split = Noneunk\_token = '<unk>'eos\_token = '<eos>'additional\_special\_tokens = \['<formula>'\]language = 'en'\*\*kwargs )

Construct a Transformer-XL tokenizer adapted from Vocab class in [the original code](https://github.com/kimiyoung/transformer-xl). The Transformer-XL tokenizer is a word-level tokenizer (no sub-word tokenization).

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### save\_vocabulary

[](#transformers.TransfoXLTokenizer.save_vocabulary)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/tokenization_transfo_xl.py#L310)

( save\_directory: strfilename\_prefix: typing.Optional\[str\] = None )

## [](#transformers.models.transfo_xl.modeling_transfo_xl.TransfoXLModelOutput)TransfoXL specific outputs

### class transformers.models.transfo\_xl.modeling\_transfo\_xl.TransfoXLModelOutput

[](#transformers.models.transfo_xl.modeling_transfo_xl.TransfoXLModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L600)

( last\_hidden\_state: FloatTensormems: typing.List\[torch.FloatTensor\] = Nonehidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Noneattentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = None )

Base class for model’s outputs that may also contain a past key/values (to speed up sequential decoding).

### class transformers.models.transfo\_xl.modeling\_transfo\_xl.TransfoXLLMHeadModelOutput

[](#transformers.models.transfo_xl.modeling_transfo_xl.TransfoXLLMHeadModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L665)

( losses: typing.Optional\[torch.FloatTensor\] = Noneprediction\_scores: FloatTensor = Nonemems: typing.List\[torch.FloatTensor\] = Nonehidden\_states: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Noneattentions: typing.Optional\[typing.Tuple\[torch.FloatTensor\]\] = Noneloss: typing.Optional\[torch.FloatTensor\] = None )

Base class for model’s outputs that may also contain a past key/values (to speed up sequential decoding).

### class transformers.models.transfo\_xl.modeling\_tf\_transfo\_xl.TFTransfoXLModelOutput

[](#transformers.models.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L689)

( last\_hidden\_state: tf.Tensor = Nonemems: List\[tf.Tensor\] = Nonehidden\_states: Tuple\[tf.Tensor\] | None = Noneattentions: Tuple\[tf.Tensor\] | None = None )

Base class for model’s outputs that may also contain a past key/values (to speed up sequential decoding).

### class transformers.models.transfo\_xl.modeling\_tf\_transfo\_xl.TFTransfoXLLMHeadModelOutput

[](#transformers.models.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLLMHeadModelOutput)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L720)

( prediction\_scores: tf.Tensor = Nonemems: List\[tf.Tensor\] = Nonehidden\_states: Tuple\[tf.Tensor\] | None = Noneattentions: Tuple\[tf.Tensor\] | None = None )

Base class for model’s outputs that may also contain a past key/values (to speed up sequential decoding).

## [](#transformers.TransfoXLModel)TransfoXLModel

### class transformers.TransfoXLModel

[](#transformers.TransfoXLModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L764)

( config )

Parameters

-   [](#transformers.TransfoXLModel.config)**config** ([TransfoXLConfig](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

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

This model inherits from [PreTrainedModel](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.TransfoXLModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L867)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonemems: typing.Optional\[typing.List\[torch.FloatTensor\]\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.transfo\_xl.modeling\_transfo\_xl.TransfoXLModelOutput](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.models.transfo_xl.modeling_transfo_xl.TransfoXLModelOutput) or `tuple(torch.FloatTensor)`

The [TransfoXLModel](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLModel) forward method, overrides the `__call__` special method.

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:

```
>>> from transformers import AutoTokenizer, TransfoXLModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TransfoXLModel.from_pretrained("transfo-xl-wt103")

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

>>> last_hidden_states = outputs.last_hidden_state```

## [](#transformers.TransfoXLLMHeadModel)TransfoXLLMHeadModel

### class transformers.TransfoXLLMHeadModel

[](#transformers.TransfoXLLMHeadModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L1004)

( config )

Parameters

-   [](#transformers.TransfoXLLMHeadModel.config)**config** ([TransfoXLConfig](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive input embeddings)

This model inherits from [PreTrainedModel](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.TransfoXLLMHeadModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L1060)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonemems: typing.Optional\[typing.List\[torch.FloatTensor\]\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Nonelabels: typing.Optional\[torch.LongTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.models.transfo\_xl.modeling\_transfo\_xl.TransfoXLLMHeadModelOutput](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.models.transfo_xl.modeling_transfo_xl.TransfoXLLMHeadModelOutput) or `tuple(torch.FloatTensor)`

The [TransfoXLLMHeadModel](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLLMHeadModel) forward method, overrides the `__call__` special method.

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:

```
>>> import torch
>>> from transformers import AutoTokenizer, TransfoXLLMHeadModel

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs.logits```

## [](#transformers.TransfoXLForSequenceClassification)TransfoXLForSequenceClassification

### class transformers.TransfoXLForSequenceClassification

[](#transformers.TransfoXLForSequenceClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L1192)

( config )

Parameters

-   [](#transformers.TransfoXLForSequenceClassification.config)**config** ([TransfoXLConfig](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Transformer-XL Model transformer with a sequence classification head on top (linear layer).

[TransfoXLForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLForSequenceClassification) uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do.

Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch).

This model inherits from [PreTrainedModel](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.TransfoXLForSequenceClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L1203)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonemems: typing.Optional\[typing.List\[torch.FloatTensor\]\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Nonelabels: typing.Optional\[torch.LongTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → `transformers.models.transfo_xl.modeling_transfo_xl.TransfoXLSequenceClassifierOutputWithPast` or `tuple(torch.FloatTensor)`

The [TransfoXLForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLForSequenceClassification) forward method, overrides the `__call__` special method.

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:

```
>>> import torch
>>> from transformers import AutoTokenizer, TransfoXLForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TransfoXLForSequenceClassification.from_pretrained("transfo-xl-wt103")

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

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

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

>>> 
>>> num_labels = len(model.config.id2label)
>>> model = TransfoXLForSequenceClassification.from_pretrained("transfo-xl-wt103", num_labels=num_labels)

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

Example of multi-label classification:

```
>>> import torch
>>> from transformers import AutoTokenizer, TransfoXLForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TransfoXLForSequenceClassification.from_pretrained("transfo-xl-wt103", 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]

>>> 
>>> num_labels = len(model.config.id2label)
>>> model = TransfoXLForSequenceClassification.from_pretrained(
...     "transfo-xl-wt103", 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```

## [](#transformers.TFTransfoXLModel)TFTransfoXLModel

### class transformers.TFTransfoXLModel

[](#transformers.TFTransfoXLModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L871)

( \*args\*\*kwargs )

Parameters

-   [](#transformers.TFTransfoXLModel.config)**config** ([TransfoXLConfig](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

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

This model inherits from [TFPreTrainedModel](/docs/transformers/v4.30.0/en/main_classes/model#transformers.TFPreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.

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})`

Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) 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!

#### call

[](#transformers.TFTransfoXLModel.call)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L876)

( input\_ids: TFModelInputType | None = Nonemems: List\[tf.Tensor\] | None = Nonehead\_mask: np.ndarray | tf.Tensor | None = Noneinputs\_embeds: np.ndarray | tf.Tensor | None = Noneoutput\_attentions: Optional\[bool\] = Noneoutput\_hidden\_states: Optional\[bool\] = Nonereturn\_dict: Optional\[bool\] = Nonetraining: bool = False ) → [transformers.models.transfo\_xl.modeling\_tf\_transfo\_xl.TFTransfoXLModelOutput](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.models.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLModelOutput) or `tuple(tf.Tensor)`

The [TFTransfoXLModel](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TFTransfoXLModel) forward method, overrides the `__call__` special method.

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:

```
>>> from transformers import AutoTokenizer, TFTransfoXLModel
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TFTransfoXLModel.from_pretrained("transfo-xl-wt103")

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

>>> last_hidden_states = outputs.last_hidden_state```

## [](#transformers.TFTransfoXLLMHeadModel)TFTransfoXLLMHeadModel

### class transformers.TFTransfoXLLMHeadModel

[](#transformers.TFTransfoXLLMHeadModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L915)

( \*args\*\*kwargs )

Parameters

-   [](#transformers.TFTransfoXLLMHeadModel.config)**config** ([TransfoXLConfig](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive input embeddings)

This model inherits from [TFPreTrainedModel](/docs/transformers/v4.30.0/en/main_classes/model#transformers.TFPreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.

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})`

Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) 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!

#### call

[](#transformers.TFTransfoXLLMHeadModel.call)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L944)

( input\_ids: TFModelInputType | None = Nonemems: List\[tf.Tensor\] | None = Nonehead\_mask: np.ndarray | tf.Tensor | None = Noneinputs\_embeds: np.ndarray | tf.Tensor | None = Noneoutput\_attentions: Optional\[bool\] = Noneoutput\_hidden\_states: Optional\[bool\] = Nonereturn\_dict: Optional\[bool\] = Nonelabels: np.ndarray | tf.Tensor | None = Nonetraining: bool = False ) → [transformers.models.transfo\_xl.modeling\_tf\_transfo\_xl.TFTransfoXLLMHeadModelOutput](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.models.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLLMHeadModelOutput) or `tuple(tf.Tensor)`

The [TFTransfoXLLMHeadModel](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TFTransfoXLLMHeadModel) forward method, overrides the `__call__` special method.

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:

```
>>> from transformers import AutoTokenizer, TFTransfoXLLMHeadModel
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> logits = outputs.logits```

## [](#transformers.TFTransfoXLForSequenceClassification)TFTransfoXLForSequenceClassification

### class transformers.TFTransfoXLForSequenceClassification

[](#transformers.TFTransfoXLForSequenceClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L1022)

( \*args\*\*kwargs )

Parameters

-   [](#transformers.TFTransfoXLForSequenceClassification.config)**config** ([TransfoXLConfig](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TransfoXLConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Transfo XL Model transformer with a sequence classification head on top (linear layer).

[TFTransfoXLForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TFTransfoXLForSequenceClassification) uses the last token in order to do the classification, as other causal models (e.g. GPT-1,GPT-2) do.

Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch).

This model inherits from [TFPreTrainedModel](/docs/transformers/v4.30.0/en/main_classes/model#transformers.TFPreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.

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})`

Note that when creating models and layers with [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) 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!

#### call

[](#transformers.TFTransfoXLForSequenceClassification.call)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L1037)

( input\_ids: TFModelInputType | None = Nonemems: List\[tf.Tensor\] | None = Nonehead\_mask: np.ndarray | tf.Tensor | None = Noneinputs\_embeds: np.ndarray | tf.Tensor | None = Noneoutput\_attentions: Optional\[bool\] = Noneoutput\_hidden\_states: Optional\[bool\] = Nonereturn\_dict: Optional\[bool\] = Nonelabels: np.ndarray | tf.Tensor | None = Nonetraining: Optional\[bool\] = False ) → `transformers.models.transfo_xl.modeling_tf_transfo_xl.TFTransfoXLSequenceClassifierOutputWithPast` or `tuple(tf.Tensor)`

The [TFTransfoXLForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/transfo-xl#transformers.TFTransfoXLForSequenceClassification) forward method, overrides the `__call__` special method.

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:

```
>>> from transformers import AutoTokenizer, TFTransfoXLForSequenceClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("transfo-xl-wt103")
>>> model = TFTransfoXLForSequenceClassification.from_pretrained("transfo-xl-wt103")

>>> 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])```

```
>>> 
>>> num_labels = len(model.config.id2label)
>>> model = TFTransfoXLForSequenceClassification.from_pretrained("transfo-xl-wt103", num_labels=num_labels)

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

## [](#transformers.AdaptiveEmbedding)Internal Layers

### class transformers.AdaptiveEmbedding

[](#transformers.AdaptiveEmbedding)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_transfo_xl.py#L399)

( n\_tokend\_embedd\_projcutoffsdiv\_val = 1sample\_softmax = False )

### class transformers.TFAdaptiveEmbedding

[](#transformers.TFAdaptiveEmbedding)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py#L344)

( \*args\*\*kwargs )