YingxuHe commited on
Commit
90bc16b
·
verified ·
1 Parent(s): ff2e0d7

Delete modeling_text_decoder.py

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