Yingxu He commited on
Commit
de883d6
·
verified ·
1 Parent(s): 1ceef1c

Upload modeling_text_decoder.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_text_decoder.py +1104 -0
modeling_text_decoder.py ADDED
@@ -0,0 +1,1104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+
23
+ from transformers.activations import ACT2FN
24
+ from transformers.cache_utils import Cache, HybridCache
25
+ from transformers.modeling_outputs import (
26
+ BaseModelOutputWithPast,
27
+ CausalLMOutputWithPast,
28
+ )
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.utils import (
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ is_flash_attn_2_available,
34
+ is_flash_attn_greater_or_equal,
35
+ is_flash_attn_greater_or_equal_2_10,
36
+ logging,
37
+ replace_return_docstrings,
38
+ )
39
+ from .configuration_meralion import MERaLiONTextConfig
40
+
41
+
42
+ if is_flash_attn_2_available():
43
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
50
+ def _prepare_4d_causal_attention_mask_with_cache_position(
51
+ attention_mask: torch.Tensor,
52
+ sequence_length: int,
53
+ target_length: int,
54
+ dtype: torch.dtype,
55
+ device: torch.device,
56
+ min_dtype: float,
57
+ cache_position: torch.Tensor,
58
+ batch_size: int,
59
+ ):
60
+ """
61
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
62
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
63
+
64
+ Args:
65
+ attention_mask (`torch.Tensor`):
66
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
67
+ sequence_length (`int`):
68
+ The sequence length being processed.
69
+ target_length (`int`):
70
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
71
+ dtype (`torch.dtype`):
72
+ The dtype to use for the 4D attention mask.
73
+ device (`torch.device`):
74
+ The device to plcae the 4D attention mask on.
75
+ min_dtype (`float`):
76
+ The minimum value representable with the dtype `dtype`.
77
+ cache_position (`torch.Tensor`):
78
+ Indices depicting the position of the input sequence tokens in the sequence.
79
+ batch_size (`torch.Tensor`):
80
+ Batch size.
81
+ """
82
+ if attention_mask is not None and attention_mask.dim() == 4:
83
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
84
+ causal_mask = attention_mask
85
+ else:
86
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
87
+ if sequence_length != 1:
88
+ causal_mask = torch.triu(causal_mask, diagonal=1)
89
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
90
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
91
+ if attention_mask is not None:
92
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
93
+ mask_length = attention_mask.shape[-1]
94
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
95
+ padding_mask = padding_mask == 0
96
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
97
+ padding_mask, min_dtype
98
+ )
99
+ return causal_mask
100
+
101
+
102
+ class MERaLiONTextRMSNorm(nn.Module):
103
+ def __init__(self, dim: int, eps: float = 1e-6):
104
+ super().__init__()
105
+ self.eps = eps
106
+ self.weight = nn.Parameter(torch.zeros(dim))
107
+
108
+ def _norm(self, x):
109
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
110
+
111
+ def forward(self, x):
112
+ output = self._norm(x.float())
113
+ # Llama does x.to(float16) * w whilst MERaLiONText is (x * w).to(float16)
114
+ # See https://github.com/huggingface/transformers/pull/29402
115
+ output = output * (1.0 + self.weight.float())
116
+ return output.type_as(x)
117
+
118
+ def extra_repr(self):
119
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
120
+
121
+
122
+ class MERaLiONTextRotaryEmbedding(nn.Module):
123
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
124
+ super().__init__()
125
+
126
+ self.dim = dim
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.base = base
129
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
130
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
131
+
132
+ @torch.no_grad()
133
+ def forward(self, x, position_ids, seq_len=None):
134
+ # x: [bs, num_attention_heads, seq_len, head_size]
135
+ self.inv_freq.to(x.device)
136
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
137
+ position_ids_expanded = position_ids[:, None, :].float()
138
+ # Force float32 since bfloat16 loses precision on long contexts
139
+ # See https://github.com/huggingface/transformers/pull/29285
140
+ device_type = x.device.type
141
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
142
+ with torch.autocast(device_type=device_type, enabled=False):
143
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ cos = emb.cos()
146
+ sin = emb.sin()
147
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
148
+
149
+
150
+ def rotate_half(x):
151
+ """Rotates half the hidden dims of the input."""
152
+ x1 = x[..., : x.shape[-1] // 2]
153
+ x2 = x[..., x.shape[-1] // 2 :]
154
+ return torch.cat((-x2, x1), dim=-1)
155
+
156
+
157
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
158
+ """Applies Rotary Position Embedding to the query and key tensors.
159
+
160
+ Args:
161
+ q (`torch.Tensor`): The query tensor.
162
+ k (`torch.Tensor`): The key tensor.
163
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
164
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
165
+ position_ids (`torch.Tensor`, *optional*):
166
+ Deprecated and unused.
167
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
168
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
169
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
170
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
171
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
172
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
173
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
174
+ Returns:
175
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
176
+ """
177
+ cos = cos.unsqueeze(unsqueeze_dim)
178
+ sin = sin.unsqueeze(unsqueeze_dim)
179
+ q_embed = (q * cos) + (rotate_half(q) * sin)
180
+ k_embed = (k * cos) + (rotate_half(k) * sin)
181
+ return q_embed, k_embed
182
+
183
+
184
+ class MERaLiONTextMLP(nn.Module):
185
+ def __init__(self, config):
186
+ super().__init__()
187
+ self.config = config
188
+ self.hidden_size = config.hidden_size
189
+ self.intermediate_size = config.intermediate_size
190
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
191
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
192
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
193
+ self.act_fn = ACT2FN[config.hidden_activation]
194
+
195
+ def forward(self, x):
196
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
197
+
198
+
199
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
200
+ """
201
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
202
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
203
+ """
204
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
205
+ if n_rep == 1:
206
+ return hidden_states
207
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
208
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
209
+
210
+
211
+ class MERaLiONTextAttention(nn.Module):
212
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
213
+
214
+ def __init__(self, config: MERaLiONTextConfig, layer_idx: Optional[int] = None):
215
+ super().__init__()
216
+ self.config = config
217
+ self.layer_idx = layer_idx
218
+ if layer_idx is None:
219
+ logger.warning_once(
220
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
221
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
222
+ "when creating this class."
223
+ )
224
+
225
+ self.attention_dropout = config.attention_dropout
226
+ self.hidden_size = config.hidden_size
227
+ self.num_heads = config.num_attention_heads
228
+ self.head_dim = config.head_dim
229
+ self.num_key_value_heads = config.num_key_value_heads
230
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
231
+ self.max_position_embeddings = config.max_position_embeddings
232
+ self.rope_theta = config.rope_theta
233
+ self.is_causal = True
234
+ self.scaling = config.query_pre_attn_scalar**-0.5
235
+
236
+ if self.hidden_size % self.num_heads != 0:
237
+ raise ValueError(
238
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
239
+ f" and `num_heads`: {self.num_heads})."
240
+ )
241
+
242
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
243
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
244
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
245
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
246
+ self.rotary_emb = MERaLiONTextRotaryEmbedding(
247
+ self.head_dim,
248
+ max_position_embeddings=self.max_position_embeddings,
249
+ base=self.rope_theta,
250
+ )
251
+ self.sliding_window = config.sliding_window if not bool(layer_idx % 2) else None
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ attention_mask: Optional[torch.Tensor] = None,
257
+ position_ids: Optional[torch.LongTensor] = None,
258
+ past_key_value: Optional[Cache] = None,
259
+ output_attentions: bool = False,
260
+ use_cache: bool = False,
261
+ cache_position: Optional[torch.LongTensor] = None,
262
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
263
+ bsz, q_len, _ = hidden_states.size()
264
+
265
+ query_states = self.q_proj(hidden_states)
266
+ key_states = self.k_proj(hidden_states)
267
+ value_states = self.v_proj(hidden_states)
268
+
269
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
270
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
271
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
272
+
273
+ cos, sin = self.rotary_emb(value_states, position_ids)
274
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
275
+
276
+ if past_key_value is not None:
277
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
278
+ cache_kwargs = {
279
+ "sin": sin,
280
+ "cos": cos,
281
+ "sliding_window": self.sliding_window,
282
+ "cache_position": cache_position,
283
+ }
284
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
285
+
286
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
287
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
288
+
289
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
290
+
291
+ if self.config.attn_logit_softcapping is not None:
292
+ attn_weights = attn_weights / self.config.attn_logit_softcapping
293
+ attn_weights = torch.tanh(attn_weights)
294
+ attn_weights = attn_weights * self.config.attn_logit_softcapping
295
+ if attention_mask is not None: # no matter the length, we just slice it
296
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
297
+ attn_weights = attn_weights + causal_mask
298
+
299
+ # upcast attention to fp32
300
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
301
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
302
+ attn_output = torch.matmul(attn_weights, value_states)
303
+
304
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
305
+ raise ValueError(
306
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
307
+ f" {attn_output.size()}"
308
+ )
309
+
310
+ attn_output = attn_output.transpose(1, 2).contiguous()
311
+
312
+ attn_output = attn_output.view(bsz, q_len, -1)
313
+ attn_output = self.o_proj(attn_output)
314
+
315
+ if not output_attentions:
316
+ attn_weights = None
317
+
318
+ return attn_output, attn_weights, past_key_value
319
+
320
+
321
+ class MERaLiONTextFlashAttention2(MERaLiONTextAttention):
322
+ """
323
+ MERaLiONText flash attention module. This module inherits from `MERaLiONTextAttention` as the weights of the module stays
324
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
325
+ flash attention and deal with padding tokens in case the input contains any of them.
326
+ """
327
+
328
+ def __init__(self, *args, **kwargs):
329
+ super().__init__(*args, **kwargs)
330
+
331
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
332
+ # 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.
333
+ # 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).
334
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
335
+
336
+ def forward(
337
+ self,
338
+ hidden_states: torch.Tensor,
339
+ attention_mask: Optional[torch.LongTensor] = None,
340
+ position_ids: Optional[torch.LongTensor] = None,
341
+ past_key_value: Optional[Cache] = None,
342
+ output_attentions: bool = False,
343
+ use_cache: bool = False,
344
+ cache_position: Optional[torch.LongTensor] = None,
345
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
346
+ output_attentions = False
347
+
348
+ bsz, q_len, _ = hidden_states.size()
349
+
350
+ query_states = self.q_proj(hidden_states)
351
+ key_states = self.k_proj(hidden_states)
352
+ value_states = self.v_proj(hidden_states)
353
+
354
+ # Flash attention requires the input to have the shape
355
+ # batch_size x seq_length x head_dim x hidden_dim
356
+ # therefore we just need to keep the original shape
357
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
358
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
359
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
360
+
361
+ cos, sin = self.rotary_emb(value_states, position_ids)
362
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
363
+
364
+ if past_key_value is not None:
365
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
366
+ cache_kwargs = {
367
+ "sin": sin,
368
+ "cos": cos,
369
+ "sliding_window": self.sliding_window,
370
+ "cache_position": cache_position,
371
+ }
372
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
373
+
374
+ if attention_mask is not None:
375
+ seq_len = attention_mask.shape[1]
376
+ key_states = key_states[:, :, :seq_len]
377
+ value_states = value_states[:, :, :seq_len]
378
+
379
+ # 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
380
+ # to be able to avoid many of these transpose/reshape/view.
381
+ query_states = query_states.transpose(1, 2)
382
+ key_states = key_states.transpose(1, 2)
383
+ value_states = value_states.transpose(1, 2)
384
+
385
+ dropout_rate = self.attention_dropout if self.training else 0.0
386
+
387
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
388
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
389
+ # cast them back in the correct dtype just to be sure everything works as expected.
390
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
391
+ # in fp32. (MERaLiONTextRMSNorm handles it correctly)
392
+
393
+ input_dtype = query_states.dtype
394
+ if input_dtype == torch.float32:
395
+ if torch.is_autocast_enabled():
396
+ target_dtype = torch.get_autocast_gpu_dtype()
397
+ # Handle the case where the model is quantized
398
+ elif hasattr(self.config, "_pre_quantization_dtype"):
399
+ target_dtype = self.config._pre_quantization_dtype
400
+ else:
401
+ target_dtype = self.q_proj.weight.dtype
402
+
403
+ logger.warning_once(
404
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
405
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
406
+ f" {target_dtype}."
407
+ )
408
+
409
+ query_states = query_states.to(target_dtype)
410
+ key_states = key_states.to(target_dtype)
411
+ value_states = value_states.to(target_dtype)
412
+
413
+ attn_output = _flash_attention_forward(
414
+ query_states,
415
+ key_states,
416
+ value_states,
417
+ attention_mask,
418
+ q_len,
419
+ dropout=dropout_rate,
420
+ softmax_scale=self.scaling,
421
+ is_causal=self.is_causal,
422
+ sliding_window=self.sliding_window,
423
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
424
+ softcap=self.config.attn_logit_softcapping if is_flash_attn_greater_or_equal("2.6.0") else None,
425
+ )
426
+
427
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
428
+ attn_output = self.o_proj(attn_output)
429
+
430
+ if not output_attentions:
431
+ attn_weights = None
432
+
433
+ return attn_output, attn_weights, past_key_value
434
+
435
+
436
+ class MERaLiONTextSdpaAttention(MERaLiONTextAttention):
437
+ """
438
+ MERaLiONText attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
439
+ `MERaLiONTextAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
440
+ SDPA API.
441
+ """
442
+
443
+ # Adapted from MERaLiONTextAttention.forward
444
+ def forward(
445
+ self,
446
+ hidden_states: torch.Tensor,
447
+ attention_mask: Optional[torch.Tensor] = None,
448
+ position_ids: Optional[torch.LongTensor] = None,
449
+ past_key_value: Optional[Cache] = None,
450
+ output_attentions: bool = False,
451
+ use_cache: bool = False,
452
+ cache_position: Optional[torch.LongTensor] = None,
453
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
454
+ if output_attentions:
455
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
456
+ logger.warning_once(
457
+ "MERaLiONTextModel is using MERaLiONTextSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
458
+ '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.'
459
+ )
460
+ return super().forward(
461
+ hidden_states=hidden_states,
462
+ attention_mask=attention_mask,
463
+ position_ids=position_ids,
464
+ past_key_value=past_key_value,
465
+ output_attentions=output_attentions,
466
+ use_cache=use_cache,
467
+ cache_position=cache_position,
468
+ )
469
+
470
+ bsz, q_len, _ = hidden_states.size()
471
+
472
+ query_states = self.q_proj(hidden_states)
473
+ key_states = self.k_proj(hidden_states)
474
+ value_states = self.v_proj(hidden_states)
475
+
476
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
477
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
478
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
479
+
480
+ cos, sin = self.rotary_emb(value_states, position_ids)
481
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
482
+
483
+ if past_key_value is not None:
484
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
485
+ cache_kwargs = {
486
+ "sin": sin,
487
+ "cos": cos,
488
+ "sliding_window": self.sliding_window,
489
+ "cache_position": cache_position,
490
+ }
491
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
492
+
493
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
494
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
495
+ causal_mask = attention_mask
496
+ if attention_mask is not None:
497
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
498
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
499
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
500
+ if query_states.device.type == "cuda" and causal_mask is not None:
501
+ query_states = query_states.contiguous()
502
+ key_states = key_states.contiguous()
503
+ value_states = value_states.contiguous()
504
+
505
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
506
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
507
+ is_causal = True if causal_mask is None and q_len > 1 else False
508
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
509
+ query_states,
510
+ key_states,
511
+ value_states,
512
+ attn_mask=causal_mask,
513
+ dropout_p=self.attention_dropout if self.training else 0.0,
514
+ is_causal=is_causal,
515
+ scale=self.scaling,
516
+ )
517
+
518
+ attn_output = attn_output.transpose(1, 2).contiguous()
519
+ attn_output = attn_output.view(bsz, q_len, -1)
520
+
521
+ attn_output = self.o_proj(attn_output)
522
+
523
+ return attn_output, None, past_key_value
524
+
525
+
526
+ MERaLiONText_ATTENTION_CLASSES = {
527
+ "eager": MERaLiONTextAttention,
528
+ "flash_attention_2": MERaLiONTextFlashAttention2,
529
+ "sdpa": MERaLiONTextSdpaAttention,
530
+ }
531
+
532
+
533
+ class MERaLiONTextDecoderLayer(nn.Module):
534
+ def __init__(self, config: MERaLiONTextConfig, layer_idx: int):
535
+ super().__init__()
536
+ self.config = config
537
+ self.hidden_size = config.hidden_size
538
+
539
+ self.self_attn = MERaLiONText_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
540
+
541
+ self.mlp = MERaLiONTextMLP(config)
542
+ self.input_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
543
+ self.post_attention_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
544
+
545
+ self.is_sliding = not bool(layer_idx % 2)
546
+ self.pre_feedforward_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
547
+ self.post_feedforward_layernorm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
548
+ self.sliding_window = config.sliding_window
549
+
550
+ def forward(
551
+ self,
552
+ hidden_states: torch.Tensor,
553
+ attention_mask: Optional[torch.Tensor] = None,
554
+ position_ids: Optional[torch.LongTensor] = None,
555
+ past_key_value: Optional[Cache] = None,
556
+ output_attentions: Optional[bool] = False,
557
+ use_cache: Optional[bool] = False,
558
+ cache_position: Optional[torch.LongTensor] = None,
559
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
560
+ if self.is_sliding and attention_mask is not None: # efficient SDPA and no padding
561
+ # Flash-attn is a 2D tensor
562
+ if self.config._attn_implementation == "flash_attention_2":
563
+ if past_key_value is not None: # when decoding
564
+ attention_mask = attention_mask[:, -self.sliding_window :]
565
+ else:
566
+ min_dtype = torch.finfo(hidden_states.dtype).min
567
+ sliding_window_mask = torch.tril(
568
+ torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-self.sliding_window
569
+ )
570
+ attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
571
+ if attention_mask.shape[-1] <= 1: # when decoding
572
+ attention_mask = attention_mask[:, :, :, -self.sliding_window :]
573
+ residual = hidden_states
574
+
575
+ hidden_states = self.input_layernorm(hidden_states)
576
+
577
+ # Self Attention
578
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
579
+ hidden_states=hidden_states,
580
+ attention_mask=attention_mask,
581
+ position_ids=position_ids,
582
+ past_key_value=past_key_value,
583
+ output_attentions=output_attentions,
584
+ use_cache=use_cache,
585
+ cache_position=cache_position,
586
+ )
587
+ hidden_states = self.post_attention_layernorm(hidden_states)
588
+ hidden_states = residual + hidden_states
589
+
590
+ residual = hidden_states
591
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
592
+ hidden_states = self.mlp(hidden_states)
593
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
594
+ hidden_states = residual + hidden_states
595
+
596
+ outputs = (hidden_states,)
597
+
598
+ if output_attentions:
599
+ outputs += (self_attn_weights,)
600
+
601
+ if use_cache:
602
+ outputs += (present_key_value,)
603
+
604
+ return outputs
605
+
606
+
607
+ MERALION_TEXT_START_DOCSTRING = r"""
608
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
609
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
610
+ etc.)
611
+
612
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
613
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
614
+ and behavior.
615
+
616
+ Parameters:
617
+ config ([`MERaLiONTextConfig`]):
618
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
619
+ load the weights associated with the model, only the configuration. Check out the
620
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
621
+ """
622
+
623
+
624
+ @add_start_docstrings(
625
+ "The bare MERaLiONText Model outputting raw hidden-states without any specific head on top.",
626
+ MERALION_TEXT_START_DOCSTRING,
627
+ )
628
+ class MERaLiONTextPreTrainedModel(PreTrainedModel):
629
+ config_class = MERaLiONTextConfig
630
+ base_model_prefix = "model"
631
+ supports_gradient_checkpointing = True
632
+ _no_split_modules = ["MERaLiONTextDecoderLayer"]
633
+ _skip_keys_device_placement = ["past_key_values"]
634
+ _supports_flash_attn_2 = True
635
+ _supports_sdpa = True
636
+ _supports_cache_class = True
637
+ _supports_quantized_cache = False
638
+ _supports_static_cache = True
639
+
640
+ def _init_weights(self, module):
641
+ std = self.config.initializer_range
642
+ if isinstance(module, nn.Linear):
643
+ module.weight.data.normal_(mean=0.0, std=std)
644
+ if module.bias is not None:
645
+ module.bias.data.zero_()
646
+ elif isinstance(module, nn.Embedding):
647
+ module.weight.data.normal_(mean=0.0, std=std)
648
+ if module.padding_idx is not None:
649
+ module.weight.data[module.padding_idx].zero_()
650
+
651
+
652
+ _CONFIG_FOR_DOC = "MERaLiONTextConfig"
653
+
654
+
655
+ MERALION_TEXT_INPUTS_DOCSTRING = r"""
656
+ Args:
657
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
658
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
659
+ it.
660
+
661
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
662
+ [`PreTrainedTokenizer.__call__`] for details.
663
+
664
+ [What are input IDs?](../glossary#input-ids)
665
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
666
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
667
+
668
+ - 1 for tokens that are **not masked**,
669
+ - 0 for tokens that are **masked**.
670
+
671
+ [What are attention masks?](../glossary#attention-mask)
672
+
673
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
674
+ [`PreTrainedTokenizer.__call__`] for details.
675
+
676
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
677
+ `past_key_values`).
678
+
679
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
680
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
681
+ information on the default strategy.
682
+
683
+ - 1 indicates the head is **not masked**,
684
+ - 0 indicates the head is **masked**.
685
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
686
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
687
+ config.n_positions - 1]`.
688
+
689
+ [What are position IDs?](../glossary#position-ids)
690
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
691
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
692
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
693
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
694
+
695
+ Two formats are allowed:
696
+ - a [`~cache_utils.Cache`] instance;
697
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
698
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
699
+ cache format.
700
+
701
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
702
+ legacy cache format will be returned.
703
+
704
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
705
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
706
+ of shape `(batch_size, sequence_length)`.
707
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
708
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
709
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
710
+ model's internal embedding lookup matrix.
711
+ use_cache (`bool`, *optional*):
712
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
713
+ `past_key_values`).
714
+ output_attentions (`bool`, *optional*):
715
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
716
+ tensors for more detail.
717
+ output_hidden_states (`bool`, *optional*):
718
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
719
+ more detail.
720
+ return_dict (`bool`, *optional*):
721
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
722
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
723
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
724
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
725
+ the complete sequence length.
726
+ """
727
+
728
+
729
+ @add_start_docstrings(
730
+ "The bare MERaLiONText Model outputting raw hidden-states without any specific head on top.",
731
+ MERALION_TEXT_START_DOCSTRING,
732
+ )
733
+ class MERaLiONTextModel(MERaLiONTextPreTrainedModel):
734
+ """
735
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MERaLiONTextDecoderLayer`]
736
+
737
+ Args:
738
+ config: MERaLiONTextConfig
739
+ """
740
+
741
+ def __init__(self, config: MERaLiONTextConfig):
742
+ super().__init__(config)
743
+ self.padding_idx = config.pad_token_id
744
+ self.vocab_size = config.vocab_size
745
+
746
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
747
+ self.layers = nn.ModuleList(
748
+ [MERaLiONTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
749
+ )
750
+ self.norm = MERaLiONTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
751
+ self.gradient_checkpointing = False
752
+
753
+ # Initialize weights and apply final processing
754
+ self.post_init()
755
+
756
+ def get_input_embeddings(self):
757
+ return self.embed_tokens
758
+
759
+ def set_input_embeddings(self, value):
760
+ self.embed_tokens = value
761
+
762
+ @add_start_docstrings_to_model_forward(MERALION_TEXT_INPUTS_DOCSTRING)
763
+ def forward(
764
+ self,
765
+ input_ids: torch.LongTensor = None,
766
+ attention_mask: Optional[torch.Tensor] = None,
767
+ position_ids: Optional[torch.LongTensor] = None,
768
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
769
+ inputs_embeds: Optional[torch.FloatTensor] = None,
770
+ use_cache: Optional[bool] = None,
771
+ output_attentions: Optional[bool] = None,
772
+ output_hidden_states: Optional[bool] = None,
773
+ return_dict: Optional[bool] = None,
774
+ cache_position: Optional[torch.LongTensor] = None,
775
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
776
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
777
+ output_hidden_states = (
778
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
779
+ )
780
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
781
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
782
+
783
+ if (input_ids is None) ^ (inputs_embeds is not None):
784
+ raise ValueError(
785
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
786
+ )
787
+
788
+ if self.gradient_checkpointing and self.training and use_cache:
789
+ logger.warning_once(
790
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
791
+ )
792
+ use_cache = False
793
+
794
+ if inputs_embeds is None:
795
+ inputs_embeds = self.embed_tokens(input_ids)
796
+
797
+ if cache_position is None:
798
+ cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
799
+
800
+ if position_ids is None:
801
+ position_ids = cache_position.unsqueeze(0)
802
+
803
+ causal_mask = self._update_causal_mask(
804
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
805
+ )
806
+
807
+ # embed positions
808
+ hidden_states = inputs_embeds
809
+
810
+ # normalized
811
+ # MERaLiONText downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
812
+ # See https://github.com/huggingface/transformers/pull/29402
813
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
814
+ hidden_states = hidden_states * normalizer
815
+
816
+ all_hidden_states = () if output_hidden_states else None
817
+ all_self_attns = () if output_attentions else None
818
+
819
+ for decoder_layer in self.layers:
820
+ if output_hidden_states:
821
+ all_hidden_states += (hidden_states,)
822
+
823
+ if self.gradient_checkpointing and self.training:
824
+ layer_outputs = self._gradient_checkpointing_func(
825
+ decoder_layer.__call__,
826
+ hidden_states,
827
+ causal_mask,
828
+ position_ids,
829
+ past_key_values,
830
+ output_attentions,
831
+ use_cache,
832
+ cache_position,
833
+ )
834
+ else:
835
+ layer_outputs = decoder_layer(
836
+ hidden_states,
837
+ attention_mask=causal_mask,
838
+ position_ids=position_ids,
839
+ past_key_value=past_key_values,
840
+ output_attentions=output_attentions,
841
+ use_cache=use_cache,
842
+ cache_position=cache_position,
843
+ )
844
+
845
+ hidden_states = layer_outputs[0]
846
+
847
+ if output_attentions:
848
+ all_self_attns += (layer_outputs[1],)
849
+
850
+ hidden_states = self.norm(hidden_states)
851
+
852
+ # add hidden states from the last decoder layer
853
+ if output_hidden_states:
854
+ all_hidden_states += (hidden_states,)
855
+
856
+ next_cache = past_key_values if use_cache else None
857
+
858
+ if not return_dict:
859
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
860
+ return BaseModelOutputWithPast(
861
+ last_hidden_state=hidden_states,
862
+ past_key_values=next_cache,
863
+ hidden_states=all_hidden_states,
864
+ attentions=all_self_attns,
865
+ )
866
+
867
+ def _update_causal_mask(
868
+ self,
869
+ attention_mask: torch.Tensor,
870
+ input_tensor: torch.Tensor,
871
+ cache_position: torch.Tensor,
872
+ past_key_values: Cache,
873
+ output_attentions: bool,
874
+ ):
875
+ # Flash Attention currently doesn't support static cache but MERaLiONText work only with static cache.
876
+ # So we will pass in attention mask as is in any case, not only when ther's padding. Then we'll use its shape
877
+ # to cut out keys/values trailing 0 used in static cache. This workaround should be compile compatible
878
+ # as it doesn't cause dynamic control issues.
879
+ if self.config._attn_implementation == "flash_attention_2":
880
+ return attention_mask
881
+
882
+ dtype, device = input_tensor.dtype, input_tensor.device
883
+ min_dtype = torch.finfo(dtype).min
884
+ sequence_length = input_tensor.shape[1]
885
+ if isinstance(past_key_values, HybridCache):
886
+ target_length = past_key_values.get_max_length()
887
+ else:
888
+ target_length = attention_mask.shape[-1] if attention_mask is not None else input_tensor.shape[1]
889
+
890
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
891
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
892
+ attention_mask,
893
+ sequence_length=sequence_length,
894
+ target_length=target_length,
895
+ dtype=dtype,
896
+ device=device,
897
+ min_dtype=min_dtype,
898
+ cache_position=cache_position,
899
+ batch_size=input_tensor.shape[0],
900
+ )
901
+ return causal_mask
902
+
903
+
904
+ class MERaLiONTextForCausalLM(MERaLiONTextPreTrainedModel):
905
+ _tied_weights_keys = ["lm_head.weight"]
906
+
907
+ def __init__(self, config):
908
+ super().__init__(config)
909
+ self.model = MERaLiONTextModel(config)
910
+ self.vocab_size = config.vocab_size
911
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
912
+
913
+ # Initialize weights and apply final processing
914
+ self.post_init()
915
+
916
+ def get_input_embeddings(self):
917
+ return self.model.embed_tokens
918
+
919
+ def set_input_embeddings(self, value):
920
+ self.model.embed_tokens = value
921
+
922
+ def get_output_embeddings(self):
923
+ return self.lm_head
924
+
925
+ def set_output_embeddings(self, new_embeddings):
926
+ self.lm_head = new_embeddings
927
+
928
+ def set_decoder(self, decoder):
929
+ self.model = decoder
930
+
931
+ def get_decoder(self):
932
+ return self.model
933
+
934
+ @add_start_docstrings_to_model_forward(MERALION_TEXT_INPUTS_DOCSTRING)
935
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
936
+ def forward(
937
+ self,
938
+ input_ids: torch.LongTensor = None,
939
+ attention_mask: Optional[torch.Tensor] = None,
940
+ position_ids: Optional[torch.LongTensor] = None,
941
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
942
+ inputs_embeds: Optional[torch.FloatTensor] = None,
943
+ labels: Optional[torch.LongTensor] = None,
944
+ use_cache: Optional[bool] = None,
945
+ output_attentions: Optional[bool] = None,
946
+ output_hidden_states: Optional[bool] = None,
947
+ return_dict: Optional[bool] = None,
948
+ cache_position: Optional[torch.LongTensor] = None,
949
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
950
+ r"""
951
+ Args:
952
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
953
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
954
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
955
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
956
+
957
+ Returns:
958
+
959
+ Example:
960
+
961
+ ```python
962
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
963
+
964
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-2-9b")
965
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
966
+
967
+ >>> prompt = "What is your favorite condiment?"
968
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
969
+
970
+ >>> # Generate
971
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
972
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
973
+ "What is your favorite condiment?"
974
+ ```"""
975
+ if self.training and self.config._attn_implementation != "eager":
976
+ logger.warning_once(
977
+ "It is strongly recommended to train MERaLiONText models with the `eager` attention implementation "
978
+ f"instead of `{self.config._attn_implementation}`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`."
979
+ )
980
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
981
+ output_hidden_states = (
982
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
983
+ )
984
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
985
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
986
+
987
+ outputs = self.model(
988
+ input_ids=input_ids,
989
+ attention_mask=attention_mask,
990
+ position_ids=position_ids,
991
+ past_key_values=past_key_values,
992
+ inputs_embeds=inputs_embeds,
993
+ use_cache=use_cache,
994
+ output_attentions=output_attentions,
995
+ output_hidden_states=output_hidden_states,
996
+ return_dict=return_dict,
997
+ cache_position=cache_position,
998
+ )
999
+
1000
+ hidden_states = outputs[0]
1001
+ logits = self.lm_head(hidden_states)
1002
+ if self.config.final_logit_softcapping is not None:
1003
+ logits = logits / self.config.final_logit_softcapping
1004
+ logits = torch.tanh(logits)
1005
+ logits = logits * self.config.final_logit_softcapping
1006
+
1007
+ logits = logits.float()
1008
+ loss = None
1009
+ if labels is not None:
1010
+ # Shift so that tokens < n predict n
1011
+ shift_logits = logits[..., :-1, :].contiguous()
1012
+ shift_labels = labels[..., 1:].contiguous()
1013
+ # Flatten the tokens
1014
+ loss_fct = CrossEntropyLoss()
1015
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1016
+ shift_labels = shift_labels.view(-1)
1017
+ # Enable model parallelism
1018
+ shift_labels = shift_labels.to(shift_logits.device)
1019
+ loss = loss_fct(shift_logits, shift_labels)
1020
+
1021
+ if not return_dict:
1022
+ output = (logits,) + outputs[1:]
1023
+ return (loss,) + output if loss is not None else output
1024
+
1025
+ return CausalLMOutputWithPast(
1026
+ loss=loss,
1027
+ logits=logits,
1028
+ past_key_values=outputs.past_key_values,
1029
+ hidden_states=outputs.hidden_states,
1030
+ attentions=outputs.attentions,
1031
+ )
1032
+
1033
+ def prepare_inputs_for_generation(
1034
+ self,
1035
+ input_ids,
1036
+ past_key_values=None,
1037
+ attention_mask=None,
1038
+ inputs_embeds=None,
1039
+ cache_position=None,
1040
+ position_ids=None,
1041
+ use_cache=True,
1042
+ **kwargs,
1043
+ ):
1044
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1045
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1046
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1047
+ if past_key_values is not None:
1048
+ if inputs_embeds is not None: # Exception 1
1049
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1050
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1051
+ input_ids = input_ids[:, cache_position]
1052
+ if attention_mask is not None and position_ids is None:
1053
+ # create position_ids on the fly for batch generation
1054
+ position_ids = attention_mask.long().cumsum(-1) - 1
1055
+ position_ids.masked_fill_(attention_mask == 0, 1)
1056
+ if past_key_values:
1057
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1058
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s
1059
+ # `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride
1060
+ # during the decoding. Here, simply using `.contiguous()` is not sufficient as in the
1061
+ # batch size = 1 case, `position_ids` is already contiguous but with varying stride
1062
+ # which retriggers a capture.
1063
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1064
+
1065
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1066
+ if inputs_embeds is not None and cache_position[0] == 0:
1067
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1068
+ else:
1069
+ # The clone here is for the same reason as for `position_ids`.
1070
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1071
+
1072
+ if (
1073
+ isinstance(past_key_values, HybridCache)
1074
+ and attention_mask.ndim == 2
1075
+ and not self.config._attn_implementation == "flash_attention_2"
1076
+ ):
1077
+ if model_inputs["inputs_embeds"] is not None:
1078
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1079
+ device = model_inputs["inputs_embeds"].device
1080
+ else:
1081
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1082
+ device = model_inputs["input_ids"].device
1083
+ dtype = self.lm_head.weight.dtype
1084
+ min_dtype = torch.finfo(dtype).min
1085
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1086
+ attention_mask,
1087
+ sequence_length=sequence_length,
1088
+ target_length=past_key_values.get_max_length(),
1089
+ dtype=dtype,
1090
+ device=device,
1091
+ min_dtype=min_dtype,
1092
+ cache_position=cache_position,
1093
+ batch_size=batch_size,
1094
+ )
1095
+ model_inputs.update(
1096
+ {
1097
+ "position_ids": position_ids,
1098
+ "cache_position": cache_position,
1099
+ "past_key_values": past_key_values,
1100
+ "use_cache": use_cache,
1101
+ "attention_mask": attention_mask,
1102
+ }
1103
+ )
1104
+ return model_inputs