GPT NeoΒΆ
OverviewΒΆ
The GPTNeo model was released in the EleutherAI/gpt-neo repository by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy. It is a GPT2 like causal language model trained on the Pile dataset.
The architecture is similar to GPT2 except that GPT Neo uses local attention in every other layer with a window size of 256 tokens.
GenerationΒΆ
The generate()
method can be used to generate text using GPT Neo model.
>>> from transformers import GPTNeoForCausalLM, GPT2Tokenizer
>>> model = GPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B")
>>> tokenizer = GPT2Tokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B")
>>> prompt = "In a shocking finding, scientists discovered a herd of unicorns living in a remote, " \
... "previously unexplored valley, in the Andes Mountains. Even more surprising to the " \
... "researchers was the fact that the unicorns spoke perfect English."
>>> input_ids = tokenizer(unicorns, return_tensors="pt").input_ids
>>> gen_tokens = model.generate(ids, do_sample=True, temperature=0.9, max_length=100,)
>>> gen_text = tokenizer.batch_decode(gen_tokens)[0]
GPTNeoConfigΒΆ
-
class
transformers.
GPTNeoConfig
(vocab_size=50257, max_position_embeddings=2048, hidden_size=2048, num_layers=24, attention_types=[[['global', 'local'], 12]], num_heads=16, intermediate_size=None, window_size=256, activation_function='gelu_new', resid_dropout=0.0, embed_dropout=0.0, attention_dropout=0.0, layer_norm_epsilon=1e-05, initializer_range=0.02, summary_type='cls_index', summary_use_proj=True, summary_activation=None, summary_proj_to_labels=True, summary_first_dropout=0.1, gradient_checkpointing=False, use_cache=True, bos_token_id=50256, eos_token_id=50256, **kwargs)[source]ΒΆ This is the configuration class to store the configuration of a
GPTNeoModel
. It is used to instantiate a GPT Neo 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 GPTNeo gpt-neo-1.3B architecture.Configuration objects inherit from
PretrainedConfig
and can be used to control the model outputs. Read the documentation fromPretrainedConfig
for more information.- Parameters
vocab_size (
int
, optional, defaults to 50257) β Vocabulary size of the GPT Neo model. Defines the number of different tokens that can be represented by theinputs_ids
passed when callingGPTNeoModel
. Vocabulary size of the model. Defines the different tokens that can be represented by the inputs_ids passed to the forward method ofGPTNeoModel
.attention_types (
List
, optional, defaults to[[["global", "local"], 12]]
) β The type of attention for each layer in aList
of the following format[[["attention_type"], num_layerss]]
e.g. for a 24 layer model[[["global"], 24]]
or[[["global", "local"], 12]]
Choose the value ofattention_type
from["global", "local"]
hidden_size (
int
, optional, defaults to 2048) β Dimensionality of the encoder layers and the pooler layer.num_layers (
int
, optional, defaults to 24) β Number of hidden layers in the Transformer encoder.num_heads (
int
, optional, defaults to 16) β Number of attention heads for each attention layer in the Transformer encoder.intermediate_size (
int
, optional, defaults to 8192) β Dimensionality of the βintermediateβ (i.e., feed-forward) layer in the Transformer encoder.activation_function (
str
orfunction
, optional, defaults to"gelu_new"
) β The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu"
,"relu"
,"selu"
and"gelu_new"
are supported.embed_dropout (
float
, optional, defaults to 0.0) β The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.attention_dropout (
float
, optional, defaults to 0.0) β The dropout ratio for the attention probabilities.max_position_embeddings (
int
, optional, defaults to 2048) β 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).type_vocab_size (
int
, optional, defaults to 2) β The vocabulary size of thetoken_type_ids
passed when callingGPTNeoModel
.initializer_range (
float
, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices.layer_norm_epsilon (
float
, optional, defaults to 1e-5) β The epsilon used by the layer normalization layers.use_cache (
bool
, optional, defaults toTrue
) β Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=True
.gradient_checkpointing (
bool
, optional, defaults toFalse
) β If True, use gradient checkpointing to save memory at the expense of slower backward pass.Example:: β
>>> from transformers import GPTNeoModel, GPTNeoConfig
>>> # Initializing a GPTNeo EleutherAI/gpt-neo-1.3B style configuration >>> configuration = GPTNeoConfig()
>>> # Initializing a model from the EleutherAI/gpt-neo-1.3B style configuration >>> model = GPTNeoModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config
GPTNeoModelΒΆ
-
class
transformers.
GPTNeoModel
(config)[source]ΒΆ The bare GPT Neo Model transformer outputting raw hidden-states without any specific head on top.
This model inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
GPTNeoConfig
) β 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 thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, past_key_values=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
GPTNeoModel
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, input_ids_length)
) βinput_ids_length
=sequence_length
ifpast_key_values
isNone
elsepast_key_values[0][0].shape[-2]
(sequence_length
of input past key value states). Indices of input sequence tokens in the vocabulary.If
past_key_values
is used, onlyinput_ids
that do not have their past calculated should be passed asinput_ids
.Indices can be obtained using
GPTNeoTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.past_key_values (
Tuple[Tuple[torch.Tensor]]
of lengthconfig.num_layers
) β Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (seepast_key_values
output below). Can be used to speed up sequential decoding. Theinput_ids
which have their past given to this model should not be passed asinput_ids
as they have already been computed.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) βMask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensor
of shape(batch_size, input_ids_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.If
past_key_values
is used, optionally only the lastinputs_embeds
have to be input (seepast_key_values
).use_cache (
bool
, optional) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
instead of a plain tuple.
- Returns
A
BaseModelOutputWithPastAndCrossAttentions
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (GPTNeoConfig
) and inputs.last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.If
past_key_values
is used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)
is output.past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and optionally ifconfig.is_encoder_decoder=True
2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
config.is_encoder_decoder=True
in the cross-attention blocks) that can be used (seepast_key_values
input) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
andconfig.add_cross_attention=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights of the decoderβs cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
- Return type
BaseModelOutputWithPastAndCrossAttentions
ortuple(torch.FloatTensor)
Example:
>>> from transformers import GPT2Tokenizer, GPTNeoModel >>> import torch >>> tokenizer = GPT2Tokenizer.from_pretrained('EleutherAI/gpt-neo-1.3B') >>> model = GPTNeoModel.from_pretrained('EleutherAI/gpt-neo-1.3B') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
GPTNeoForCausalLMΒΆ
-
class
transformers.
GPTNeoForCausalLM
(config)[source]ΒΆ The GPT Neo Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
This model inherits from
PreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
GPTNeoConfig
) β 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 thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, past_key_values=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
GPTNeoForCausalLM
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, input_ids_length)
) βinput_ids_length
=sequence_length
ifpast_key_values
isNone
elsepast_key_values[0][0].shape[-2]
(sequence_length
of input past key value states). Indices of input sequence tokens in the vocabulary.If
past_key_values
is used, onlyinput_ids
that do not have their past calculated should be passed asinput_ids
.Indices can be obtained using
GPTNeoTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.past_key_values (
Tuple[Tuple[torch.Tensor]]
of lengthconfig.num_layers
) β Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (seepast_key_values
output below). Can be used to speed up sequential decoding. Theinput_ids
which have their past given to this model should not be passed asinput_ids
as they have already been computed.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) βMask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
token_type_ids (
torch.LongTensor
of shape(batch_size, input_ids_length)
, optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]
:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
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]
.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 convertinput_ids
indices into associated vectors than the modelβs internal embedding lookup matrix.If
past_key_values
is used, optionally only the lastinputs_embeds
have to be input (seepast_key_values
).use_cache (
bool
, optional) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aModelOutput
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 setlabels = 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]
- Returns
A
CausalLMOutputWithCrossAttentions
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (GPTNeoConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.Cross attentions weights after the attention softmax, used to compute the weighted average in the cross-attention heads.
past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β Tuple oftorch.FloatTensor
tuples of lengthconfig.n_layers
, with each tuple containing the cached key, value states of the self-attention and the cross-attention layers if model is used in encoder-decoder setting. Only relevant ifconfig.is_decoder = True
.Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
past_key_values
input) to speed up sequential decoding.
- Return type
CausalLMOutputWithCrossAttentions
ortuple(torch.FloatTensor)
Example:
>>> import torch >>> from transformers import GPT2Tokenizer, GPTNeoForCausalLM >>> tokenizer = GPT2Tokenizer.from_pretrained('EleutherAI/gpt-neo-1.3B') >>> model = GPTNeoForCausalLM.from_pretrained('EleutherAI/gpt-neo-1.3B') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs, labels=inputs["input_ids"]) >>> loss = outputs.loss >>> logits = outputs.logits