---
local: openai-gpt
sections:
- local: overview
  title: Overview
- local: transformers.OpenAIGPTConfig
  title: OpenAIGPTConfig
- local: transformers.OpenAIGPTTokenizer
  title: OpenAIGPTTokenizer
- local: transformers.OpenAIGPTTokenizerFast
  title: OpenAIGPTTokenizerFast
- local: transformers.models.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput
  title: OpenAI specific outputs
- local: transformers.OpenAIGPTModel
  title: OpenAIGPTModel
- local: transformers.OpenAIGPTLMHeadModel
  title: OpenAIGPTLMHeadModel
- local: transformers.OpenAIGPTDoubleHeadsModel
  title: OpenAIGPTDoubleHeadsModel
- local: transformers.OpenAIGPTForSequenceClassification
  title: OpenAIGPTForSequenceClassification
- local: transformers.TFOpenAIGPTModel
  title: TFOpenAIGPTModel
- local: transformers.TFOpenAIGPTLMHeadModel
  title: TFOpenAIGPTLMHeadModel
- local: transformers.TFOpenAIGPTDoubleHeadsModel
  title: TFOpenAIGPTDoubleHeadsModel
- local: transformers.TFOpenAIGPTForSequenceClassification
  title: TFOpenAIGPTForSequenceClassification
title: OpenAI GPT
---
<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-gpt">OpenAI GPT</h1>

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

OpenAI GPT model was proposed in [Improving Language Understanding by Generative Pre-Training](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf)
by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever. It's a causal (unidirectional) transformer
pre-trained using language modeling on a large corpus will long range dependencies, the Toronto Book Corpus.

The abstract from the paper is the following:

*Natural language understanding comprises a wide range of diverse tasks such as textual entailment, question answering,
semantic similarity assessment, and document classification. Although large unlabeled text corpora are abundant,
labeled data for learning these specific tasks is scarce, making it challenging for discriminatively trained models to
perform adequately. We demonstrate that large gains on these tasks can be realized by generative pretraining of a
language model on a diverse corpus of unlabeled text, followed by discriminative fine-tuning on each specific task. In
contrast to previous approaches, we make use of task-aware input transformations during fine-tuning to achieve
effective transfer while requiring minimal changes to the model architecture. We demonstrate the effectiveness of our
approach on a wide range of benchmarks for natural language understanding. Our general task-agnostic model outperforms
discriminatively trained models that use architectures specifically crafted for each task, significantly improving upon
the state of the art in 9 out of the 12 tasks studied.*

Tips:

- GPT is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than
  the left.
- GPT 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.

[Write With Transformer](https://transformer.huggingface.co/doc/gpt) is a webapp created and hosted by Hugging Face
showcasing the generative capabilities of several models. GPT is one of them.

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

Note:

If you want to reproduce the original tokenization process of the *OpenAI GPT* paper, you will need to install `ftfy`
and `SpaCy`:

```bash
pip install spacy ftfy==4.4.3
python -m spacy download en
```

If you don't install `ftfy` and `SpaCy`, the [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer) will default to tokenize
using BERT's `BasicTokenizer` followed by Byte-Pair Encoding (which should be fine for most usage, don't worry).

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

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTConfig</name><anchor>transformers.OpenAIGPTConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/configuration_openai.py#L27</source><parameters>[{"name": "vocab_size", "val": " = 40478"}, {"name": "n_positions", "val": " = 512"}, {"name": "n_embd", "val": " = 768"}, {"name": "n_layer", "val": " = 12"}, {"name": "n_head", "val": " = 12"}, {"name": "afn", "val": " = 'gelu'"}, {"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": "predict_special_tokens", "val": " = True"}, {"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": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_size** (`int`, *optional*, defaults to 40478) --
  Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
  `inputs_ids` passed when calling [OpenAIGPTModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTModel) or [TFOpenAIGPTModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTModel).
- **n_positions** (`int`, *optional*, defaults to 512) --
  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.
- **afn** (`str` or `Callable`, *optional*, defaults to `"gelu"`) --
  The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  `"relu"`, `"silu"` and `"gelu_new"` are supported.
- **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.
- **predict_special_tokens** (`bool`, *optional*, defaults to `True`) --
  Whether or not special tokens should be predicted when the model has a language modeling head.
- **summary_type** (`str`, *optional*, defaults to `"cls_index"`) --
  Argument used when doing sequence summary, used in the models [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel) and
  [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel).

  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 [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel) and
  [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel).

  Whether or not to add a projection after the vector extraction.
- **summary_activation** (`str`, *optional*) --
  Argument used when doing sequence summary, used in the models [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel) and
  [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel).

  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 [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel) and
  [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel).

  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 [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel) and
  [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel).

  The dropout ratio to be used after the projection and activation.
- **use_cache** (`bool`, *optional*, defaults to `True`) --
  Whether or not the model should return the last key/values attentions (not used by all models).</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [OpenAIGPTModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTModel) or a [TFOpenAIGPTModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTModel). It is
used to instantiate a GPT 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](https://huggingface.co/openai-gpt) architecture from OpenAI.

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.



Examples:

```python
>>> from transformers import OpenAIGPTConfig, OpenAIGPTModel

>>> # Initializing a GPT configuration
>>> configuration = OpenAIGPTConfig()

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

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

</div>

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

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTTokenizer</name><anchor>transformers.OpenAIGPTTokenizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/tokenization_openai.py#L73</source><parameters>[{"name": "vocab_file", "val": ""}, {"name": "merges_file", "val": ""}, {"name": "unk_token", "val": " = '<unk>'"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  Path to the vocabulary file.
- **merges_file** (`str`) --
  Path to the merges file.
- **unk_token** (`str`, *optional*, defaults to `"&amp;lt;unk>"`) --
  The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  token instead.</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct a GPT Tokenizer. Based on Byte-Pair-Encoding with the following peculiarities:

- lowercases all inputs,
- uses `SpaCy` tokenizer and `ftfy` for pre-BPE tokenization if they are installed, fallback to BERT's
  `BasicTokenizer` if not.

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.OpenAIGPTTokenizerFast">OpenAIGPTTokenizerFast</h2>

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTTokenizerFast</name><anchor>transformers.OpenAIGPTTokenizerFast</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/tokenization_openai_fast.py#L40</source><parameters>[{"name": "vocab_file", "val": " = None"}, {"name": "merges_file", "val": " = None"}, {"name": "tokenizer_file", "val": " = None"}, {"name": "unk_token", "val": " = '<unk>'"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  Path to the vocabulary file.
- **merges_file** (`str`) --
  Path to the merges file.
- **unk_token** (`str`, *optional*, defaults to `"&amp;lt;unk>"`) --
  The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  token instead.</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct a "fast" GPT Tokenizer (backed by HuggingFace's *tokenizers* library). Based on Byte-Pair-Encoding with
the following peculiarities:

- lower case all inputs
- uses BERT's BasicTokenizer for pre-BPE tokenization

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.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput">OpenAI specific outputs</h2>

<div class="docstring">

<docstring><name>class transformers.models.openai.modeling\_openai.OpenAIGPTDoubleHeadsModelOutput</name><anchor>transformers.models.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L301</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": "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).
- **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.</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.openai.modeling\_tf\_openai.TFOpenAIGPTDoubleHeadsModelOutput</name><anchor>transformers.models.openai.modeling_tf_openai.TFOpenAIGPTDoubleHeadsModelOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L391</source><parameters>[{"name": "logits", "val": ": Tensor = None"}, {"name": "mc_logits", "val": ": 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).
- **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.OpenAIGPTModel">OpenAIGPTModel</h2>

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTModel</name><anchor>transformers.OpenAIGPTModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L405</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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 OpenAI GPT transformer model 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.OpenAIGPTModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L431</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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** (`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, 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** (`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.
- **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.BaseModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.BaseModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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.
- **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 [OpenAIGPTModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTModel) 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 OpenAIGPTTokenizer, OpenAIGPTModel
>>> import torch

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = OpenAIGPTModel.from_pretrained("openai-gpt")

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

>>> last_hidden_states = outputs.last_hidden_state
```


</div></div>

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

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTLMHeadModel</name><anchor>transformers.OpenAIGPTLMHeadModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L536</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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>

OpenAI GPT 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.OpenAIGPTLMHeadModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L551</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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** (`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, 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** (`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.
- **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.CausalLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.CausalLMOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.CausalLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.CausalLMOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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.</retdesc></docstring>
The [OpenAIGPTLMHeadModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTLMHeadModel) 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 OpenAIGPTTokenizer, OpenAIGPTLMHeadModel

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt")

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

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

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTDoubleHeadsModel</name><anchor>transformers.OpenAIGPTDoubleHeadsModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L623</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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>

OpenAI GPT 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.OpenAIGPTDoubleHeadsModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L641</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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** (`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, 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** (`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.
- **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 `[-1, 0, ..., config.vocab_size]` All labels set to `-100` are
  ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
- **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.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.models.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.models.openai.modeling_openai.OpenAIGPTDoubleHeadsModelOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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).
- **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 [OpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTDoubleHeadsModel) 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
>>> from transformers import OpenAIGPTTokenizer, OpenAIGPTDoubleHeadsModel
>>> import torch

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = OpenAIGPTDoubleHeadsModel.from_pretrained("openai-gpt")
>>> tokenizer.add_special_tokens(
...     &amp;lcub;"cls_token": "[CLS]"}
>>> )  # Add a [CLS] to the vocabulary (we should train it also!)
>>> model.resize_token_embeddings(len(tokenizer))

>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0)  # Batch size 1, 2 choices
>>> mc_token_ids = torch.tensor([input_ids.size(-1) - 1, input_ids.size(-1) - 1]).unsqueeze(0)  # 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.OpenAIGPTForSequenceClassification">OpenAIGPTForSequenceClassification</h2>

<div class="docstring">

<docstring><name>class transformers.OpenAIGPTForSequenceClassification</name><anchor>transformers.OpenAIGPTForSequenceClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L749</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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 Original OpenAI GPT Model transformer with a sequence classification head on top (linear layer).
[OpenAIGPTForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTForSequenceClassification) uses the last token in order to do the classification, as other causal
models (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the
last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding
token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since
it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take
the last value in each row of the batch).


This model inherits from [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.OpenAIGPTForSequenceClassification.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_openai.py#L759</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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** (`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, 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** (`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.
- **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.SequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.SequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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).
- **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 [OpenAIGPTForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTForSequenceClassification) 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 OpenAIGPTTokenizer, OpenAIGPTForSequenceClassification
>>> import torch

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = OpenAIGPTForSequenceClassification.from_pretrained("openai-gpt")

>>> 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 OpenAIGPTTokenizer, OpenAIGPTForSequenceClassification
>>> import torch

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = OpenAIGPTForSequenceClassification.from_pretrained("openai-gpt", 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.TFOpenAIGPTModel">TFOpenAIGPTModel</h2>

<div class="docstring">

<docstring><name>class transformers.TFOpenAIGPTModel</name><anchor>transformers.TFOpenAIGPTModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L516</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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 OpenAI GPT transformer model 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.TFOpenAIGPTModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L521</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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)
- **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** (`tf.Tensor` or `Numpy array` 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` or `Numpy array` 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).</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_tf_outputs.TFBaseModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFBaseModelOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFBaseModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFBaseModelOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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.
- **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.</retdesc></docstring>
The [TFOpenAIGPTModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTModel) 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 OpenAIGPTTokenizer, TFOpenAIGPTModel
>>> import tensorflow as tf

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = TFOpenAIGPTModel.from_pretrained("openai-gpt")

>>> 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.TFOpenAIGPTLMHeadModel">TFOpenAIGPTLMHeadModel</h2>

<div class="docstring">

<docstring><name>class transformers.TFOpenAIGPTLMHeadModel</name><anchor>transformers.TFOpenAIGPTLMHeadModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L586</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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>

OpenAI GPT 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.TFOpenAIGPTLMHeadModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L597</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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)
- **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** (`tf.Tensor` or `Numpy array` 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` or `Numpy array` 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.TFCausalLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFCausalLMOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFCausalLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFCausalLMOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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.</retdesc></docstring>
The [TFOpenAIGPTLMHeadModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTLMHeadModel) 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 OpenAIGPTTokenizer, TFOpenAIGPTLMHeadModel
>>> import tensorflow as tf

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = TFOpenAIGPTLMHeadModel.from_pretrained("openai-gpt")

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


</div></div>

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

<div class="docstring">

<docstring><name>class transformers.TFOpenAIGPTDoubleHeadsModel</name><anchor>transformers.TFOpenAIGPTDoubleHeadsModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L690</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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>

OpenAI GPT 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.TFOpenAIGPTDoubleHeadsModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L699</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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)
- **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** (`tf.Tensor` or `Numpy array` 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` or `Numpy array` 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.openai.modeling_tf_openai.TFOpenAIGPTDoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.models.openai.modeling_tf_openai.TFOpenAIGPTDoubleHeadsModelOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.models.openai.modeling_tf_openai.TFOpenAIGPTDoubleHeadsModelOutput](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.models.openai.modeling_tf_openai.TFOpenAIGPTDoubleHeadsModelOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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).
- **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 [TFOpenAIGPTDoubleHeadsModel](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTDoubleHeadsModel) 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 OpenAIGPTTokenizer, TFOpenAIGPTDoubleHeadsModel

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = TFOpenAIGPTDoubleHeadsModel.from_pretrained("openai-gpt")

>>> # Add a [CLS] to the vocabulary (we should train it also!)
>>> tokenizer.add_special_tokens(&amp;lcub;"cls_token": "[CLS]"})
>>> model.resize_token_embeddings(len(tokenizer))  # Update the model embeddings with the new vocabulary size
>>> print(tokenizer.cls_token_id, len(tokenizer))  # The newly token the last token of the vocabulary

>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> encoding = tokenizer(choices, return_tensors="tf")
>>> inputs = &amp;lcub;k: tf.expand_dims(v, 0) for k, v in encoding.items()}
>>> inputs["mc_token_ids"] = tf.constant(
...     [inputs["input_ids"].shape[-1] - 1, inputs["input_ids"].shape[-1] - 1]
>>> )[
...     None, :
>>> ]  # Batch size 1
>>> outputs = model(inputs)
>>> lm_prediction_scores, mc_prediction_scores = outputs[:2]
```

</div></div>

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

<div class="docstring">

<docstring><name>class transformers.TFOpenAIGPTForSequenceClassification</name><anchor>transformers.TFOpenAIGPTForSequenceClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L848</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) -- 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 OpenAI GPT Model transformer with a sequence classification head on top (linear layer).

[TFOpenAIGPTForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTForSequenceClassification) uses the last token in order to do the classification, as other causal
models (e.g. GPT-2) do.

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


This model inherits from [TFPreTrainedModel](/docs/transformers/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.TFOpenAIGPTForSequenceClassification.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/openai/modeling_tf_openai.py#L860</source><parameters>[{"name": "input_ids", "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": "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, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary.

  Indices can be obtained using [OpenAIGPTTokenizer](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTTokenizer). 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)
- **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** (`tf.Tensor` or `Numpy array` 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` or `Numpy array` 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.TFSequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFSequenceClassifierOutput) or `tuple(tf.Tensor)`</rettype><retdesc>A [transformers.modeling_tf_outputs.TFSequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_tf_outputs.TFSequenceClassifierOutput) 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 ([OpenAIGPTConfig](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.OpenAIGPTConfig)) 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).
- **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 [TFOpenAIGPTForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/openai-gpt#transformers.TFOpenAIGPTForSequenceClassification) 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 OpenAIGPTTokenizer, TFOpenAIGPTForSequenceClassification
>>> import tensorflow as tf

>>> tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
>>> model = TFOpenAIGPTForSequenceClassification.from_pretrained("openai-gpt")

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