The Gemma2 model was proposed in Gemma2: Open Models Based on Gemini Technology and Research by Gemma2 Team, Google. Two Gemma2 models are released, with parameters sizes of 9 billion (9B) and 27 billion (27B).
The abstract from the blog post is the following:
Now we’re officially releasing Gemma 2 to researchers and developers globally. Available in both 9 billion (9B) and 27 billion (27B) parameter sizes, Gemma 2 is higher-performing and more efficient at inference than the first generation, with significant safety advancements built in. In fact, at 27B, it offers competitive alternatives to models more than twice its size, delivering the kind of performance that was only possible with proprietary models as recently as December.
Tips:
src/transformers/models/Gemma2/convert_Gemma2_weights_to_hf.pyThis model was contributed by Arthur Zucker, Pedro Cuenca and Tom Arsen.
( vocab_size = 256000 hidden_size = 3072 intermediate_size = 24576 num_hidden_layers = 28 num_attention_heads = 16 num_key_value_heads = 16 head_dim = 256 hidden_activation = 'gelu_pytorch_tanh' max_position_embeddings = 8192 initializer_range = 0.02 rms_norm_eps = 1e-06 use_cache = True pad_token_id = 0 eos_token_id = 1 bos_token_id = 2 tie_word_embeddings = True rope_theta = 10000.0 rope_scaling = None attention_bias = False attention_dropout = 0.0 final_logit_softcapping = 30.0 attn_logit_softcapping = 50.0 query_pre_attn_scalar = 224 sliding_window = 4096 **kwargs )
( config: Gemma2Config )
Parameters
The bare Gemma2 Model 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.
Transformer decoder consisting of config.num_hidden_layers layers. Each layer is a Gemma2DecoderLayer
( input_ids: LongTensor = None attention_mask: Optional = None position_ids: Optional = None past_key_values: Union = None inputs_embeds: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None cache_position: Optional = None position_embeddings: Optional = None )
Parameters
torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If past_key_values is used, optionally only the last input_ids have to be input (see
past_key_values).
If you want to change padding behavior, you should read modeling_opt._prepare_decoder_attention_mask
and modify to your needs. See diagram 1 in the paper for more
information on the default strategy.
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.n_positions - 1].
Cache or tuple(tuple(torch.FloatTensor)), optional) —
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values
returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.
Two formats are allowed:
tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of
shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy
cache format.The model will output the same cache format that is fed as input. If no past_key_values are passed, the
legacy cache format will be returned.
If past_key_values are used, the user can optionally input only the last input_ids (those that don’t
have their past key value states given to this model) of shape (batch_size, 1) instead of all input_ids
of shape (batch_size, sequence_length).
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. bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values). bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail. bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail. bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. torch.LongTensor of shape (sequence_length), optional) —
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids,
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
the complete sequence length. Tuple[torch.FloatTensor, torch.FloatTensor], optional) —
Tuple containing the cosine and sine positional embeddings of shape (batch_size, seq_len, head_dim),
with head_dim being the embedding dimension of each attention head. This input is used to dynamically
overwrite the default positional embeddings. The Gemma2Model forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
( input_ids: LongTensor = None attention_mask: Optional = None position_ids: Optional = None past_key_values: Union = None inputs_embeds: Optional = None labels: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None cache_position: Optional = None position_embeddings: Optional = None ) → transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)
Parameters
torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If past_key_values is used, optionally only the last input_ids have to be input (see
past_key_values).
If you want to change padding behavior, you should read modeling_opt._prepare_decoder_attention_mask
and modify to your needs. See diagram 1 in the paper for more
information on the default strategy.
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.n_positions - 1].
Cache or tuple(tuple(torch.FloatTensor)), optional) —
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values
returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.
Two formats are allowed:
tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of
shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy
cache format.The model will output the same cache format that is fed as input. If no past_key_values are passed, the
legacy cache format will be returned.
If past_key_values are used, the user can optionally input only the last input_ids (those that don’t
have their past key value states given to this model) of shape (batch_size, 1) instead of all input_ids
of shape (batch_size, sequence_length).
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. bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values). bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail. bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail. bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. torch.LongTensor of shape (sequence_length), optional) —
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids,
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
the complete sequence length. Tuple[torch.FloatTensor, torch.FloatTensor], optional) —
Tuple containing the cosine and sine positional embeddings of shape (batch_size, seq_len, head_dim),
with head_dim being the embedding dimension of each attention head. This input is used to dynamically
overwrite the default positional embeddings.
Args —
labels (torch.LongTensor of shape (batch_size, sequence_length), optional):
Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored
(masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
Returns
transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)
A transformers.modeling_outputs.CausalLMOutputWithPast 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 (Gemma2Config) 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).
past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) — Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape
(batch_size, num_heads, sequence_length, embed_size_per_head))
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
past_key_values input) to speed up sequential decoding.
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
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 optional 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.
The Gemma2ForCausalLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example:
>>> from transformers import AutoTokenizer, GemmaForCausalLM
>>> model = GemmaForCausalLM.from_pretrained("google/gemma-2-9b")
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is your favorite condiment?"( config )
Parameters
The Gemma2 Model transformer with a sequence classification head on top (linear layer).
Gemma2ForSequenceClassification 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. 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.
( input_ids: LongTensor = None attention_mask: Optional = None position_ids: Optional = None past_key_values: Union = None inputs_embeds: Optional = None labels: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None position_embeddings: Optional = None )
Parameters
torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If past_key_values is used, optionally only the last input_ids have to be input (see
past_key_values).
If you want to change padding behavior, you should read modeling_opt._prepare_decoder_attention_mask
and modify to your needs. See diagram 1 in the paper for more
information on the default strategy.
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.n_positions - 1].
Cache or tuple(tuple(torch.FloatTensor)), optional) —
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values
returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.
Two formats are allowed:
tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of
shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy
cache format.The model will output the same cache format that is fed as input. If no past_key_values are passed, the
legacy cache format will be returned.
If past_key_values are used, the user can optionally input only the last input_ids (those that don’t
have their past key value states given to this model) of shape (batch_size, 1) instead of all input_ids
of shape (batch_size, sequence_length).
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. bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values). bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail. bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail. bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. torch.LongTensor of shape (sequence_length), optional) —
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids,
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
the complete sequence length. Tuple[torch.FloatTensor, torch.FloatTensor], optional) —
Tuple containing the cosine and sine positional embeddings of shape (batch_size, seq_len, head_dim),
with head_dim being the embedding dimension of each attention head. This input is used to dynamically
overwrite the default positional embeddings. 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). The Gemma2ForSequenceClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
( config )
Parameters
The Gemma2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
This model inherits from PreTrainedModel. 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.
( input_ids: Optional = None attention_mask: Optional = None position_ids: Optional = None past_key_values: Optional = None inputs_embeds: Optional = None labels: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None position_embeddings: Optional = None )
Parameters
torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
torch.Tensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
If past_key_values is used, optionally only the last input_ids have to be input (see
past_key_values).
If you want to change padding behavior, you should read modeling_opt._prepare_decoder_attention_mask
and modify to your needs. See diagram 1 in the paper for more
information on the default strategy.
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.n_positions - 1].
Cache or tuple(tuple(torch.FloatTensor)), optional) —
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values
returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.
Two formats are allowed:
tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of
shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy
cache format.The model will output the same cache format that is fed as input. If no past_key_values are passed, the
legacy cache format will be returned.
If past_key_values are used, the user can optionally input only the last input_ids (those that don’t
have their past key value states given to this model) of shape (batch_size, 1) instead of all input_ids
of shape (batch_size, sequence_length).
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. bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values). bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail. bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail. bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple. torch.LongTensor of shape (sequence_length), optional) —
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids,
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
the complete sequence length. Tuple[torch.FloatTensor, torch.FloatTensor], optional) —
Tuple containing the cosine and sine positional embeddings of shape (batch_size, seq_len, head_dim),
with head_dim being the embedding dimension of each attention head. This input is used to dynamically
overwrite the default positional embeddings. 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). The Gemma2ForTokenClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.