d-Matrix commited on
Commit
0c80f2e
·
verified ·
1 Parent(s): 0cd2fb7

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_gemma.py +149 -0
  2. modeling_gemma.py +1320 -0
configuration_gemma.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Gemma model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ class GemmaConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`GemmaModel`]. It is used to instantiate an Gemma
26
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
27
+ defaults will yield a similar configuration to that of the Gemma-7B.
28
+
29
+ e.g. [google/gemma-7b](https://huggingface.co/google/gemma-7b)
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 256000):
37
+ Vocabulary size of the Gemma model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`GemmaModel`]
39
+ hidden_size (`int`, *optional*, defaults to 3072):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 24576):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 28):
44
+ Number of hidden layers in the Transformer decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 16):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 16):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
54
+ `num_attention_heads`.
55
+ head_dim (`int`, *optional*, defaults to 256):
56
+ The attention head dimension.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
58
+ The legacy activation function. It is overwritten by the `hidden_activation`.
59
+ hidden_activation (`str` or `function`, *optional*):
60
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
61
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
62
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
63
+ The maximum sequence length that this model might ever be used with.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*, defaults to 0):
72
+ Padding token id.
73
+ eos_token_id (`int`, *optional*, defaults to 1):
74
+ End of stream token id.
75
+ bos_token_id (`int`, *optional*, defaults to 2):
76
+ Beginning of stream token id.
77
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
78
+ Whether to tie weight embeddings
79
+ rope_theta (`float`, *optional*, defaults to 10000.0):
80
+ The base period of the RoPE embeddings.
81
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
82
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
83
+ attention_dropout (`float`, *optional*, defaults to 0.0):
84
+ The dropout ratio for the attention probabilities.
85
+
86
+ ```python
87
+ >>> from transformers import GemmaModel, GemmaConfig
88
+
89
+ >>> # Initializing a Gemma gemma-7b style configuration
90
+ >>> configuration = GemmaConfig()
91
+
92
+ >>> # Initializing a model from the gemma-7b style configuration
93
+ >>> model = GemmaModel(configuration)
94
+
95
+ >>> # Accessing the model configuration
96
+ >>> configuration = model.config
97
+ ```"""
98
+
99
+ model_type = "gemma"
100
+ keys_to_ignore_at_inference = ["past_key_values"]
101
+
102
+ def __init__(
103
+ self,
104
+ vocab_size=256000,
105
+ hidden_size=3072,
106
+ intermediate_size=24576,
107
+ num_hidden_layers=28,
108
+ num_attention_heads=16,
109
+ num_key_value_heads=16,
110
+ head_dim=256,
111
+ hidden_act="gelu_pytorch_tanh",
112
+ hidden_activation=None,
113
+ max_position_embeddings=8192,
114
+ initializer_range=0.02,
115
+ rms_norm_eps=1e-6,
116
+ use_cache=True,
117
+ pad_token_id=0,
118
+ eos_token_id=1,
119
+ bos_token_id=2,
120
+ tie_word_embeddings=True,
121
+ rope_theta=10000.0,
122
+ attention_bias=False,
123
+ attention_dropout=0.0,
124
+ **kwargs,
125
+ ):
126
+ self.vocab_size = vocab_size
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.hidden_size = hidden_size
129
+ self.intermediate_size = intermediate_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+ self.head_dim = head_dim
133
+ self.num_key_value_heads = num_key_value_heads
134
+ self.hidden_act = hidden_act
135
+ self.hidden_activation = hidden_activation
136
+ self.initializer_range = initializer_range
137
+ self.rms_norm_eps = rms_norm_eps
138
+ self.use_cache = use_cache
139
+ self.rope_theta = rope_theta
140
+ self.attention_bias = attention_bias
141
+ self.attention_dropout = attention_dropout
142
+
143
+ super().__init__(
144
+ pad_token_id=pad_token_id,
145
+ bos_token_id=bos_token_id,
146
+ eos_token_id=eos_token_id,
147
+ tie_word_embeddings=tie_word_embeddings,
148
+ **kwargs,
149
+ )
modeling_gemma.py ADDED
@@ -0,0 +1,1320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch Gemma model."""
17
+ import math
18
+ import warnings
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache, StaticCache
29
+ from ...modeling_attn_mask_utils import (
30
+ _prepare_4d_causal_attention_mask,
31
+ )
32
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
35
+ from ...utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from ...utils.import_utils import is_torch_fx_available
44
+ from .configuration_gemma import GemmaConfig
45
+
46
+
47
+ if is_flash_attn_2_available():
48
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
49
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
50
+
51
+
52
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
53
+ # It means that the function will not be traced through and simply appear as a node in the graph.
54
+ if is_torch_fx_available():
55
+ if not is_torch_greater_or_equal_than_1_13:
56
+ import torch.fx
57
+
58
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CONFIG_FOR_DOC = "GemmaConfig"
64
+
65
+
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
71
+ return (
72
+ indices,
73
+ cu_seqlens,
74
+ max_seqlen_in_batch,
75
+ )
76
+
77
+
78
+ class GemmaRMSNorm(nn.Module):
79
+ def __init__(self, dim: int, eps: float = 1e-6):
80
+ super().__init__()
81
+ self.eps = eps
82
+ self.weight = nn.Parameter(torch.zeros(dim))
83
+
84
+ def _norm(self, x):
85
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
86
+
87
+ def forward(self, x):
88
+ output = self._norm(x.float()).type_as(x)
89
+ return output.to(self.weight.device) * (1 + self.weight)
90
+
91
+
92
+ ALL_LAYERNORM_LAYERS.append(GemmaRMSNorm)
93
+
94
+
95
+ class GemmaRotaryEmbedding(nn.Module):
96
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
97
+ super().__init__()
98
+
99
+ self.dim = dim
100
+ self.max_position_embeddings = max_position_embeddings
101
+ self.base = base
102
+ # self.register_buffer("inv_freq", None, persistent=False)
103
+ self.inv_freq = None
104
+
105
+ @torch.no_grad()
106
+ def forward(self, x, position_ids, seq_len=None):
107
+ # x: [bs, num_attention_heads, seq_len, head_size]
108
+ if self.inv_freq is None:
109
+ self.inv_freq = 1.0 / (
110
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
111
+ )
112
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
113
+ position_ids_expanded = position_ids[:, None, :].float().to(x.device)
114
+ # Force float32 since bfloat16 loses precision on long contexts
115
+ # See https://github.com/huggingface/transformers/pull/29285
116
+ device_type = x.device.type
117
+ device_type = device_type if isinstance(device_type, str) else "cpu"
118
+ with torch.autocast(device_type=device_type, enabled=False):
119
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
120
+ emb = torch.cat((freqs, freqs), dim=-1)
121
+ cos = emb.cos()
122
+ sin = emb.sin()
123
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
124
+
125
+
126
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
127
+ def rotate_half(x):
128
+ """Rotates half the hidden dims of the input."""
129
+ x1 = x[..., : x.shape[-1] // 2]
130
+ x2 = x[..., x.shape[-1] // 2 :]
131
+ return torch.cat((-x2, x1), dim=-1)
132
+
133
+
134
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
135
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
136
+ """Applies Rotary Position Embedding to the query and key tensors.
137
+
138
+ Args:
139
+ q (`torch.Tensor`): The query tensor.
140
+ k (`torch.Tensor`): The key tensor.
141
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
142
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
143
+ position_ids (`torch.Tensor`, *optional*):
144
+ Deprecated and unused.
145
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
146
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
147
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
148
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
149
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
150
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
151
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
152
+ Returns:
153
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
154
+ """
155
+ cos = cos.unsqueeze(unsqueeze_dim)
156
+ sin = sin.unsqueeze(unsqueeze_dim)
157
+ q_embed = (q * cos) + (rotate_half(q) * sin)
158
+ k_embed = (k * cos) + (rotate_half(k) * sin)
159
+ return q_embed, k_embed
160
+
161
+
162
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Gemma
163
+ class GemmaMLP(nn.Module):
164
+ def __init__(self, config):
165
+ super().__init__()
166
+ self.config = config
167
+ self.hidden_size = config.hidden_size
168
+ self.intermediate_size = config.intermediate_size
169
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
170
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
171
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
172
+ self.act_fn = ACT2FN[config.hidden_act]
173
+
174
+ def forward(self, x):
175
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
176
+
177
+
178
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
179
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
180
+ """
181
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
182
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
183
+ """
184
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
185
+ if n_rep == 1:
186
+ return hidden_states
187
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
188
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
189
+
190
+
191
+ class GemmaAttention(nn.Module):
192
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
193
+
194
+ # Ignore copy
195
+ def __init__(self, config: GemmaConfig, layer_idx: Optional[int] = None):
196
+ super().__init__()
197
+ self.config = config
198
+ self.layer_idx = layer_idx
199
+ if layer_idx is None:
200
+ logger.warning_once(
201
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
202
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
203
+ "when creating this class."
204
+ )
205
+
206
+ self.attention_dropout = config.attention_dropout
207
+ self.hidden_size = config.hidden_size
208
+ self.num_heads = config.num_attention_heads
209
+ self.head_dim = config.head_dim
210
+ self.num_key_value_heads = config.num_key_value_heads
211
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
212
+ self.max_position_embeddings = config.max_position_embeddings
213
+ self.rope_theta = config.rope_theta
214
+ self.is_causal = True
215
+
216
+ if self.hidden_size % self.num_heads != 0:
217
+ raise ValueError(
218
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
219
+ f" and `num_heads`: {self.num_heads})."
220
+ )
221
+
222
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
223
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
224
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
225
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
226
+ self.rotary_emb = GemmaRotaryEmbedding(
227
+ self.head_dim,
228
+ max_position_embeddings=self.max_position_embeddings,
229
+ base=self.rope_theta,
230
+ )
231
+
232
+ def forward(
233
+ self,
234
+ hidden_states: torch.Tensor,
235
+ attention_mask: Optional[torch.Tensor] = None,
236
+ position_ids: Optional[torch.LongTensor] = None,
237
+ past_key_value: Optional[Cache] = None,
238
+ output_attentions: bool = False,
239
+ use_cache: bool = False,
240
+ cache_position: Optional[torch.LongTensor] = None,
241
+ **kwargs,
242
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
243
+ bsz, q_len, _ = hidden_states.size()
244
+
245
+ query_states = self.q_proj(hidden_states)
246
+ key_states = self.k_proj(hidden_states)
247
+ value_states = self.v_proj(hidden_states)
248
+
249
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
250
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
251
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
252
+
253
+ past_key_value = getattr(self, "past_key_value", past_key_value)
254
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
255
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
256
+
257
+ if past_key_value is not None:
258
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
259
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
260
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
261
+
262
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
263
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
264
+
265
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
266
+
267
+ if attention_mask is not None: # no matter the length, we just slice it
268
+ if cache_position is not None:
269
+ causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
270
+ else:
271
+ causal_mask = attention_mask
272
+ attn_weights = attn_weights + causal_mask
273
+
274
+ # upcast attention to fp32
275
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
276
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
277
+ attn_output = torch.matmul(attn_weights, value_states)
278
+
279
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
280
+ raise ValueError(
281
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
282
+ f" {attn_output.size()}"
283
+ )
284
+
285
+ attn_output = attn_output.transpose(1, 2).contiguous()
286
+
287
+ attn_output = attn_output.view(bsz, q_len, -1)
288
+ attn_output = self.o_proj(attn_output)
289
+
290
+ if not output_attentions:
291
+ attn_weights = None
292
+
293
+ return attn_output, attn_weights, past_key_value
294
+
295
+
296
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Gemma
297
+ class GemmaFlashAttention2(GemmaAttention):
298
+ """
299
+ Gemma flash attention module. This module inherits from `GemmaAttention` as the weights of the module stays
300
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
301
+ flash attention and deal with padding tokens in case the input contains any of them.
302
+ """
303
+
304
+ def __init__(self, *args, **kwargs):
305
+ super().__init__(*args, **kwargs)
306
+
307
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
308
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
309
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
310
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
311
+
312
+ # Ignore copy
313
+ def forward(
314
+ self,
315
+ hidden_states: torch.Tensor,
316
+ attention_mask: Optional[torch.LongTensor] = None,
317
+ position_ids: Optional[torch.LongTensor] = None,
318
+ past_key_value: Optional[Cache] = None,
319
+ output_attentions: bool = False,
320
+ use_cache: bool = False,
321
+ cache_position: Optional[torch.LongTensor] = None,
322
+ **kwargs,
323
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
324
+ output_attentions = False
325
+
326
+ bsz, q_len, _ = hidden_states.size()
327
+
328
+ query_states = self.q_proj(hidden_states)
329
+ key_states = self.k_proj(hidden_states)
330
+ value_states = self.v_proj(hidden_states)
331
+
332
+ # Flash attention requires the input to have the shape
333
+ # batch_size x seq_length x head_dim x hidden_dim
334
+ # therefore we just need to keep the original shape
335
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
336
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
337
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
338
+
339
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
340
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
341
+
342
+ past_key_value = getattr(self, "past_key_value", past_key_value)
343
+
344
+ if past_key_value is not None:
345
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
346
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
347
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
348
+
349
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
350
+ # to be able to avoid many of these transpose/reshape/view.
351
+ query_states = query_states.transpose(1, 2)
352
+ key_states = key_states.transpose(1, 2)
353
+ value_states = value_states.transpose(1, 2)
354
+
355
+ dropout_rate = self.attention_dropout if self.training else 0.0
356
+
357
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
358
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
359
+ # cast them back in the correct dtype just to be sure everything works as expected.
360
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
361
+ # in fp32. (GemmaRMSNorm handles it correctly)
362
+
363
+ input_dtype = query_states.dtype
364
+ if input_dtype == torch.float32:
365
+ if torch.is_autocast_enabled():
366
+ target_dtype = torch.get_autocast_gpu_dtype()
367
+ # Handle the case where the model is quantized
368
+ elif hasattr(self.config, "_pre_quantization_dtype"):
369
+ target_dtype = self.config._pre_quantization_dtype
370
+ else:
371
+ target_dtype = self.q_proj.weight.dtype
372
+
373
+ logger.warning_once(
374
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
375
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
376
+ f" {target_dtype}."
377
+ )
378
+
379
+ query_states = query_states.to(target_dtype)
380
+ key_states = key_states.to(target_dtype)
381
+ value_states = value_states.to(target_dtype)
382
+
383
+ attn_output = self._flash_attention_forward(
384
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
385
+ )
386
+
387
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
388
+ attn_output = self.o_proj(attn_output)
389
+
390
+ if not output_attentions:
391
+ attn_weights = None
392
+
393
+ return attn_output, attn_weights, past_key_value
394
+
395
+ def _flash_attention_forward(
396
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
397
+ ):
398
+ """
399
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
400
+ first unpad the input, then computes the attention scores and pad the final attention scores.
401
+
402
+ Args:
403
+ query_states (`torch.Tensor`):
404
+ Input query states to be passed to Flash Attention API
405
+ key_states (`torch.Tensor`):
406
+ Input key states to be passed to Flash Attention API
407
+ value_states (`torch.Tensor`):
408
+ Input value states to be passed to Flash Attention API
409
+ attention_mask (`torch.Tensor`):
410
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
411
+ position of padding tokens and 1 for the position of non-padding tokens.
412
+ dropout (`int`, *optional*):
413
+ Attention dropout
414
+ softmax_scale (`float`, *optional*):
415
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
416
+ """
417
+ if not self._flash_attn_uses_top_left_mask:
418
+ causal = self.is_causal
419
+ else:
420
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in GemmaFlashAttention2 __init__.
421
+ causal = self.is_causal and query_length != 1
422
+
423
+ # Contains at least one padding token in the sequence
424
+ if attention_mask is not None:
425
+ batch_size = query_states.shape[0]
426
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
427
+ query_states, key_states, value_states, attention_mask, query_length
428
+ )
429
+
430
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
431
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
432
+
433
+ attn_output_unpad = flash_attn_varlen_func(
434
+ query_states,
435
+ key_states,
436
+ value_states,
437
+ cu_seqlens_q=cu_seqlens_q,
438
+ cu_seqlens_k=cu_seqlens_k,
439
+ max_seqlen_q=max_seqlen_in_batch_q,
440
+ max_seqlen_k=max_seqlen_in_batch_k,
441
+ dropout_p=dropout,
442
+ softmax_scale=softmax_scale,
443
+ causal=causal,
444
+ )
445
+
446
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
447
+ else:
448
+ attn_output = flash_attn_func(
449
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
450
+ )
451
+
452
+ return attn_output
453
+
454
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
455
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
456
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
457
+
458
+ key_layer = index_first_axis(
459
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
460
+ )
461
+ value_layer = index_first_axis(
462
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
463
+ )
464
+ if query_length == kv_seq_len:
465
+ query_layer = index_first_axis(
466
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
467
+ )
468
+ cu_seqlens_q = cu_seqlens_k
469
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
470
+ indices_q = indices_k
471
+ elif query_length == 1:
472
+ max_seqlen_in_batch_q = 1
473
+ cu_seqlens_q = torch.arange(
474
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
475
+ ) # There is a memcpy here, that is very bad.
476
+ indices_q = cu_seqlens_q[:-1]
477
+ query_layer = query_layer.squeeze(1)
478
+ else:
479
+ # The -q_len: slice assumes left padding.
480
+ attention_mask = attention_mask[:, -query_length:]
481
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
482
+
483
+ return (
484
+ query_layer,
485
+ key_layer,
486
+ value_layer,
487
+ indices_q,
488
+ (cu_seqlens_q, cu_seqlens_k),
489
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
490
+ )
491
+
492
+
493
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Gemma
494
+ class GemmaSdpaAttention(GemmaAttention):
495
+ """
496
+ Gemma attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
497
+ `GemmaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
498
+ SDPA API.
499
+ """
500
+
501
+ # Ignore copy
502
+ def forward(
503
+ self,
504
+ hidden_states: torch.Tensor,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ position_ids: Optional[torch.LongTensor] = None,
507
+ past_key_value: Optional[Cache] = None,
508
+ output_attentions: bool = False,
509
+ use_cache: bool = False,
510
+ cache_position: Optional[torch.LongTensor] = None,
511
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
512
+ if output_attentions:
513
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
514
+ logger.warning_once(
515
+ "GemmaModel is using GemmaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
516
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
517
+ )
518
+ return super().forward(
519
+ hidden_states=hidden_states,
520
+ attention_mask=attention_mask,
521
+ position_ids=position_ids,
522
+ past_key_value=past_key_value,
523
+ output_attentions=output_attentions,
524
+ use_cache=use_cache,
525
+ cache_position=cache_position,
526
+ )
527
+
528
+ bsz, q_len, _ = hidden_states.size()
529
+
530
+ query_states = self.q_proj(hidden_states)
531
+ key_states = self.k_proj(hidden_states)
532
+ value_states = self.v_proj(hidden_states)
533
+
534
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
535
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
536
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
537
+
538
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
539
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
540
+
541
+ past_key_value = getattr(self, "past_key_value", past_key_value)
542
+
543
+ if past_key_value is not None:
544
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
545
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
546
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
547
+
548
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
549
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
550
+
551
+ causal_mask = attention_mask
552
+ if attention_mask is not None and cache_position is not None:
553
+ causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
554
+
555
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
556
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
557
+ if query_states.device.type == "cuda" and causal_mask is not None:
558
+ query_states = query_states.contiguous()
559
+ key_states = key_states.contiguous()
560
+ value_states = value_states.contiguous()
561
+
562
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
563
+ query_states,
564
+ key_states,
565
+ value_states,
566
+ attn_mask=causal_mask.to(query_states.device),
567
+ dropout_p=self.attention_dropout if self.training else 0.0,
568
+ )
569
+
570
+ attn_output = attn_output.transpose(1, 2).contiguous()
571
+ attn_output = attn_output.view(bsz, q_len, -1)
572
+
573
+ attn_output = self.o_proj(attn_output)
574
+
575
+ return attn_output, None, past_key_value
576
+
577
+
578
+ GEMMA_ATTENTION_CLASSES = {
579
+ "eager": GemmaAttention,
580
+ "flash_attention_2": GemmaFlashAttention2,
581
+ "sdpa": GemmaSdpaAttention,
582
+ }
583
+
584
+
585
+ # Copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with LLAMA->GEMMA,Llama->Gemma
586
+ class GemmaDecoderLayer(nn.Module):
587
+ def __init__(self, config: GemmaConfig, layer_idx: int):
588
+ super().__init__()
589
+ self.hidden_size = config.hidden_size
590
+
591
+ self.self_attn = GEMMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
592
+
593
+ self.mlp = GemmaMLP(config)
594
+ self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
595
+ self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
596
+
597
+ def forward(
598
+ self,
599
+ hidden_states: torch.Tensor,
600
+ attention_mask: Optional[torch.Tensor] = None,
601
+ position_ids: Optional[torch.LongTensor] = None,
602
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
603
+ output_attentions: Optional[bool] = False,
604
+ use_cache: Optional[bool] = False,
605
+ cache_position: Optional[torch.LongTensor] = None,
606
+ **kwargs,
607
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
608
+ """
609
+ Args:
610
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
611
+ attention_mask (`torch.FloatTensor`, *optional*):
612
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
613
+ query_sequence_length, key_sequence_length)` if default attention is used.
614
+ output_attentions (`bool`, *optional*):
615
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
616
+ returned tensors for more detail.
617
+ use_cache (`bool`, *optional*):
618
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
619
+ (see `past_key_values`).
620
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
621
+ """
622
+ if "padding_mask" in kwargs:
623
+ warnings.warn(
624
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
625
+ )
626
+
627
+ residual = hidden_states
628
+
629
+ hidden_states = self.input_layernorm(hidden_states)
630
+
631
+ # Self Attention
632
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
633
+ hidden_states=hidden_states,
634
+ attention_mask=attention_mask,
635
+ position_ids=position_ids,
636
+ past_key_value=past_key_value,
637
+ output_attentions=output_attentions,
638
+ use_cache=use_cache,
639
+ cache_position=cache_position,
640
+ **kwargs,
641
+ )
642
+ hidden_states = residual.to(hidden_states.device) + hidden_states
643
+
644
+ # Fully Connected
645
+ residual = hidden_states
646
+ hidden_states = self.post_attention_layernorm(hidden_states)
647
+ hidden_states = self.mlp(hidden_states)
648
+ hidden_states = residual + hidden_states
649
+ outputs = (hidden_states,)
650
+
651
+ if output_attentions:
652
+ outputs += (self_attn_weights,)
653
+
654
+ if use_cache:
655
+ outputs += (present_key_value,)
656
+
657
+ return outputs
658
+
659
+
660
+ GEMMA_START_DOCSTRING = r"""
661
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
662
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
663
+ etc.)
664
+
665
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
666
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
667
+ and behavior.
668
+
669
+ Parameters:
670
+ config ([`GemmaConfig`]):
671
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
672
+ load the weights associated with the model, only the configuration. Check out the
673
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
674
+ """
675
+
676
+
677
+ @add_start_docstrings(
678
+ "The bare Gemma Model outputting raw hidden-states without any specific head on top.",
679
+ GEMMA_START_DOCSTRING,
680
+ )
681
+ class GemmaPreTrainedModel(PreTrainedModel):
682
+ config_class = GemmaConfig
683
+ base_model_prefix = "model"
684
+ supports_gradient_checkpointing = True
685
+ _keep_in_fp32_modules = ["inv_freq", "rotary_emb", "cos_cached", "sin_cached"]
686
+ _no_split_modules = ["GemmaDecoderLayer"]
687
+ _skip_keys_device_placement = ["past_key_values", "causal_mask"]
688
+ _supports_flash_attn_2 = True
689
+ _supports_sdpa = True
690
+ _supports_cache_class = True
691
+
692
+ def _init_weights(self, module):
693
+ std = self.config.initializer_range
694
+ if isinstance(module, nn.Linear):
695
+ module.weight.data.normal_(mean=0.0, std=std)
696
+ if module.bias is not None:
697
+ module.bias.data.zero_()
698
+ elif isinstance(module, nn.Embedding):
699
+ module.weight.data.normal_(mean=0.0, std=std)
700
+ if module.padding_idx is not None:
701
+ module.weight.data[module.padding_idx].zero_()
702
+
703
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
704
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
705
+ raise ValueError(
706
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
707
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
708
+ )
709
+
710
+ if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
711
+ causal_mask = torch.full((max_cache_len, max_cache_len), fill_value=1, device=self.device)
712
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
713
+
714
+ for layer in self.model.layers:
715
+ weights = layer.self_attn.o_proj.weight
716
+ layer.self_attn.past_key_value = cache_cls(
717
+ self.config, max_batch_size, max_cache_len, device=weights.device, dtype=weights.dtype
718
+ )
719
+
720
+ def _reset_cache(self):
721
+ for layer in self.model.layers:
722
+ layer.self_attn.past_key_value = None
723
+
724
+
725
+ GEMMA_INPUTS_DOCSTRING = r"""
726
+ Args:
727
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
728
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
729
+ it.
730
+
731
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
732
+ [`PreTrainedTokenizer.__call__`] for details.
733
+
734
+ [What are input IDs?](../glossary#input-ids)
735
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
736
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
737
+
738
+ - 1 for tokens that are **not masked**,
739
+ - 0 for tokens that are **masked**.
740
+
741
+ [What are attention masks?](../glossary#attention-mask)
742
+
743
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
744
+ [`PreTrainedTokenizer.__call__`] for details.
745
+
746
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
747
+ `past_key_values`).
748
+
749
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
750
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
751
+ information on the default strategy.
752
+
753
+ - 1 indicates the head is **not masked**,
754
+ - 0 indicates the head is **masked**.
755
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
756
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
757
+ config.n_positions - 1]`.
758
+
759
+ [What are position IDs?](../glossary#position-ids)
760
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
761
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
762
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
763
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
764
+
765
+ Two formats are allowed:
766
+ - a [`~cache_utils.Cache`] instance;
767
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
768
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
769
+ cache format.
770
+
771
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
772
+ legacy cache format will be returned.
773
+
774
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
775
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
776
+ of shape `(batch_size, sequence_length)`.
777
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
778
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
779
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
780
+ model's internal embedding lookup matrix.
781
+ use_cache (`bool`, *optional*):
782
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
783
+ `past_key_values`).
784
+ output_attentions (`bool`, *optional*):
785
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
786
+ tensors for more detail.
787
+ output_hidden_states (`bool`, *optional*):
788
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
789
+ more detail.
790
+ return_dict (`bool`, *optional*):
791
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
792
+ """
793
+
794
+
795
+ @add_start_docstrings(
796
+ "The bare Gemma Model outputting raw hidden-states without any specific head on top.",
797
+ GEMMA_START_DOCSTRING,
798
+ )
799
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel with LLAMA->GEMMA,Llama->Gemma
800
+ class GemmaModel(GemmaPreTrainedModel):
801
+ """
802
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GemmaDecoderLayer`]
803
+
804
+ Args:
805
+ config: GemmaConfig
806
+ """
807
+
808
+ def __init__(self, config: GemmaConfig):
809
+ super().__init__(config)
810
+ self.padding_idx = config.pad_token_id
811
+ self.vocab_size = config.vocab_size
812
+
813
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
814
+ self.layers = nn.ModuleList(
815
+ [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
816
+ )
817
+ self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
818
+ self.gradient_checkpointing = False
819
+
820
+ # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
821
+ # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
822
+ causal_mask = torch.full(
823
+ (config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool
824
+ )
825
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
826
+ # Initialize weights and apply final processing
827
+ self.post_init()
828
+
829
+ def get_input_embeddings(self):
830
+ return self.embed_tokens
831
+
832
+ def set_input_embeddings(self, value):
833
+ self.embed_tokens = value
834
+
835
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
836
+ # Ignore copy
837
+ def forward(
838
+ self,
839
+ input_ids: torch.LongTensor = None,
840
+ attention_mask: Optional[torch.Tensor] = None,
841
+ position_ids: Optional[torch.LongTensor] = None,
842
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
843
+ inputs_embeds: Optional[torch.FloatTensor] = None,
844
+ use_cache: Optional[bool] = None,
845
+ output_attentions: Optional[bool] = None,
846
+ output_hidden_states: Optional[bool] = None,
847
+ return_dict: Optional[bool] = None,
848
+ cache_position: Optional[torch.LongTensor] = None,
849
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
850
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
851
+ output_hidden_states = (
852
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
853
+ )
854
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
855
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
856
+
857
+ if (input_ids is None) ^ (inputs_embeds is not None):
858
+ raise ValueError(
859
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
860
+ )
861
+
862
+ if self.gradient_checkpointing and self.training and use_cache:
863
+ logger.warning_once(
864
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
865
+ )
866
+ use_cache = False
867
+
868
+ if inputs_embeds is None:
869
+ inputs_embeds = self.embed_tokens(input_ids)
870
+
871
+ past_seen_tokens = 0
872
+ if use_cache: # kept for BC (cache positions)
873
+ if not isinstance(past_key_values, StaticCache):
874
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
875
+ past_seen_tokens = past_key_values.get_seq_length()
876
+
877
+ if cache_position is None:
878
+ cache_position = torch.arange(
879
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
880
+ )
881
+
882
+ if position_ids is None:
883
+ position_ids = cache_position.unsqueeze(0)
884
+
885
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
886
+
887
+ # embed positions
888
+ hidden_states = inputs_embeds
889
+
890
+ # normalized
891
+ hidden_states = hidden_states * (self.config.hidden_size**0.5)
892
+
893
+ # decoder layers
894
+ all_hidden_states = () if output_hidden_states else None
895
+ all_self_attns = () if output_attentions else None
896
+ next_decoder_cache = None
897
+
898
+ for decoder_layer in self.layers:
899
+ if output_hidden_states:
900
+ all_hidden_states += (hidden_states,)
901
+
902
+ if self.gradient_checkpointing and self.training:
903
+ layer_outputs = self._gradient_checkpointing_func(
904
+ decoder_layer.__call__,
905
+ hidden_states,
906
+ causal_mask,
907
+ position_ids,
908
+ past_key_values,
909
+ output_attentions,
910
+ use_cache,
911
+ cache_position,
912
+ )
913
+ else:
914
+ layer_outputs = decoder_layer(
915
+ hidden_states,
916
+ attention_mask=causal_mask,
917
+ position_ids=position_ids,
918
+ past_key_value=past_key_values,
919
+ output_attentions=output_attentions,
920
+ use_cache=use_cache,
921
+ cache_position=cache_position,
922
+ )
923
+
924
+ hidden_states = layer_outputs[0]
925
+
926
+ if use_cache:
927
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
928
+
929
+ if output_attentions:
930
+ all_self_attns += (layer_outputs[1],)
931
+
932
+ hidden_states = self.norm(hidden_states)
933
+
934
+ # add hidden states from the last decoder layer
935
+ if output_hidden_states:
936
+ all_hidden_states += (hidden_states,)
937
+
938
+ next_cache = None
939
+ if use_cache:
940
+ next_cache = (
941
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
942
+ )
943
+ if not return_dict:
944
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
945
+ return BaseModelOutputWithPast(
946
+ last_hidden_state=hidden_states,
947
+ past_key_values=next_cache,
948
+ hidden_states=all_hidden_states,
949
+ attentions=all_self_attns,
950
+ )
951
+
952
+ def _update_causal_mask(self, attention_mask, input_tensor):
953
+ if self.config._attn_implementation == "flash_attention_2":
954
+ if attention_mask is not None and 0.0 in attention_mask:
955
+ return attention_mask
956
+ return None
957
+
958
+ batch_size, seq_length = input_tensor.shape[:2]
959
+ dtype = input_tensor.dtype
960
+ device = input_tensor.device
961
+
962
+ # support going beyond cached `max_position_embedding`
963
+ if seq_length > self.causal_mask.shape[-1]:
964
+ causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
965
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
966
+
967
+ # We use the current dtype to avoid any overflows
968
+ min_dtype = torch.finfo(dtype).min
969
+ causal_mask = self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype) * min_dtype
970
+
971
+ causal_mask = causal_mask.to(dtype=dtype, device=device)
972
+ if attention_mask is not None and attention_mask.dim() == 2:
973
+ mask_length = attention_mask.shape[-1]
974
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
975
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
976
+
977
+ if self.config._attn_implementation == "sdpa" and attention_mask is not None:
978
+ # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
979
+ is_tracing = (
980
+ torch.jit.is_tracing()
981
+ or isinstance(input_tensor, torch.fx.Proxy)
982
+ or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
983
+ )
984
+ if not is_tracing and torch.any(attention_mask != 1):
985
+ # Attend to all tokens in masked rows from the causal_mask, for example the relevant first rows when
986
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
987
+ # Details: https://github.com/pytorch/pytorch/issues/110213
988
+ causal_mask = causal_mask.mul(~torch.all(causal_mask == min_dtype, dim=-1, keepdim=True)).to(dtype)
989
+
990
+ return causal_mask
991
+
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with LLAMA->GEMMA,Llama->Gemma,llama->gemma
994
+ class GemmaForCausalLM(GemmaPreTrainedModel):
995
+ _tied_weights_keys = ["lm_head.weight"]
996
+
997
+ def __init__(self, config):
998
+ super().__init__(config)
999
+ self.model = GemmaModel(config)
1000
+ self.vocab_size = config.vocab_size
1001
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1002
+
1003
+ # Initialize weights and apply final processing
1004
+ self.post_init()
1005
+
1006
+ def get_input_embeddings(self):
1007
+ return self.model.embed_tokens
1008
+
1009
+ def set_input_embeddings(self, value):
1010
+ self.model.embed_tokens = value
1011
+
1012
+ def get_output_embeddings(self):
1013
+ return self.lm_head
1014
+
1015
+ def set_output_embeddings(self, new_embeddings):
1016
+ self.lm_head = new_embeddings
1017
+
1018
+ def set_decoder(self, decoder):
1019
+ self.model = decoder
1020
+
1021
+ def get_decoder(self):
1022
+ return self.model
1023
+
1024
+ # Ignore copy
1025
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
1026
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1027
+ def forward(
1028
+ self,
1029
+ input_ids: torch.LongTensor = None,
1030
+ attention_mask: Optional[torch.Tensor] = None,
1031
+ position_ids: Optional[torch.LongTensor] = None,
1032
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1033
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1034
+ labels: Optional[torch.LongTensor] = None,
1035
+ use_cache: Optional[bool] = None,
1036
+ output_attentions: Optional[bool] = None,
1037
+ output_hidden_states: Optional[bool] = None,
1038
+ return_dict: Optional[bool] = None,
1039
+ cache_position: Optional[torch.LongTensor] = None,
1040
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1041
+ r"""
1042
+ Args:
1043
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1044
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1045
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1046
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1047
+
1048
+ Returns:
1049
+
1050
+ Example:
1051
+
1052
+ ```python
1053
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
1054
+
1055
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
1056
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
1057
+
1058
+ >>> prompt = "What is your favorite condiment?"
1059
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1060
+
1061
+ >>> # Generate
1062
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1063
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1064
+ "What is your favorite condiment?"
1065
+ ```"""
1066
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1067
+ output_hidden_states = (
1068
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1069
+ )
1070
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1071
+
1072
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1073
+ outputs = self.model(
1074
+ input_ids=input_ids,
1075
+ attention_mask=attention_mask,
1076
+ position_ids=position_ids,
1077
+ past_key_values=past_key_values,
1078
+ inputs_embeds=inputs_embeds,
1079
+ use_cache=use_cache,
1080
+ output_attentions=output_attentions,
1081
+ output_hidden_states=output_hidden_states,
1082
+ return_dict=return_dict,
1083
+ cache_position=cache_position,
1084
+ )
1085
+
1086
+ hidden_states = outputs[0]
1087
+ logits = self.lm_head(hidden_states)
1088
+ logits = logits.float()
1089
+ loss = None
1090
+ if labels is not None:
1091
+ # Shift so that tokens < n predict n
1092
+ shift_logits = logits[..., :-1, :].contiguous()
1093
+ shift_labels = labels[..., 1:].contiguous()
1094
+ # Flatten the tokens
1095
+ loss_fct = CrossEntropyLoss()
1096
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1097
+ shift_labels = shift_labels.view(-1)
1098
+ # Enable model parallelism
1099
+ shift_labels = shift_labels.to(shift_logits.device)
1100
+ loss = loss_fct(shift_logits, shift_labels)
1101
+
1102
+ if not return_dict:
1103
+ output = (logits,) + outputs[1:]
1104
+ return (loss,) + output if loss is not None else output
1105
+
1106
+ return CausalLMOutputWithPast(
1107
+ loss=loss,
1108
+ logits=logits,
1109
+ past_key_values=outputs.past_key_values,
1110
+ hidden_states=outputs.hidden_states,
1111
+ attentions=outputs.attentions,
1112
+ )
1113
+
1114
+ def prepare_inputs_for_generation(
1115
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1116
+ ):
1117
+ past_length = 0
1118
+ if past_key_values is not None:
1119
+ if isinstance(past_key_values, Cache):
1120
+ cache_length = past_key_values.get_seq_length()
1121
+ past_length = past_key_values.seen_tokens
1122
+ max_cache_length = past_key_values.get_max_length()
1123
+ else:
1124
+ cache_length = past_length = past_key_values[0][0].shape[2]
1125
+ max_cache_length = None
1126
+
1127
+ # Keep only the unprocessed tokens:
1128
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1129
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1130
+ # input)
1131
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1132
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1133
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1134
+ # input_ids based on the past_length.
1135
+ elif past_length < input_ids.shape[1]:
1136
+ input_ids = input_ids[:, past_length:]
1137
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1138
+
1139
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1140
+ if (
1141
+ max_cache_length is not None
1142
+ and attention_mask is not None
1143
+ and cache_length + input_ids.shape[1] > max_cache_length
1144
+ ):
1145
+ attention_mask = attention_mask[:, -max_cache_length:]
1146
+
1147
+ position_ids = kwargs.get("position_ids", None)
1148
+ if attention_mask is not None and position_ids is None:
1149
+ # create position_ids on the fly for batch generation
1150
+ position_ids = attention_mask.long().cumsum(-1) - 1
1151
+ position_ids.masked_fill_(attention_mask == 0, 1)
1152
+ if past_key_values:
1153
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1154
+
1155
+ if self.generation_config.cache_implementation == "static":
1156
+ # generation with static cache
1157
+ cache_position = kwargs.get("cache_position", None)
1158
+ if cache_position is None:
1159
+ past_length = 0
1160
+ else:
1161
+ past_length = cache_position[-1] + 1
1162
+ input_ids = input_ids[:, past_length:]
1163
+ position_ids = position_ids[:, past_length:]
1164
+
1165
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
1166
+ # same goes for position ids. Could also help with continued generation.
1167
+ cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
1168
+
1169
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1170
+ if inputs_embeds is not None and past_key_values is None:
1171
+ model_inputs = {"inputs_embeds": inputs_embeds}
1172
+ else:
1173
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1174
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1175
+ # TODO: use `next_tokens` directly instead.
1176
+ model_inputs = {"input_ids": input_ids.contiguous()}
1177
+
1178
+ model_inputs.update(
1179
+ {
1180
+ "position_ids": position_ids.contiguous(),
1181
+ "cache_position": cache_position,
1182
+ "past_key_values": past_key_values,
1183
+ "use_cache": kwargs.get("use_cache"),
1184
+ "attention_mask": attention_mask,
1185
+ }
1186
+ )
1187
+ return model_inputs
1188
+
1189
+ @staticmethod
1190
+ def _reorder_cache(past_key_values, beam_idx):
1191
+ reordered_past = ()
1192
+ for layer_past in past_key_values:
1193
+ reordered_past += (
1194
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1195
+ )
1196
+ return reordered_past
1197
+
1198
+
1199
+ @add_start_docstrings(
1200
+ """
1201
+ The Gemma Model transformer with a sequence classification head on top (linear layer).
1202
+
1203
+ [`GemmaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1204
+ (e.g. GPT-2) do.
1205
+
1206
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1207
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1208
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1209
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1210
+ each row of the batch).
1211
+ """,
1212
+ GEMMA_START_DOCSTRING,
1213
+ )
1214
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->GEMMA,Llama->Gemma
1215
+ class GemmaForSequenceClassification(GemmaPreTrainedModel):
1216
+ def __init__(self, config):
1217
+ super().__init__(config)
1218
+ self.num_labels = config.num_labels
1219
+ self.model = GemmaModel(config)
1220
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1221
+
1222
+ # Initialize weights and apply final processing
1223
+ self.post_init()
1224
+
1225
+ def get_input_embeddings(self):
1226
+ return self.model.embed_tokens
1227
+
1228
+ def set_input_embeddings(self, value):
1229
+ self.model.embed_tokens = value
1230
+
1231
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
1232
+ def forward(
1233
+ self,
1234
+ input_ids: torch.LongTensor = None,
1235
+ attention_mask: Optional[torch.Tensor] = None,
1236
+ position_ids: Optional[torch.LongTensor] = None,
1237
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1238
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1239
+ labels: Optional[torch.LongTensor] = None,
1240
+ use_cache: Optional[bool] = None,
1241
+ output_attentions: Optional[bool] = None,
1242
+ output_hidden_states: Optional[bool] = None,
1243
+ return_dict: Optional[bool] = None,
1244
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1245
+ r"""
1246
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1247
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1248
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1249
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1250
+ """
1251
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1252
+
1253
+ transformer_outputs = self.model(
1254
+ input_ids,
1255
+ attention_mask=attention_mask,
1256
+ position_ids=position_ids,
1257
+ past_key_values=past_key_values,
1258
+ inputs_embeds=inputs_embeds,
1259
+ use_cache=use_cache,
1260
+ output_attentions=output_attentions,
1261
+ output_hidden_states=output_hidden_states,
1262
+ return_dict=return_dict,
1263
+ )
1264
+ hidden_states = transformer_outputs[0]
1265
+ logits = self.score(hidden_states)
1266
+
1267
+ if input_ids is not None:
1268
+ batch_size = input_ids.shape[0]
1269
+ else:
1270
+ batch_size = inputs_embeds.shape[0]
1271
+
1272
+ if self.config.pad_token_id is None and batch_size != 1:
1273
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1274
+ if self.config.pad_token_id is None:
1275
+ sequence_lengths = -1
1276
+ else:
1277
+ if input_ids is not None:
1278
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1279
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1280
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1281
+ sequence_lengths = sequence_lengths.to(logits.device)
1282
+ else:
1283
+ sequence_lengths = -1
1284
+
1285
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1286
+
1287
+ loss = None
1288
+ if labels is not None:
1289
+ labels = labels.to(logits.device)
1290
+ if self.config.problem_type is None:
1291
+ if self.num_labels == 1:
1292
+ self.config.problem_type = "regression"
1293
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1294
+ self.config.problem_type = "single_label_classification"
1295
+ else:
1296
+ self.config.problem_type = "multi_label_classification"
1297
+
1298
+ if self.config.problem_type == "regression":
1299
+ loss_fct = MSELoss()
1300
+ if self.num_labels == 1:
1301
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1302
+ else:
1303
+ loss = loss_fct(pooled_logits, labels)
1304
+ elif self.config.problem_type == "single_label_classification":
1305
+ loss_fct = CrossEntropyLoss()
1306
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1307
+ elif self.config.problem_type == "multi_label_classification":
1308
+ loss_fct = BCEWithLogitsLoss()
1309
+ loss = loss_fct(pooled_logits, labels)
1310
+ if not return_dict:
1311
+ output = (pooled_logits,) + transformer_outputs[1:]
1312
+ return ((loss,) + output) if loss is not None else output
1313
+
1314
+ return SequenceClassifierOutputWithPast(
1315
+ loss=loss,
1316
+ logits=pooled_logits,
1317
+ past_key_values=transformer_outputs.past_key_values,
1318
+ hidden_states=transformer_outputs.hidden_states,
1319
+ attentions=transformer_outputs.attentions,
1320
+ )