Crystalcareai commited on
Commit
b03ac5f
·
verified ·
1 Parent(s): 90f9d1a

Upload modeling_gemma.py

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