---
local: openai-gpt2
sections:
- local: overview
  title: Overview
- local: transformers.GPT2Config
  title: GPT2Config
- local: transformers.GPT2Tokenizer
  title: GPT2Tokenizer
- local: transformers.GPT2TokenizerFast
  title: GPT2TokenizerFast
- local: transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput
  title: GPT2 specific outputs
- local: transformers.GPT2Model
  title: GPT2Model
- local: transformers.GPT2LMHeadModel
  title: GPT2LMHeadModel
- local: transformers.GPT2DoubleHeadsModel
  title: GPT2DoubleHeadsModel
- local: transformers.GPT2ForSequenceClassification
  title: GPT2ForSequenceClassification
- local: transformers.GPT2ForTokenClassification
  title: GPT2ForTokenClassification
- local: transformers.TFGPT2Model
  title: TFGPT2Model
- local: transformers.TFGPT2LMHeadModel
  title: TFGPT2LMHeadModel
- local: transformers.TFGPT2DoubleHeadsModel
  title: TFGPT2DoubleHeadsModel
- local: transformers.TFGPT2ForSequenceClassification
  title: TFGPT2ForSequenceClassification
- local: transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast
  title: TFSequenceClassifierOutputWithPast
- local: transformers.FlaxGPT2Model
  title: FlaxGPT2Model
- local: transformers.FlaxGPT2LMHeadModel
  title: FlaxGPT2LMHeadModel
title: OpenAI GPT2
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2020 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="openai-gpt2">OpenAI GPT2</h1>

<h2 id="overview">Overview</h2>

OpenAI GPT-2 model was proposed in [Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) by Alec
Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever. It's a causal (unidirectional)
transformer pretrained using language modeling on a very large corpus of ~40 GB of text data.

The abstract from the paper is the following:

*GPT-2 is a large transformer-based language model with 1.5 billion parameters, trained on a dataset[1] of 8 million
web pages. GPT-2 is trained with a simple objective: predict the next word, given all of the previous words within some
text. The diversity of the dataset causes this simple goal to contain naturally occurring demonstrations of many tasks
across diverse domains. GPT-2 is a direct scale-up of GPT, with more than 10X the parameters and trained on more than
10X the amount of data.*

Tips:

- GPT-2 is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than
  the left.
- GPT-2 was trained with a causal language modeling (CLM) objective and is therefore powerful at predicting the next
  token in a sequence. Leveraging this feature allows GPT-2 to generate syntactically coherent text as it can be
  observed in the *run_generation.py* example script.
- The model can take the *past_key_values* (for PyTorch) or *past* (for TF) as input, which is the previously computed
  key/value attention pairs. Using this (*past_key_values* or *past*) value prevents the model from re-computing
  pre-computed values in the context of text generation. For PyTorch, see *past_key_values* argument of the
  [GPT2Model.forward()](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Model.forward) method, or for TF the *past* argument of the
  [TFGPT2Model.call()](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2Model.call) method for more information on its usage.
- Enabling the *scale_attn_by_inverse_layer_idx* and *reorder_and_upcast_attn* flags will apply the training stability
  improvements from [Mistral](https://github.com/stanford-crfm/mistral/) (for PyTorch only).

[Write With Transformer](https://transformer.huggingface.co/doc/gpt2-large) is a webapp created and hosted by
Hugging Face showcasing the generative capabilities of several models. GPT-2 is one of them and is available in five
different sizes: small, medium, large, xl and a distilled version of the small checkpoint: *distilgpt-2*.

This model was contributed by [thomwolf](https://huggingface.co/thomwolf). The original code can be found [here](https://openai.com/blog/better-language-models/).


<h2 id="transformers.GPT2Config">GPT2Config</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2Config</name><anchor>transformers.GPT2Config</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/configuration_gpt2.py#L38</source><parameters>[{"name": "vocab_size", "val": " = 50257"}, {"name": "n_positions", "val": " = 1024"}, {"name": "n_embd", "val": " = 768"}, {"name": "n_layer", "val": " = 12"}, {"name": "n_head", "val": " = 12"}, {"name": "n_inner", "val": " = None"}, {"name": "activation_function", "val": " = 'gelu_new'"}, {"name": "resid_pdrop", "val": " = 0.1"}, {"name": "embd_pdrop", "val": " = 0.1"}, {"name": "attn_pdrop", "val": " = 0.1"}, {"name": "layer_norm_epsilon", "val": " = 1e-05"}, {"name": "initializer_range", "val": " = 0.02"}, {"name": "summary_type", "val": " = 'cls_index'"}, {"name": "summary_use_proj", "val": " = True"}, {"name": "summary_activation", "val": " = None"}, {"name": "summary_proj_to_labels", "val": " = True"}, {"name": "summary_first_dropout", "val": " = 0.1"}, {"name": "scale_attn_weights", "val": " = True"}, {"name": "use_cache", "val": " = True"}, {"name": "bos_token_id", "val": " = 50256"}, {"name": "eos_token_id", "val": " = 50256"}, {"name": "scale_attn_by_inverse_layer_idx", "val": " = False"}, {"name": "reorder_and_upcast_attn", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_size** (`int`, *optional*, defaults to 50257) --
  Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
  `inputs_ids` passed when calling [GPT2Model](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Model) or [TFGPT2Model](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2Model).
- **n_positions** (`int`, *optional*, defaults to 1024) --
  The maximum sequence length that this model might ever be used with. Typically set this to something large
  just in case (e.g., 512 or 1024 or 2048).
- **n_embd** (`int`, *optional*, defaults to 768) --
  Dimensionality of the embeddings and hidden states.
- **n_layer** (`int`, *optional*, defaults to 12) --
  Number of hidden layers in the Transformer encoder.
- **n_head** (`int`, *optional*, defaults to 12) --
  Number of attention heads for each attention layer in the Transformer encoder.
- **n_inner** (`int`, *optional*, defaults to None) --
  Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
- **activation_function** (`str`, *optional*, defaults to `"gelu"`) --
  Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
- **resid_pdrop** (`float`, *optional*, defaults to 0.1) --
  The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
- **embd_pdrop** (`int`, *optional*, defaults to 0.1) --
  The dropout ratio for the embeddings.
- **attn_pdrop** (`float`, *optional*, defaults to 0.1) --
  The dropout ratio for the attention.
- **layer_norm_epsilon** (`float`, *optional*, defaults to 1e-5) --
  The epsilon to use in the layer normalization layers.
- **initializer_range** (`float`, *optional*, defaults to 0.02) --
  The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- **summary_type** (`string`, *optional*, defaults to `"cls_index"`) --
  Argument used when doing sequence summary, used in the models [GPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2DoubleHeadsModel) and
  [TFGPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2DoubleHeadsModel).

  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 models [GPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2DoubleHeadsModel) and
  [TFGPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2DoubleHeadsModel).

  Whether or not to add a projection after the vector extraction.
- **summary_activation** (`str`, *optional*) --
  Argument used when doing sequence summary. Used in for the multiple choice head in
  [GPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2DoubleHeadsModel).

  Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
- **summary_proj_to_labels** (`bool`, *optional*, defaults to `True`) --
  Argument used when doing sequence summary, used in the models [GPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2DoubleHeadsModel) and
  [TFGPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2DoubleHeadsModel).

  Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
- **summary_first_dropout** (`float`, *optional*, defaults to 0.1) --
  Argument used when doing sequence summary, used in the models [GPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2DoubleHeadsModel) and
  [TFGPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2DoubleHeadsModel).

  The dropout ratio to be used after the projection and activation.
- **scale_attn_weights** (`bool`, *optional*, defaults to `True`) --
  Scale attention weights by dividing by sqrt(hidden_size)..
- **use_cache** (`bool`, *optional*, defaults to `True`) --
  Whether or not the model should return the last key/values attentions (not used by all models).
- **scale_attn_by_inverse_layer_idx** (`bool`, *optional*, defaults to `False`) --
  Whether to additionally scale attention weights by `1 / layer_idx + 1`.
- **reorder_and_upcast_attn** (`bool`, *optional*, defaults to `False`) --
  Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
  dot-product/softmax to float() when training with mixed precision.</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [GPT2Model](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Model) or a [TFGPT2Model](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2Model). It is used to
instantiate a GPT-2 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 GPT-2
[small](https://huggingface.co/gpt2) architecture.

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




Example:

```python
>>> from transformers import GPT2Model, GPT2Config

>>> # Initializing a GPT2 configuration
>>> configuration = GPT2Config()

>>> # Initializing a model from the configuration
>>> model = GPT2Model(configuration)

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

</div>

<h2 id="transformers.GPT2Tokenizer">GPT2Tokenizer</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2Tokenizer</name><anchor>transformers.GPT2Tokenizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/tokenization_gpt2.py#L104</source><parameters>[{"name": "vocab_file", "val": ""}, {"name": "merges_file", "val": ""}, {"name": "errors", "val": " = 'replace'"}, {"name": "unk_token", "val": " = '<|endoftext|>'"}, {"name": "bos_token", "val": " = '<|endoftext|>'"}, {"name": "eos_token", "val": " = '<|endoftext|>'"}, {"name": "add_prefix_space", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  Path to the vocabulary file.
- **merges_file** (`str`) --
  Path to the merges file.
- **errors** (`str`, *optional*, defaults to `"replace"`) --
  Paradigm to follow when decoding bytes to UTF-8. See
  [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
- **unk_token** (`str`, *optional*, defaults to `<|endoftext|>`) --
  The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  token instead.
- **bos_token** (`str`, *optional*, defaults to `<|endoftext|>`) --
  The beginning of sequence token.
- **eos_token** (`str`, *optional*, defaults to `<|endoftext|>`) --
  The end of sequence token.
- **add_prefix_space** (`bool`, *optional*, defaults to `False`) --
  Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  other word. (GPT2 tokenizer detect beginning of words by the preceding space).</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct a GPT-2 tokenizer. Based on byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without space) or not:

```
>>> from transformers import GPT2Tokenizer
>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> tokenizer("Hello world")['input_ids']
[15496, 995]
>>> tokenizer(" Hello world")['input_ids']
[18435, 995]
```

You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

<Tip>

When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).

</Tip>

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/pr_15592/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.





<div class="docstring"></div></div>

<h2 id="transformers.GPT2TokenizerFast">GPT2TokenizerFast</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2TokenizerFast</name><anchor>transformers.GPT2TokenizerFast</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/tokenization_gpt2_fast.py#L70</source><parameters>[{"name": "vocab_file", "val": " = None"}, {"name": "merges_file", "val": " = None"}, {"name": "tokenizer_file", "val": " = None"}, {"name": "unk_token", "val": " = '<|endoftext|>'"}, {"name": "bos_token", "val": " = '<|endoftext|>'"}, {"name": "eos_token", "val": " = '<|endoftext|>'"}, {"name": "add_prefix_space", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  Path to the vocabulary file.
- **merges_file** (`str`) --
  Path to the merges file.
- **errors** (`str`, *optional*, defaults to `"replace"`) --
  Paradigm to follow when decoding bytes to UTF-8. See
  [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
- **unk_token** (`str`, *optional*, defaults to `<|endoftext|>`) --
  The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  token instead.
- **bos_token** (`str`, *optional*, defaults to `<|endoftext|>`) --
  The beginning of sequence token.
- **eos_token** (`str`, *optional*, defaults to `<|endoftext|>`) --
  The end of sequence token.
- **add_prefix_space** (`bool`, *optional*, defaults to `False`) --
  Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  other word. (GPT2 tokenizer detect beginning of words by the preceding space).
- **trim_offsets** (`bool`, *optional*, defaults to `True`) --
  Whether or not the post-processing step should trim offsets to avoid including whitespaces.</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct a "fast" GPT-2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without space) or not:

```
>>> from transformers import GPT2TokenizerFast
>>> tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
>>> tokenizer("Hello world")['input_ids']
[15496, 995]
>>> tokenizer(" Hello world")['input_ids']
[18435, 995]
```

You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
the model was not pretrained this way, it might yield a decrease in performance.

<Tip>

When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.

</Tip>

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




</div>

<h2 id="transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput">GPT2 specific outputs</h2>

<div class="docstring">

<docstring><name>class transformers.models.gpt2.modeling\_gpt2.GPT2DoubleHeadsModelOutput</name><anchor>transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L492</source><parameters>[{"name": "loss", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "mc_loss", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "logits", "val": ": FloatTensor = None"}, {"name": "mc_logits", "val": ": FloatTensor = None"}, {"name": "past_key_values", "val": ": typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None"}, {"name": "hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}]</parameters><paramsdesc>- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) --
  Language modeling loss.
- **mc_loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided) --
  Multiple choice classification loss.
- **logits** (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`) --
  Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **mc_logits** (`torch.FloatTensor` of shape `(batch_size, num_choices)`) --
  Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) --
  Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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)`.

  GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
  self-attention heads.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for outputs of models predicting if two sentences are consecutive or not.




</div>

<div class="docstring">

<docstring><name>class transformers.models.gpt2.modeling\_tf\_gpt2.TFGPT2DoubleHeadsModelOutput</name><anchor>transformers.models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L588</source><parameters>[{"name": "logits", "val": ": Tensor = None"}, {"name": "mc_logits", "val": ": Tensor = None"}, {"name": "past_key_values", "val": ": typing.Optional[typing.List[tensorflow.python.framework.ops.Tensor]] = None"}, {"name": "hidden_states", "val": ": typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = None"}, {"name": "attentions", "val": ": typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = None"}]</parameters><paramsdesc>- **logits** (`tf.Tensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`) --
  Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **mc_logits** (`tf.Tensor` of shape `(batch_size, num_choices)`) --
  Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
- **past_key_values** (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) --
  List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for outputs of models predicting if two sentences are consecutive or not.




</div>

<h2 id="transformers.GPT2Model">GPT2Model</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2Model</name><anchor>transformers.GPT2Model</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L668</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.GPT2Model.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L737</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "encoder_hidden_states", "val": " = None"}, {"name": "encoder_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
  sequence tokens in the vocabulary.

  If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`) --
  Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  their past given to this model should not be passed as `input_ids` as they have already been computed.
- **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**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_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.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **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.

  If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
  `past_key_values`).
- **use_cache** (`bool`, *optional*) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past_key_values`).
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.

  If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **past_key_values** (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
  `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
  `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
  encoder_sequence_length, embed_size_per_head)`.

  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
  input) to speed up sequential decoding.
- **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.
- **cross_attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=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 of the decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</retdesc></docstring>
The [GPT2Model](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Model) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, GPT2Model
>>> import torch

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = GPT2Model.from_pretrained("gpt2")

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

>>> last_hidden_states = outputs.last_hidden_state
```


</div>
<div class="docstring">
<docstring><name>parallelize</name><anchor>transformers.GPT2Model.parallelize</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L691</source><parameters>[{"name": "device_map", "val": " = None"}]</parameters><paramsdesc>- **device_map** (`Dict[int, list]`, optional, defaults to None) --
  A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
  automatically mapped to the first device (for esoteric reasons). That means that the first device should
  have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
  following number of attention modules:

  - gpt2: 12
  - gpt2-medium: 24
  - gpt2-large: 36
  - gpt2-xl: 48</paramsdesc><paramgroups>0</paramgroups></docstring>

This is an experimental feature and is a subject to change at a moment's notice.

Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
it will evenly distribute blocks across all devices.



Example:

```python
# Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
device_map = &amp;lcub;
    0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
    1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
    3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
}
model.parallelize(device_map)
```


</div>
<div class="docstring">
<docstring><name>deparallelize</name><anchor>transformers.GPT2Model.deparallelize</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L711</source><parameters>[]</parameters></docstring>

Moves the model to cpu from a model parallel state.

Example:

```python
# On a 4 GPU machine with gpt2-large:
model = GPT2LMHeadModel.from_pretrained("gpt2-large")
device_map = &amp;lcub;
    0: [0, 1, 2, 3, 4, 5, 6, 7],
    1: [8, 9, 10, 11, 12, 13, 14, 15],
    2: [16, 17, 18, 19, 20, 21, 22, 23],
    3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
}
model.parallelize(device_map)  # Splits the model across several devices
model.deparallelize()  # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
```


</div></div>

<h2 id="transformers.GPT2LMHeadModel">GPT2LMHeadModel</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2LMHeadModel</name><anchor>transformers.GPT2LMHeadModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L946</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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


This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.GPT2LMHeadModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1015</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "encoder_hidden_states", "val": " = None"}, {"name": "encoder_attention_mask", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
  sequence tokens in the vocabulary.

  If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`) --
  Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  their past given to this model should not be passed as `input_ids` as they have already been computed.
- **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**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_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.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **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.

  If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
  `past_key_values`).
- **use_cache** (`bool`, *optional*) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past_key_values`).
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **labels** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.CausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithCrossAttentions) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **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, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned 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.
- **cross_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)`.

  Cross attentions weights after the attention softmax, used to compute the weighted average in the
  cross-attention heads.
- **past_key_values** (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `torch.FloatTensor` tuples of length `config.n_layers`, with each tuple containing the cached key,
  value states of the self-attention and the cross-attention layers if model is used in encoder-decoder
  setting. Only relevant if `config.is_decoder = True`.

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.</retdesc></docstring>
The [GPT2LMHeadModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2LMHeadModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> import torch
>>> from transformers import GPT2Tokenizer, GPT2LMHeadModel

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = GPT2LMHeadModel.from_pretrained("gpt2")

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


</div>
<div class="docstring">
<docstring><name>parallelize</name><anchor>transformers.GPT2LMHeadModel.parallelize</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L961</source><parameters>[{"name": "device_map", "val": " = None"}]</parameters><paramsdesc>- **device_map** (`Dict[int, list]`, optional, defaults to None) --
  A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
  automatically mapped to the first device (for esoteric reasons). That means that the first device should
  have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
  following number of attention modules:

  - gpt2: 12
  - gpt2-medium: 24
  - gpt2-large: 36
  - gpt2-xl: 48</paramsdesc><paramgroups>0</paramgroups></docstring>

This is an experimental feature and is a subject to change at a moment's notice.

Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
it will evenly distribute blocks across all devices.



Example:

```python
# Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
device_map = &amp;lcub;
    0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
    1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
    3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
}
model.parallelize(device_map)
```


</div>
<div class="docstring">
<docstring><name>deparallelize</name><anchor>transformers.GPT2LMHeadModel.deparallelize</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L973</source><parameters>[]</parameters></docstring>

Moves the model to cpu from a model parallel state.

Example:

```python
# On a 4 GPU machine with gpt2-large:
model = GPT2LMHeadModel.from_pretrained("gpt2-large")
device_map = &amp;lcub;
    0: [0, 1, 2, 3, 4, 5, 6, 7],
    1: [8, 9, 10, 11, 12, 13, 14, 15],
    2: [16, 17, 18, 19, 20, 21, 22, 23],
    3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
}
model.parallelize(device_map)  # Splits the model across several devices
model.deparallelize()  # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
```


</div></div>

<h2 id="transformers.GPT2DoubleHeadsModel">GPT2DoubleHeadsModel</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2DoubleHeadsModel</name><anchor>transformers.GPT2DoubleHeadsModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1115</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
input embeddings, the classification head takes as input the input of a specified classification token index in the
input sequence).


This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.GPT2DoubleHeadsModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1189</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "mc_token_ids", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "mc_labels", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
  sequence tokens in the vocabulary.

  If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`) --
  Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  their past given to this model should not be passed as `input_ids` as they have already been computed.
- **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**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_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.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **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.

  If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
  `past_key_values`).
- **use_cache** (`bool`, *optional*) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past_key_values`).
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **mc_token_ids** (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input) --
  Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
  1[`.
- **labels** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size - 1]` All labels set to
  `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
- **mc_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)</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss.
- **mc_loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided) -- Multiple choice classification loss.
- **logits** (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **mc_logits** (`torch.FloatTensor` of shape `(batch_size, num_choices)`) -- Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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)`.

  GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
  self-attention heads.</retdesc></docstring>
The [GPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2DoubleHeadsModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> import torch
>>> from transformers import GPT2Tokenizer, GPT2DoubleHeadsModel

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = GPT2DoubleHeadsModel.from_pretrained("gpt2")

>>> # Add a [CLS] to the vocabulary (we should train it also!)
>>> num_added_tokens = tokenizer.add_special_tokens(&amp;lcub;"cls_token": "[CLS]"})

>>> embedding_layer = model.resize_token_embeddings(
...     len(tokenizer)
>>> )  # Update the model embeddings with the new vocabulary size

>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> encoded_choices = [tokenizer.encode(s) for s in choices]
>>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]

>>> input_ids = torch.tensor(encoded_choices).unsqueeze(0)  # Batch size: 1, number of choices: 2
>>> mc_token_ids = torch.tensor([cls_token_location])  # Batch size: 1

>>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
>>> lm_logits = outputs.logits
>>> mc_logits = outputs.mc_logits
```

</div></div>

<h2 id="transformers.GPT2ForSequenceClassification">GPT2ForSequenceClassification</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2ForSequenceClassification</name><anchor>transformers.GPT2ForSequenceClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1331</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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

[GPT2ForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2ForSequenceClassification) 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/pr_15592/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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.GPT2ForSequenceClassification.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1347</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
  sequence tokens in the vocabulary.

  If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`) --
  Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  their past given to this model should not be passed as `input_ids` as they have already been computed.
- **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**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_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.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **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.

  If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
  `past_key_values`).
- **use_cache** (`bool`, *optional*) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past_key_values`).
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **labels** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  config.num_labels - 1]`. 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).</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.modeling_outputs.SequenceClassifierOutputWithPast`or `tuple(torch.FloatTensor)`</rettype><retdesc>A `transformers.modeling_outputs.SequenceClassifierOutputWithPast`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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` 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).
- **past_key_values** (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
  `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

  Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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.</retdesc></docstring>
The [GPT2ForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2ForSequenceClassification) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example of single-label classification:

```python
>>> from transformers import GPT2Tokenizer, GPT2ForSequenceClassification
>>> import torch

>>> tokenizer = GPT2Tokenizer.from_pretrained("microsoft/DialogRPT-updown")
>>> model = GPT2ForSequenceClassification.from_pretrained("microsoft/DialogRPT-updown")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> labels = torch.tensor([1]).unsqueeze(0)  # Batch size 1
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
```

Example of multi-label classification:

```python
>>> from transformers import GPT2Tokenizer, GPT2ForSequenceClassification
>>> import torch

>>> tokenizer = GPT2Tokenizer.from_pretrained("microsoft/DialogRPT-updown")
>>> model = GPT2ForSequenceClassification.from_pretrained("microsoft/DialogRPT-updown", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> labels = torch.tensor([[1, 1]], dtype=torch.float)  # need dtype=float for BCEWithLogitsLoss
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
```


</div></div>

<h2 id="transformers.GPT2ForTokenClassification">GPT2ForTokenClassification</h2>

<div class="docstring">

<docstring><name>class transformers.GPT2ForTokenClassification</name><anchor>transformers.GPT2ForTokenClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1457</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

GPT2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
Named-Entity-Recognition (NER) tasks.


This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.GPT2ForTokenClassification.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_gpt2.py#L1479</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
  sequence tokens in the vocabulary.

  If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **past_key_values** (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`) --
  Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
  their past given to this model should not be passed as `input_ids` as they have already been computed.
- **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**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`torch.LongTensor` of shape `(batch_size, input_ids_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.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **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.

  If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
  `past_key_values`).
- **use_cache** (`bool`, *optional*) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past_key_values`).
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **labels** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  config.num_labels - 1]`. 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).</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.TokenClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.TokenClassifierOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.TokenClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.TokenClassifierOutput) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **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).
- **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.</retdesc></docstring>
The [GPT2ForTokenClassification](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2ForTokenClassification) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, GPT2ForTokenClassification
>>> import torch

>>> tokenizer = GPT2Tokenizer.from_pretrained("microsoft/DialogRPT-updown")
>>> model = GPT2ForTokenClassification.from_pretrained("microsoft/DialogRPT-updown")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> labels = torch.tensor([1] * inputs["input_ids"].size(1)).unsqueeze(0)  # Batch size 1

>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
```


</div></div>

<h2 id="transformers.TFGPT2Model">TFGPT2Model</h2>

<div class="docstring">

<docstring><name>class transformers.TFGPT2Model</name><anchor>transformers.TFGPT2Model</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L727</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.

This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/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.

<Tip>

TF 2.0 models accepts two formats as inputs:

- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.

This second option is useful when using `tf.keras.Model.fit` method which currently requires having all the
tensors in the first argument of the model call function: `model(inputs)`.

If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
first positional argument :

- a single Tensor with `input_ids` only and nothing else: `model(inputs_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` 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(&amp;lcub;"input_ids": input_ids, "token_type_ids": token_type_ids})`

</Tip>





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFGPT2Model.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L732</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "encoder_hidden_states", "val": " = None"}, {"name": "encoder_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
  input past key value states). Indices of input sequence tokens in the vocabulary.

  If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) and
  [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) for details.

  [What are input IDs?](../glossary#input-ids)
- **past** (`List[tf.Tensor]` of length `config.n_layers`) --
  Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past` 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.
- **attention_mask** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

  - 1 for tokens that are **not masked**,
  - 0 for tokens that are **masked**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1]`:

  - 0 corresponds to a *sentence A* token,
  - 1 corresponds to a *sentence B* token.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **head_mask** (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*) --
  Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **inputs_embeds** (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Optionally, instead of 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. This argument can be used only in eager mode, in graph mode the value in the
  config will be used instead.
- **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. This argument can be used only in eager mode, in graph mode the value in the config will be
  used instead.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple. This argument can be used
  in eager mode, in graph mode the value will always be set to True.
- **training** (`bool`, *optional*, defaults to `False`) --
  Whether or not to use the model in training mode (some modules like dropout modules have different
  behaviors between training and evaluation).

- **encoder_hidden_states**  (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  the model is configured as a decoder.
- **encoder_attention_mask** (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

  - 1 for tokens that are **not masked**,
  - 0 for tokens that are **masked**.

- **past** (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`) --
  contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
  If `past` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have
  their past key value states given to this model) of shape `(batch_size, 1)` instead of all
  `decoder_input_ids` of shape `(batch_size, sequence_length)`.
- **use_cache** (`bool`, *optional*, defaults to `True`) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past`). Set to `False` during training, `True` during generation</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **last_hidden_state** (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.

  If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **past_key_values** (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **hidden_states** (`tuple(tf.FloatTensor)`, *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.
- **cross_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 of the decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</retdesc></docstring>
The [TFGPT2Model](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2Model) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, TFGPT2Model
>>> import tensorflow as tf

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = TFGPT2Model.from_pretrained("gpt2")

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

>>> last_hidden_states = outputs.last_hidden_state
```


</div></div>

<h2 id="transformers.TFGPT2LMHeadModel">TFGPT2LMHeadModel</h2>

<div class="docstring">

<docstring><name>class transformers.TFGPT2LMHeadModel</name><anchor>transformers.TFGPT2LMHeadModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L843</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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


This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/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.

<Tip>

TF 2.0 models accepts two formats as inputs:

- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.

This second option is useful when using `tf.keras.Model.fit` method which currently requires having all the
tensors in the first argument of the model call function: `model(inputs)`.

If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
first positional argument :

- a single Tensor with `input_ids` only and nothing else: `model(inputs_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` 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(&amp;lcub;"input_ids": input_ids, "token_type_ids": token_type_ids})`

</Tip>





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFGPT2LMHeadModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L861</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "encoder_hidden_states", "val": " = None"}, {"name": "encoder_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
  input past key value states). Indices of input sequence tokens in the vocabulary.

  If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) and
  [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) for details.

  [What are input IDs?](../glossary#input-ids)
- **past** (`List[tf.Tensor]` of length `config.n_layers`) --
  Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past` 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.
- **attention_mask** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

  - 1 for tokens that are **not masked**,
  - 0 for tokens that are **masked**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1]`:

  - 0 corresponds to a *sentence A* token,
  - 1 corresponds to a *sentence B* token.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **head_mask** (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*) --
  Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **inputs_embeds** (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Optionally, instead of 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. This argument can be used only in eager mode, in graph mode the value in the
  config will be used instead.
- **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. This argument can be used only in eager mode, in graph mode the value in the config will be
  used instead.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple. This argument can be used
  in eager mode, in graph mode the value will always be set to True.
- **training** (`bool`, *optional*, defaults to `False`) --
  Whether or not to use the model in training mode (some modules like dropout modules have different
  behaviors between training and evaluation).

- **encoder_hidden_states**  (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  the model is configured as a decoder.
- **encoder_attention_mask** (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

  - 1 for tokens that are **not masked**,
  - 0 for tokens that are **masked**.

- **past** (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`) --
  contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
  If `past` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have
  their past key value states given to this model) of shape `(batch_size, 1)` instead of all
  `decoder_input_ids` of shape `(batch_size, sequence_length)`.
- **use_cache** (`bool`, *optional*, defaults to `True`) --
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  `past`). Set to `False` during training, `True` during generation
- **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]`.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **loss** (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided) -- Language modeling loss (for next-token prediction).
- **logits** (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **hidden_states** (`tuple(tf.Tensor)`, *optional*, returned 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.
- **cross_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 of the decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.
- **past_key_values** (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.</retdesc></docstring>
The [TFGPT2LMHeadModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2LMHeadModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, TFGPT2LMHeadModel
>>> import tensorflow as tf

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = TFGPT2LMHeadModel.from_pretrained("gpt2")

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


</div></div>

<h2 id="transformers.TFGPT2DoubleHeadsModel">TFGPT2DoubleHeadsModel</h2>

<div class="docstring">

<docstring><name>class transformers.TFGPT2DoubleHeadsModel</name><anchor>transformers.TFGPT2DoubleHeadsModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L995</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
input embeddings, the classification head takes as input the input of a specified classification token index in the
input sequence).


This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/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.

<Tip>

TF 2.0 models accepts two formats as inputs:

- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.

This second option is useful when using `tf.keras.Model.fit` method which currently requires having all the
tensors in the first argument of the model call function: `model(inputs)`.

If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
first positional argument :

- a single Tensor with `input_ids` only and nothing else: `model(inputs_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` 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(&amp;lcub;"input_ids": input_ids, "token_type_ids": token_type_ids})`

</Tip>





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFGPT2DoubleHeadsModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L1004</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "mc_token_ids", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
  input past key value states). Indices of input sequence tokens in the vocabulary.

  If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) and
  [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) for details.

  [What are input IDs?](../glossary#input-ids)
- **past** (`List[tf.Tensor]` of length `config.n_layers`) --
  Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past` 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.
- **attention_mask** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

  - 1 for tokens that are **not masked**,
  - 0 for tokens that are **masked**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1]`:

  - 0 corresponds to a *sentence A* token,
  - 1 corresponds to a *sentence B* token.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **head_mask** (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*) --
  Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **inputs_embeds** (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Optionally, instead of 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. This argument can be used only in eager mode, in graph mode the value in the
  config will be used instead.
- **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. This argument can be used only in eager mode, in graph mode the value in the config will be
  used instead.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple. This argument can be used
  in eager mode, in graph mode the value will always be set to True.
- **training** (`bool`, *optional*, defaults to `False`) --
  Whether or not to use the model in training mode (some modules like dropout modules have different
  behaviors between training and evaluation).

- **mc_token_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input) --
  Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
  1[`.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **logits** (`tf.Tensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **mc_logits** (`tf.Tensor` of shape `(batch_size, num_choices)`) -- Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
- **past_key_values** (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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.</retdesc></docstring>
The [TFGPT2DoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2DoubleHeadsModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Examples:

```python
>>> import tensorflow as tf
>>> from transformers import GPT2Tokenizer, TFGPT2DoubleHeadsModel

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = TFGPT2DoubleHeadsModel.from_pretrained("gpt2")

>>> # Add a [CLS] to the vocabulary (we should train it also!)
>>> num_added_tokens = tokenizer.add_special_tokens(&amp;lcub;"cls_token": "[CLS]"})

>>> embedding_layer = model.resize_token_embeddings(
...     len(tokenizer)
>>> )  # Update the model embeddings with the new vocabulary size

>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> encoded_choices = [tokenizer.encode(s) for s in choices]
>>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]

>>> input_ids = tf.constant(encoded_choices)[None, :]  # Batch size: 1, number of choices: 2
>>> mc_token_ids = tf.constant([cls_token_location])  # Batch size: 1

>>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
>>> lm_prediction_scores, mc_prediction_scores = outputs[:2]
```

</div></div>

<h2 id="transformers.TFGPT2ForSequenceClassification">TFGPT2ForSequenceClassification</h2>

<div class="docstring">

<docstring><name>class transformers.TFGPT2ForSequenceClassification</name><anchor>transformers.TFGPT2ForSequenceClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L1167</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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

[TFGPT2ForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2ForSequenceClassification) 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 [TFPreTrainedModel](/docs/transformers/pr_15592/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.

<Tip>

TF 2.0 models accepts two formats as inputs:

- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.

This second option is useful when using `tf.keras.Model.fit` method which currently requires having all the
tensors in the first argument of the model call function: `model(inputs)`.

If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the
first positional argument :

- a single Tensor with `input_ids` only and nothing else: `model(inputs_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` 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(&amp;lcub;"input_ids": input_ids, "token_type_ids": token_type_ids})`

</Tip>





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFGPT2ForSequenceClassification.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_tf_gpt2.py#L1179</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "past", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "token_type_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
  input past key value states). Indices of input sequence tokens in the vocabulary.

  If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) and
  [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) for details.

  [What are input IDs?](../glossary#input-ids)
- **past** (`List[tf.Tensor]` of length `config.n_layers`) --
  Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
  `past` 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.
- **attention_mask** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

  - 1 for tokens that are **not masked**,
  - 0 for tokens that are **masked**.

  [What are attention masks?](../glossary#attention-mask)
- **token_type_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1]`:

  - 0 corresponds to a *sentence A* token,
  - 1 corresponds to a *sentence B* token.

  [What are token type IDs?](../glossary#token-type-ids)
- **position_ids** (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.

  [What are position IDs?](../glossary#position-ids)
- **head_mask** (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*) --
  Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

  - 1 indicates the head is **not masked**,
  - 0 indicates the head is **masked**.

- **inputs_embeds** (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) --
  Optionally, instead of 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. This argument can be used only in eager mode, in graph mode the value in the
  config will be used instead.
- **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. This argument can be used only in eager mode, in graph mode the value in the config will be
  used instead.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple. This argument can be used
  in eager mode, in graph mode the value will always be set to True.
- **training** (`bool`, *optional*, defaults to `False`) --
  Whether or not to use the model in training mode (some modules like dropout modules have different
  behaviors between training and evaluation).

- **labels** (`tf.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]`.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **loss** (`tf.Tensor` of shape `(batch_size, )`, *optional*, returned when `labels` 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).
- **past_key_values** (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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.</retdesc></docstring>
The [TFGPT2ForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.TFGPT2ForSequenceClassification) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, TFGPT2ForSequenceClassification
>>> import tensorflow as tf

>>> tokenizer = GPT2Tokenizer.from_pretrained("microsoft/DialogRPT-updown")
>>> model = TFGPT2ForSequenceClassification.from_pretrained("microsoft/DialogRPT-updown")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> inputs["labels"] = tf.reshape(tf.constant(1), (-1, 1))  # Batch size 1

>>> outputs = model(inputs)
>>> loss = outputs.loss
>>> logits = outputs.logits
```


</div></div>

<h2 id="transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast">TFSequenceClassifierOutputWithPast</h2>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_outputs.TFSequenceClassifierOutputWithPast</name><anchor>transformers.modeling_tf_outputs.TFSequenceClassifierOutputWithPast</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_outputs.py#L758</source><parameters>[{"name": "loss", "val": ": typing.Optional[tensorflow.python.framework.ops.Tensor] = None"}, {"name": "logits", "val": ": Tensor = None"}, {"name": "past_key_values", "val": ": typing.Optional[typing.List[tensorflow.python.framework.ops.Tensor]] = None"}, {"name": "hidden_states", "val": ": typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = None"}, {"name": "attentions", "val": ": typing.Optional[typing.Tuple[tensorflow.python.framework.ops.Tensor]] = None"}]</parameters><paramsdesc>- **loss** (`tf.Tensor` of shape `(batch_size, )`, *optional*, returned when `labels` 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).
- **past_key_values** (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) --
  List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
  sequence_length, embed_size_per_head)`).

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.
- **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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for outputs of sentence classification models.




</div>

<h2 id="transformers.FlaxGPT2Model">FlaxGPT2Model</h2>

<div class="docstring">

<docstring><name>class transformers.FlaxGPT2Model</name><anchor>transformers.FlaxGPT2Model</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_flax_gpt2.py#L654</source><parameters>[{"name": "config", "val": ": GPT2Config"}, {"name": "input_shape", "val": ": typing.Tuple = (1, 1)"}, {"name": "seed", "val": ": int = 0"}, {"name": "dtype", "val": ": dtype = <class 'jax._src.numpy.lax_numpy.float32'>"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.from_pretrained) method to load the model weights.
- **dtype** (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`) --
  The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
  `jax.numpy.bfloat16` (on TPUs).

  This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
  specified all the computation will be performed with the given `dtype`.

  **Note that this only specifies the dtype of the computation and does not influence the dtype of model
  parameters.**

  If you wish to change the dtype of the model parameters, see [to_fp16()](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.to_fp16) and
  [to_bf16()](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.to_bf16).</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.

This model inherits from [FlaxPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel). 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 Flax Linen
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.

Finally, this model supports inherent JAX features such as:

- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.FlaxGPT2PreTrainedModel.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_flax_gpt2.py#L447</source><parameters>[{"name": "input_ids", "val": ""}, {"name": "attention_mask", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "encoder_hidden_states", "val": ": typing.Optional[jax._src.numpy.lax_numpy.ndarray] = None"}, {"name": "encoder_attention_mask", "val": ": typing.Optional[jax._src.numpy.lax_numpy.ndarray] = None"}, {"name": "params", "val": ": dict = None"}, {"name": "past_key_values", "val": ": dict = None"}, {"name": "dropout_rng", "val": ": PRNGKey = None"}, {"name": "train", "val": ": bool = False"}, {"name": "output_attentions", "val": ": typing.Optional[bool] = None"}, {"name": "output_hidden_states", "val": ": typing.Optional[bool] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}]</parameters><paramsdesc>- **input_ids** (`numpy.ndarray` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length`. Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **attention_mask** (`numpy.ndarray` 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**.

  [What are attention masks?](../glossary#attention-mask)
- **position_ids** (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.
- **past_key_values** (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`) --
  Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
  auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **last_hidden_state** (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.

  If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  hidden_size)` is output.
- **past_key_values** (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape
  `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
  `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
  encoder_sequence_length, embed_size_per_head)`.

  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
  input) to speed up sequential decoding.
- **hidden_states** (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.
- **cross_attentions** (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`) -- Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</retdesc></docstring>
The `FlaxGPT2PreTrainedModel`forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, FlaxGPT2Model

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = FlaxGPT2Model.from_pretrained("gpt2")

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

>>> last_hidden_states = outputs.last_hidden_state
```


</div></div>

<h2 id="transformers.FlaxGPT2LMHeadModel">FlaxGPT2LMHeadModel</h2>

<div class="docstring">

<docstring><name>class transformers.FlaxGPT2LMHeadModel</name><anchor>transformers.FlaxGPT2LMHeadModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_flax_gpt2.py#L732</source><parameters>[{"name": "config", "val": ": GPT2Config"}, {"name": "input_shape", "val": ": typing.Tuple = (1, 1)"}, {"name": "seed", "val": ": int = 0"}, {"name": "dtype", "val": ": dtype = <class 'jax._src.numpy.lax_numpy.float32'>"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) -- 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/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.from_pretrained) method to load the model weights.
- **dtype** (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`) --
  The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
  `jax.numpy.bfloat16` (on TPUs).

  This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
  specified all the computation will be performed with the given `dtype`.

  **Note that this only specifies the dtype of the computation and does not influence the dtype of model
  parameters.**

  If you wish to change the dtype of the model parameters, see [to_fp16()](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.to_fp16) and
  [to_bf16()](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel.to_bf16).</paramsdesc><paramgroups>0</paramgroups></docstring>

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


This model inherits from [FlaxPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.FlaxPreTrainedModel). 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 Flax Linen
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.

Finally, this model supports inherent JAX features such as:

- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.FlaxGPT2PreTrainedModel.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/gpt2/modeling_flax_gpt2.py#L447</source><parameters>[{"name": "input_ids", "val": ""}, {"name": "attention_mask", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "encoder_hidden_states", "val": ": typing.Optional[jax._src.numpy.lax_numpy.ndarray] = None"}, {"name": "encoder_attention_mask", "val": ": typing.Optional[jax._src.numpy.lax_numpy.ndarray] = None"}, {"name": "params", "val": ": dict = None"}, {"name": "past_key_values", "val": ": dict = None"}, {"name": "dropout_rng", "val": ": PRNGKey = None"}, {"name": "train", "val": ": bool = False"}, {"name": "output_attentions", "val": ": typing.Optional[bool] = None"}, {"name": "output_hidden_states", "val": ": typing.Optional[bool] = None"}, {"name": "return_dict", "val": ": typing.Optional[bool] = None"}]</parameters><paramsdesc>- **input_ids** (`numpy.ndarray` of shape `(batch_size, input_ids_length)`) --
  `input_ids_length` = `sequence_length`. Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [GPT2Tokenizer](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Tokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#input-ids)
- **attention_mask** (`numpy.ndarray` 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**.

  [What are attention masks?](../glossary#attention-mask)
- **position_ids** (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*) --
  Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  config.max_position_embeddings - 1]`.
- **past_key_values** (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`) --
  Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
  auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
- **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.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions) 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 ([GPT2Config](/docs/transformers/pr_15592/en/model_doc/gpt2#transformers.GPT2Config)) and inputs.

- **logits** (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **hidden_states** (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.
- **cross_attentions** (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Cross attentions weights after the attention softmax, used to compute the weighted average in the
  cross-attention heads.
- **past_key_values** (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `jnp.ndarray` tuples of length `config.n_layers`, with each tuple containing the cached key, value
  states of the self-attention and the cross-attention layers if model is used in encoder-decoder setting.
  Only relevant if `config.is_decoder = True`.

  Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
  `past_key_values` input) to speed up sequential decoding.</retdesc></docstring>
The `FlaxGPT2PreTrainedModel`forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import GPT2Tokenizer, FlaxGPT2LMHeadModel

>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = FlaxGPT2LMHeadModel.from_pretrained("gpt2")

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

>>> # retrieve logts for next token
>>> next_token_logits = outputs.logits[:, -1]
```


</div></div>
