Delta-Vector commited on
Commit
2d6ed75
·
verified ·
1 Parent(s): 65e42b4

Upload modeling_decilm.py

Browse files
Files changed (1) hide show
  1. modeling_decilm.py +1700 -0
modeling_decilm.py ADDED
@@ -0,0 +1,1700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Nvidia Corporation, Google Inc, HuggingFace Inc, EleutherAI. All rights reserved.
3
+ #
4
+ # This code for Nvidia's model is based on the Llama modeling code by HuggingFace,
5
+ # which is in turn based on EleutherAI's GPT-NeoX library and the GPT-NeoX and
6
+ # OPT implementations in this library.
7
+ # Sliding window code based on Gemma2 by Google.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers import GenerationConfig
30
+ from transformers.generation.utils import NEED_SETUP_CACHE_CLASSES_MAPPING, GenerationMixin, GenerateOutput
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
33
+ from transformers.utils import (
34
+ add_start_docstrings,
35
+ add_start_docstrings_to_model_forward,
36
+ is_flash_attn_greater_or_equal_2_10,
37
+ logging,
38
+ replace_return_docstrings,
39
+ )
40
+
41
+ from .block_config import AttentionConfig, FFNConfig
42
+ from .configuration_decilm import DeciLMConfig
43
+ from .transformers_4_44_2__activations import ACT2FN
44
+ from .transformers_4_44_2__cache_utils import Cache, StaticCache
45
+ from .transformers_4_44_2__modeling_attn_mask_utils import AttentionMaskConverter
46
+ from .transformers_4_44_2__modeling_flash_attention_utils_backward_compat import _flash_attention_forward
47
+ from .transformers_4_44_2__modeling_outputs import (
48
+ BaseModelOutputWithPast,
49
+ CausalLMOutputWithPast,
50
+ QuestionAnsweringModelOutput,
51
+ SequenceClassifierOutputWithPast,
52
+ TokenClassifierOutput,
53
+ )
54
+ from .transformers_4_44_2__modeling_rope_utils import ROPE_INIT_FUNCTIONS
55
+ from .transformers_4_44_2__pytorch_utils import ALL_LAYERNORM_LAYERS
56
+ from .variable_cache import VariableCache
57
+
58
+ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
59
+
60
+ MODEL_FOR_CAUSAL_LM_MAPPING_NAMES[DeciLMConfig.model_type] = "DeciLMForCausalLM"
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CONFIG_FOR_DOC = "DeciLMConfig"
64
+
65
+
66
+ def _prepare_4d_causal_attention_mask_with_cache_position(
67
+ attention_mask: torch.Tensor,
68
+ sequence_length: int,
69
+ target_length: int,
70
+ dtype: torch.dtype,
71
+ device: torch.device,
72
+ min_dtype: float,
73
+ cache_position: torch.Tensor,
74
+ batch_size: int,
75
+ ):
76
+ """
77
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
78
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
79
+
80
+ Args:
81
+ attention_mask (`torch.Tensor`):
82
+ 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)`.
83
+ sequence_length (`int`):
84
+ The sequence length being processed.
85
+ target_length (`int`):
86
+ 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.
87
+ dtype (`torch.dtype`):
88
+ The dtype to use for the 4D attention mask.
89
+ device (`torch.device`):
90
+ The device to place the 4D attention mask on.
91
+ min_dtype (`float`):
92
+ The minimum value representable with the dtype `dtype`.
93
+ cache_position (`torch.Tensor`):
94
+ Indices depicting the position of the input sequence tokens in the sequence.
95
+ batch_size (`torch.Tensor`):
96
+ Batch size.
97
+ """
98
+ if attention_mask is not None and attention_mask.dim() == 4:
99
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
100
+ causal_mask = attention_mask
101
+ else:
102
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
103
+ if sequence_length != 1:
104
+ causal_mask = torch.triu(causal_mask, diagonal=1)
105
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
106
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
107
+ if attention_mask is not None:
108
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
109
+ mask_length = attention_mask.shape[-1]
110
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
111
+ padding_mask = padding_mask == 0
112
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
113
+ padding_mask, min_dtype
114
+ )
115
+
116
+ return causal_mask
117
+
118
+
119
+ class DeciLMRMSNorm(nn.Module):
120
+ def __init__(self, hidden_size, eps=1e-6):
121
+ """
122
+ DeciLMRMSNorm is equivalent to T5LayerNorm
123
+ """
124
+ super().__init__()
125
+ self.weight = nn.Parameter(torch.ones(hidden_size))
126
+ self.variance_epsilon = eps
127
+
128
+ def forward(self, hidden_states):
129
+ input_dtype = hidden_states.dtype
130
+ hidden_states = hidden_states.to(torch.float32)
131
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
132
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
133
+ return self.weight * hidden_states.to(input_dtype)
134
+
135
+ def extra_repr(self):
136
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
137
+
138
+
139
+ ALL_LAYERNORM_LAYERS.append(DeciLMRMSNorm)
140
+
141
+
142
+ class DeciLMRotaryEmbedding(nn.Module):
143
+ def __init__(
144
+ self,
145
+ dim=None,
146
+ max_position_embeddings=2048,
147
+ base=10000,
148
+ device=None,
149
+ scaling_factor=1.0,
150
+ rope_type="default",
151
+ config: Optional[DeciLMConfig] = None,
152
+ ):
153
+ super().__init__()
154
+ # TODO (joao): remove the `if` below, only used for BC
155
+ self.rope_kwargs = {}
156
+ if config is None:
157
+ logger.warning_once(
158
+ "`DeciLMRotaryEmbedding` can now be fully parameterized by passing the model config through the "
159
+ "`config` argument. All other arguments will be removed in v4.45"
160
+ )
161
+ self.rope_kwargs = {
162
+ "rope_type": rope_type,
163
+ "factor": scaling_factor,
164
+ "dim": dim,
165
+ "base": base,
166
+ "max_position_embeddings": max_position_embeddings,
167
+ }
168
+ self.rope_type = rope_type
169
+ self.max_seq_len_cached = max_position_embeddings
170
+ self.original_max_seq_len = max_position_embeddings
171
+ else:
172
+ # BC: "rope_type" was originally "type"
173
+ if config.rope_scaling is not None:
174
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
175
+ else:
176
+ self.rope_type = "default"
177
+ self.max_seq_len_cached = config.max_position_embeddings
178
+ self.original_max_seq_len = config.max_position_embeddings
179
+
180
+ self.config = config
181
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
182
+
183
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
184
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
185
+ self.original_inv_freq = self.inv_freq
186
+
187
+ def _dynamic_frequency_update(self, position_ids, device):
188
+ """
189
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
190
+ 1 - growing beyond the cached sequence length (allow scaling)
191
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
192
+ """
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.max_seq_len_cached: # growth
195
+ inv_freq, self.attention_scaling = self.rope_init_fn(
196
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
197
+ )
198
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
199
+ self.max_seq_len_cached = seq_len
200
+
201
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
202
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
203
+ self.max_seq_len_cached = self.original_max_seq_len
204
+
205
+ @torch.no_grad()
206
+ def forward(self, x, position_ids):
207
+ if "dynamic" in self.rope_type:
208
+ self._dynamic_frequency_update(position_ids, device=x.device)
209
+
210
+ # Core RoPE block
211
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
212
+ position_ids_expanded = position_ids[:, None, :].float()
213
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
214
+ device_type = x.device.type
215
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
216
+ with torch.autocast(device_type=device_type, enabled=False):
217
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
218
+ emb = torch.cat((freqs, freqs), dim=-1)
219
+ cos = emb.cos()
220
+ sin = emb.sin()
221
+
222
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
223
+ cos = cos * self.attention_scaling
224
+ sin = sin * self.attention_scaling
225
+
226
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
227
+
228
+
229
+ class DeciLMLinearScalingRotaryEmbedding(DeciLMRotaryEmbedding):
230
+ """DeciLMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
231
+
232
+ def __init__(self, *args, **kwargs):
233
+ logger.warning_once(
234
+ "`DeciLMLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
235
+ "`DeciLMRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
236
+ )
237
+ kwargs["rope_type"] = "linear"
238
+ super().__init__(*args, **kwargs)
239
+
240
+
241
+ class DeciLMDynamicNTKScalingRotaryEmbedding(DeciLMRotaryEmbedding):
242
+ """DeciLMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
243
+
244
+ def __init__(self, *args, **kwargs):
245
+ logger.warning_once(
246
+ "`DeciLMDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
247
+ "`DeciLMRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
248
+ "__init__)."
249
+ )
250
+ kwargs["rope_type"] = "dynamic"
251
+ super().__init__(*args, **kwargs)
252
+
253
+
254
+ def rotate_half(x):
255
+ """Rotates half the hidden dims of the input."""
256
+ x1 = x[..., : x.shape[-1] // 2]
257
+ x2 = x[..., x.shape[-1] // 2:]
258
+ return torch.cat((-x2, x1), dim=-1)
259
+
260
+
261
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
262
+ """Applies Rotary Position Embedding to the query and key tensors.
263
+
264
+ Args:
265
+ q (`torch.Tensor`): The query tensor.
266
+ k (`torch.Tensor`): The key tensor.
267
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
268
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
269
+ position_ids (`torch.Tensor`, *optional*):
270
+ Deprecated and unused.
271
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
272
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
273
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
274
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
275
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
276
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
277
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
278
+ Returns:
279
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
280
+ """
281
+ cos = cos.unsqueeze(unsqueeze_dim)
282
+ sin = sin.unsqueeze(unsqueeze_dim)
283
+ q_embed = (q * cos) + (rotate_half(q) * sin)
284
+ k_embed = (k * cos) + (rotate_half(k) * sin)
285
+ return q_embed, k_embed
286
+
287
+
288
+ class DeciLMMLP(nn.Module):
289
+ def __init__(self,
290
+ config: DeciLMConfig,
291
+ ffn_config: FFNConfig,
292
+ ):
293
+ super().__init__()
294
+ self.config = config
295
+ self.ffn_config = ffn_config
296
+ self.hidden_size = config.hidden_size
297
+ self.intermediate_size = _ffn_mult_to_intermediate_size(
298
+ ffn_config.ffn_mult, config.hidden_size) # DeciLM-specific code
299
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
300
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
301
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
302
+ self.act_fn = ACT2FN[config.hidden_act]
303
+
304
+ if ffn_config.sparsify is not None:
305
+ self.register_full_backward_hook(sparsity_backward_hook)
306
+
307
+ def forward(self, x):
308
+ if self.config.pretraining_tp > 1:
309
+ slice = self.intermediate_size // self.config.pretraining_tp
310
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
311
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
312
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
313
+
314
+ gate_proj = torch.cat(
315
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
316
+ )
317
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
318
+
319
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
320
+ down_proj = [
321
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
322
+ ]
323
+ down_proj = sum(down_proj)
324
+ else:
325
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
326
+
327
+ return down_proj
328
+
329
+
330
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
331
+ """
332
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
333
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
334
+ """
335
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
336
+ if n_rep == 1:
337
+ return hidden_states
338
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
339
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
340
+
341
+
342
+ class DeciLMAttention(nn.Module):
343
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
344
+
345
+ def __init__(self,
346
+ config: DeciLMConfig,
347
+ attention_config: AttentionConfig,
348
+ layer_idx: Optional[int] = None,
349
+ ):
350
+ super().__init__()
351
+ self.config = config
352
+ self.attention_config = attention_config
353
+ self.layer_idx = layer_idx
354
+ if layer_idx is None:
355
+ logger.warning_once(
356
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
357
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
358
+ "when creating this class."
359
+ )
360
+
361
+ self.attention_dropout = config.attention_dropout
362
+ self.hidden_size = config.hidden_size
363
+ self.num_heads = config.num_attention_heads
364
+ self.head_dim = self.hidden_size // self.num_heads
365
+ self.num_key_value_groups = attention_config.n_heads_in_group # DeciLM-specific code
366
+ self.num_key_value_heads = self.num_heads // self.num_key_value_groups # DeciLM-specific code
367
+ self.max_position_embeddings = config.max_position_embeddings
368
+ self.rope_theta = config.rope_theta
369
+ self.is_causal = True
370
+
371
+ if (self.head_dim * self.num_heads) != self.hidden_size:
372
+ raise ValueError(
373
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
374
+ f" and `num_heads`: {self.num_heads})."
375
+ )
376
+
377
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
378
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
379
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
380
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
381
+
382
+ # TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the decoder layers)
383
+ self.rotary_emb = DeciLMRotaryEmbedding(config=self.config)
384
+
385
+ if attention_config.sparsify is not None:
386
+ self.register_full_backward_hook(sparsity_backward_hook)
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.Tensor] = None,
392
+ position_ids: Optional[torch.LongTensor] = None,
393
+ past_key_value: Optional[Cache] = None,
394
+ output_attentions: bool = False,
395
+ use_cache: bool = False,
396
+ cache_position: Optional[torch.LongTensor] = None,
397
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
398
+ **kwargs,
399
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
400
+ bsz, q_len, _ = hidden_states.size()
401
+ if self.config.pretraining_tp > 1:
402
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
403
+ query_slices = self.q_proj.weight.split(
404
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
405
+ )
406
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
407
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
408
+
409
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
410
+ query_states = torch.cat(query_states, dim=-1)
411
+
412
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
413
+ key_states = torch.cat(key_states, dim=-1)
414
+
415
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
416
+ value_states = torch.cat(value_states, dim=-1)
417
+
418
+ else:
419
+ query_states = self.q_proj(hidden_states)
420
+ key_states = self.k_proj(hidden_states)
421
+ value_states = self.v_proj(hidden_states)
422
+
423
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
424
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
425
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
426
+
427
+ if position_embeddings is None:
428
+ logger.warning_once(
429
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
430
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
431
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
432
+ "removed and `position_embeddings` will be mandatory."
433
+ )
434
+ cos, sin = self.rotary_emb(value_states, position_ids)
435
+ else:
436
+ cos, sin = position_embeddings
437
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
438
+
439
+ if past_key_value is not None:
440
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
441
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
442
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
443
+
444
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
445
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
446
+
447
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
448
+
449
+ if attention_mask is not None: # no matter the length, we just slice it
450
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
451
+ attn_weights = attn_weights + causal_mask
452
+
453
+ # upcast attention to fp32
454
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
455
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
456
+ attn_output = torch.matmul(attn_weights, value_states)
457
+
458
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
459
+ raise ValueError(
460
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
461
+ f" {attn_output.size()}"
462
+ )
463
+
464
+ attn_output = attn_output.transpose(1, 2).contiguous()
465
+
466
+ attn_output = attn_output.reshape(bsz, q_len, -1)
467
+
468
+ if self.config.pretraining_tp > 1:
469
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
470
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
471
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
472
+ else:
473
+ attn_output = self.o_proj(attn_output)
474
+
475
+ if not output_attentions:
476
+ attn_weights = None
477
+
478
+ return attn_output, attn_weights, past_key_value
479
+
480
+
481
+ class DeciLMFlashAttention2(DeciLMAttention):
482
+ """
483
+ DeciLM flash attention module. This module inherits from `DeciLMAttention` as the weights of the module stays
484
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
485
+ flash attention and deal with padding tokens in case the input contains any of them.
486
+ """
487
+
488
+ def __init__(self, *args, **kwargs):
489
+ super().__init__(*args, **kwargs)
490
+
491
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
492
+ # 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.
493
+ # 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).
494
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
495
+
496
+ self.sliding_window = self.attention_config.prefill_sliding_window
497
+
498
+ def forward(
499
+ self,
500
+ hidden_states: torch.Tensor,
501
+ attention_mask: Optional[torch.LongTensor] = None,
502
+ position_ids: Optional[torch.LongTensor] = None,
503
+ past_key_value: Optional[Cache] = None,
504
+ output_attentions: bool = False,
505
+ use_cache: bool = False,
506
+ cache_position: Optional[torch.LongTensor] = None,
507
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
508
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
509
+ output_attentions = False
510
+
511
+ bsz, q_len, _ = hidden_states.size()
512
+
513
+ query_states = self.q_proj(hidden_states)
514
+ key_states = self.k_proj(hidden_states)
515
+ value_states = self.v_proj(hidden_states)
516
+
517
+ # Flash attention requires the input to have the shape
518
+ # batch_size x seq_length x head_dim x hidden_dim
519
+ # therefore we just need to keep the original shape
520
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
521
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
522
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
523
+
524
+ if position_embeddings is None:
525
+ logger.warning_once(
526
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
527
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
528
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
529
+ "removed and `position_embeddings` will be mandatory."
530
+ )
531
+ cos, sin = self.rotary_emb(value_states, position_ids)
532
+ else:
533
+ cos, sin = position_embeddings
534
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
535
+
536
+ if past_key_value is not None:
537
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
538
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
539
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
540
+
541
+ # 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
542
+ # to be able to avoid many of these transpose/reshape/view.
543
+ query_states = query_states.transpose(1, 2)
544
+ key_states = key_states.transpose(1, 2)
545
+ value_states = value_states.transpose(1, 2)
546
+
547
+ dropout_rate = self.attention_dropout if self.training else 0.0
548
+
549
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
550
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
551
+ # cast them back in the correct dtype just to be sure everything works as expected.
552
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
553
+ # in fp32. (DeciLMRMSNorm handles it correctly)
554
+
555
+ input_dtype = query_states.dtype
556
+ if input_dtype == torch.float32:
557
+ if torch.is_autocast_enabled():
558
+ target_dtype = torch.get_autocast_gpu_dtype()
559
+ # Handle the case where the model is quantized
560
+ elif hasattr(self.config, "_pre_quantization_dtype"):
561
+ target_dtype = self.config._pre_quantization_dtype
562
+ else:
563
+ target_dtype = self.q_proj.weight.dtype
564
+
565
+ logger.warning_once(
566
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
567
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
568
+ f" {target_dtype}."
569
+ )
570
+
571
+ query_states = query_states.to(target_dtype)
572
+ key_states = key_states.to(target_dtype)
573
+ value_states = value_states.to(target_dtype)
574
+
575
+ attn_output = _flash_attention_forward(
576
+ query_states,
577
+ key_states,
578
+ value_states,
579
+ attention_mask,
580
+ q_len,
581
+ position_ids=position_ids,
582
+ dropout=dropout_rate,
583
+ sliding_window=self.sliding_window,
584
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
585
+ is_causal=self.is_causal,
586
+ )
587
+
588
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
589
+ attn_output = self.o_proj(attn_output)
590
+
591
+ if not output_attentions:
592
+ attn_weights = None
593
+
594
+ return attn_output, attn_weights, past_key_value
595
+
596
+
597
+ DECILM_ATTENTION_CLASSES = {
598
+ "eager": DeciLMAttention,
599
+ "flash_attention_2": DeciLMFlashAttention2,
600
+ }
601
+
602
+
603
+ class DeciLMDecoderLayer(nn.Module):
604
+ # DeciLM-specific code
605
+ def __init__(self, config: DeciLMConfig, layer_idx: int):
606
+ super().__init__()
607
+ self.config = config
608
+ self.hidden_size = config.hidden_size
609
+ self.block_config = config.block_configs[layer_idx]
610
+ self.attention_config = self.block_config.attention
611
+ self.ffn_config = self.block_config.ffn
612
+
613
+ if not self.attention_config.no_op:
614
+ self.input_layernorm = DeciLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
615
+ if not self.attention_config.replace_with_linear:
616
+ self.self_attn = DECILM_ATTENTION_CLASSES[config._attn_implementation](
617
+ config=config, attention_config=self.attention_config, layer_idx=layer_idx)
618
+ else:
619
+ self.self_attn = DeciLMLinearAttention(config)
620
+
621
+ if not self.ffn_config.no_op:
622
+ self.post_attention_layernorm = DeciLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
623
+ if not self.ffn_config.replace_with_linear:
624
+ self.mlp = DeciLMMLP(config, self.ffn_config)
625
+ else:
626
+ self.mlp = DeciLMLinearMLP(config)
627
+
628
+ self.is_sliding = self.attention_config.is_sliding
629
+ self.sliding_window = self.attention_config.prefill_sliding_window
630
+
631
+ def forward(
632
+ self,
633
+ hidden_states: torch.Tensor,
634
+ attention_mask: Optional[torch.Tensor] = None,
635
+ position_ids: Optional[torch.LongTensor] = None,
636
+ past_key_value: Optional[Cache] = None,
637
+ output_attentions: Optional[bool] = False,
638
+ use_cache: Optional[bool] = False,
639
+ cache_position: Optional[torch.LongTensor] = None,
640
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
641
+ **kwargs,
642
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
643
+ """
644
+ Args:
645
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
646
+ attention_mask (`torch.FloatTensor`, *optional*):
647
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
648
+ query_sequence_length, key_sequence_length)` if default attention is used.
649
+ output_attentions (`bool`, *optional*):
650
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
651
+ returned tensors for more detail.
652
+ use_cache (`bool`, *optional*):
653
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
654
+ (see `past_key_values`).
655
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
656
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
657
+ Indices depicting the position of the input sequence tokens in the sequence
658
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
659
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
660
+ with `head_dim` being the embedding dimension of each attention head.
661
+ kwargs (`dict`, *optional*):
662
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
663
+ into the model
664
+ """
665
+ if self.attention_config.unshifted_sink and self.attention_config.is_sink:
666
+ attention_mask = self._unshifted_sink_mask(
667
+ attention_mask, hidden_states,
668
+ self.attention_config.window_length, self.attention_config.num_sink_tokens)
669
+ else:
670
+ attention_mask = self._gemma2_window_mask(attention_mask, hidden_states, past_key_value)
671
+
672
+ self_attn_weights = None
673
+ present_key_value = past_key_value
674
+ if self.attention_config.no_op:
675
+ pass
676
+ elif self.attention_config.replace_with_linear:
677
+ residual = hidden_states
678
+ hidden_states = self.input_layernorm(hidden_states)
679
+ hidden_states = self.self_attn(hidden_states)
680
+ hidden_states = residual + hidden_states
681
+ else:
682
+ residual = hidden_states
683
+ hidden_states = self.input_layernorm(hidden_states)
684
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
685
+ hidden_states=hidden_states,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_value=past_key_value,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ cache_position=cache_position,
692
+ position_embeddings=position_embeddings,
693
+ **kwargs,
694
+ )
695
+ hidden_states = residual + hidden_states
696
+
697
+ if not self.ffn_config.no_op:
698
+ residual = hidden_states
699
+ hidden_states = self.post_attention_layernorm(hidden_states)
700
+ hidden_states = self.mlp(hidden_states)
701
+ hidden_states = residual + hidden_states
702
+
703
+ outputs = (hidden_states,)
704
+
705
+ if output_attentions:
706
+ outputs += (self_attn_weights,)
707
+
708
+ if use_cache:
709
+ outputs += (present_key_value,)
710
+
711
+ return outputs
712
+
713
+ def _gemma2_window_mask(self,
714
+ attention_mask: Optional[torch.Tensor],
715
+ hidden_states: torch.Tensor,
716
+ past_key_value: Optional[VariableCache],
717
+ ) -> Optional[torch.Tensor]:
718
+ if self.is_sliding and attention_mask is not None: # efficient SDPA and no padding
719
+ # Flash-attn is a 2D tensor
720
+ if self.config._attn_implementation == "flash_attention_2":
721
+ if past_key_value is not None: # when decoding
722
+ attention_mask = attention_mask[:, -self.sliding_window:]
723
+ else:
724
+ min_dtype = torch.finfo(hidden_states.dtype).min
725
+ sliding_window_mask = torch.tril(
726
+ torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-self.sliding_window
727
+ )
728
+ attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
729
+ if attention_mask.shape[-1] <= 1: # when decoding
730
+ attention_mask = attention_mask[:, :, :, -self.sliding_window:]
731
+ return attention_mask
732
+
733
+ def _unshifted_sink_mask(self,
734
+ attention_mask: torch.Tensor,
735
+ hidden_states: torch.Tensor,
736
+ window_length: int,
737
+ num_sink_tokens: Optional[int],
738
+ ) -> torch.Tensor:
739
+ assert self.config._attn_implementation == "eager", "Unshifted sink is only supported in 'eager' mode."
740
+ assert attention_mask is not None, "The attention mask seems to not be prepared"
741
+
742
+ attention_mask = attention_mask.clone()
743
+ min_dtype = torch.finfo(hidden_states.dtype).min
744
+
745
+ if window_length == 0:
746
+ attention_mask = torch.full_like(attention_mask, fill_value=min_dtype)
747
+ else:
748
+ query_length = attention_mask.shape[-2]
749
+ is_decode = (query_length == 1)
750
+ if is_decode:
751
+ attention_mask[:, :, :, :-window_length] = min_dtype
752
+ else:
753
+ sliding_window_mask = torch.tril(
754
+ torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-window_length
755
+ )
756
+ attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
757
+
758
+ attention_mask[:, :, :, :num_sink_tokens] = 0
759
+ return attention_mask
760
+
761
+
762
+ DECILM_START_DOCSTRING = r"""
763
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
764
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
765
+ etc.)
766
+
767
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
768
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
769
+ and behavior.
770
+
771
+ Parameters:
772
+ config ([`DeciLMConfig`]):
773
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
774
+ load the weights associated with the model, only the configuration. Check out the
775
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
776
+ """
777
+
778
+
779
+ @add_start_docstrings(
780
+ "The bare DeciLM Model outputting raw hidden-states without any specific head on top.",
781
+ DECILM_START_DOCSTRING,
782
+ )
783
+ class DeciLMPreTrainedModel(PreTrainedModel):
784
+ config_class = DeciLMConfig
785
+ base_model_prefix = "model"
786
+ supports_gradient_checkpointing = True
787
+ _no_split_modules = ["DeciLMDecoderLayer"]
788
+ _skip_keys_device_placement = ["past_key_values"]
789
+ _supports_flash_attn_2 = True
790
+ _supports_sdpa = False
791
+ _supports_cache_class = True
792
+ _supports_quantized_cache = False
793
+ _supports_static_cache = True
794
+
795
+ def _init_weights(self, module):
796
+ std = self.config.initializer_range
797
+ if isinstance(module, nn.Linear):
798
+ module.weight.data.normal_(mean=0.0, std=std)
799
+ if module.bias is not None:
800
+ module.bias.data.zero_()
801
+ elif isinstance(module, nn.Embedding):
802
+ module.weight.data.normal_(mean=0.0, std=std)
803
+ if module.padding_idx is not None:
804
+ module.weight.data[module.padding_idx].zero_()
805
+
806
+ def _prepare_generation_config(
807
+ self,
808
+ generation_config: Optional[GenerationConfig],
809
+ *args,
810
+ **kwargs,
811
+ ) -> tuple[GenerationConfig, dict]:
812
+ # DeciLM-specific code
813
+ generation_config, model_kwargs = super()._prepare_generation_config(generation_config, *args, **kwargs)
814
+ generation_config.cache_implementation = "variable"
815
+ NEED_SETUP_CACHE_CLASSES_MAPPING["variable"] = VariableCache
816
+ return generation_config, model_kwargs
817
+
818
+
819
+ DECILM_INPUTS_DOCSTRING = r"""
820
+ Args:
821
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
822
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
823
+ it.
824
+
825
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
826
+ [`PreTrainedTokenizer.__call__`] for details.
827
+
828
+ [What are input IDs?](../glossary#input-ids)
829
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
830
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
831
+
832
+ - 1 for tokens that are **not masked**,
833
+ - 0 for tokens that are **masked**.
834
+
835
+ [What are attention masks?](../glossary#attention-mask)
836
+
837
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
838
+ [`PreTrainedTokenizer.__call__`] for details.
839
+
840
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
841
+ `past_key_values`).
842
+
843
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
844
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
845
+ information on the default strategy.
846
+
847
+ - 1 indicates the head is **not masked**,
848
+ - 0 indicates the head is **masked**.
849
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
850
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
851
+ config.n_positions - 1]`.
852
+
853
+ [What are position IDs?](../glossary#position-ids)
854
+ past_key_values (`VariableCache`, *optional*):
855
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
856
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
857
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
858
+
859
+ If passed to the forward function, past_key_values must be a VariableCache object (see imports).
860
+ For generation purposes, this is already handled inside model.generate().
861
+
862
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
863
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
864
+ of shape `(batch_size, sequence_length)`.
865
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
866
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
867
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
868
+ model's internal embedding lookup matrix.
869
+ use_cache (`bool`, *optional*):
870
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
871
+ `past_key_values`).
872
+ output_attentions (`bool`, *optional*):
873
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
874
+ tensors for more detail.
875
+ output_hidden_states (`bool`, *optional*):
876
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
877
+ more detail.
878
+ return_dict (`bool`, *optional*):
879
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
880
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
881
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
882
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
883
+ the complete sequence length.
884
+ """
885
+
886
+
887
+ @add_start_docstrings(
888
+ "The bare DeciLM Model outputting raw hidden-states without any specific head on top.",
889
+ DECILM_START_DOCSTRING,
890
+ )
891
+ class DeciLMModel(DeciLMPreTrainedModel):
892
+ """
893
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeciLMDecoderLayer`]
894
+
895
+ Args:
896
+ config: DeciLMConfig
897
+ """
898
+
899
+ def __init__(self, config: DeciLMConfig):
900
+ super().__init__(config)
901
+ self.padding_idx = config.pad_token_id
902
+ self.vocab_size = config.vocab_size
903
+
904
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
905
+ self.layers = nn.ModuleList(
906
+ [DeciLMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
907
+ )
908
+ self.norm = DeciLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
909
+ self.rotary_emb = DeciLMRotaryEmbedding(config=config)
910
+ self.gradient_checkpointing = False
911
+
912
+ # Initialize weights and apply final processing
913
+ self.post_init()
914
+
915
+ def get_input_embeddings(self):
916
+ return self.embed_tokens
917
+
918
+ def set_input_embeddings(self, value):
919
+ self.embed_tokens = value
920
+
921
+ @add_start_docstrings_to_model_forward(DECILM_INPUTS_DOCSTRING)
922
+ def forward(
923
+ self,
924
+ input_ids: torch.LongTensor = None,
925
+ attention_mask: Optional[torch.Tensor] = None,
926
+ position_ids: Optional[torch.LongTensor] = None,
927
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
928
+ inputs_embeds: Optional[torch.FloatTensor] = None,
929
+ use_cache: Optional[bool] = None,
930
+ output_attentions: Optional[bool] = None,
931
+ output_hidden_states: Optional[bool] = None,
932
+ return_dict: Optional[bool] = None,
933
+ cache_position: Optional[torch.LongTensor] = None,
934
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
935
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
936
+ output_hidden_states = (
937
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
938
+ )
939
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
940
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
941
+
942
+ if (input_ids is None) ^ (inputs_embeds is not None):
943
+ raise ValueError(
944
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
945
+ )
946
+
947
+ if self.gradient_checkpointing and self.training and use_cache:
948
+ logger.warning_once(
949
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
950
+ )
951
+ use_cache = False
952
+
953
+ if inputs_embeds is None:
954
+ inputs_embeds = self.embed_tokens(input_ids)
955
+
956
+ is_legacy_cache_format = (past_key_values is not None) and not isinstance(past_key_values, Cache)
957
+ if is_legacy_cache_format:
958
+ raise NotImplementedError("DeciLMModel does not support legacy cache format, please use a newer "
959
+ "transformers version or use VariableCache explicitly (see import in this file).")
960
+
961
+ if cache_position is None:
962
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
963
+ cache_position = torch.arange(
964
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
965
+ )
966
+ if position_ids is None:
967
+ position_ids = cache_position.unsqueeze(0)
968
+
969
+ causal_mask = self._update_causal_mask(
970
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
971
+ )
972
+ hidden_states = inputs_embeds
973
+
974
+ # create position embeddings to be shared across the decoder layers
975
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
976
+
977
+ # decoder layers
978
+ all_hidden_states = () if output_hidden_states else None
979
+ all_self_attns = () if output_attentions else None
980
+ next_decoder_cache = None
981
+
982
+ for decoder_layer in self.layers:
983
+ if output_hidden_states:
984
+ all_hidden_states += (hidden_states,)
985
+
986
+ if self.gradient_checkpointing and self.training:
987
+ layer_outputs = self._gradient_checkpointing_func(
988
+ decoder_layer.__call__,
989
+ hidden_states,
990
+ causal_mask,
991
+ position_ids,
992
+ past_key_values,
993
+ output_attentions,
994
+ use_cache,
995
+ cache_position,
996
+ position_embeddings,
997
+ )
998
+ else:
999
+ layer_outputs = decoder_layer(
1000
+ hidden_states,
1001
+ attention_mask=causal_mask,
1002
+ position_ids=position_ids,
1003
+ past_key_value=past_key_values,
1004
+ output_attentions=output_attentions,
1005
+ use_cache=use_cache,
1006
+ cache_position=cache_position,
1007
+ position_embeddings=position_embeddings,
1008
+ )
1009
+
1010
+ hidden_states = layer_outputs[0]
1011
+
1012
+ if use_cache:
1013
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1014
+
1015
+ if output_attentions:
1016
+ all_self_attns += (layer_outputs[1],)
1017
+
1018
+ hidden_states = self.norm(hidden_states)
1019
+
1020
+ # add hidden states from the last decoder layer
1021
+ if output_hidden_states:
1022
+ all_hidden_states += (hidden_states,)
1023
+
1024
+ next_cache = next_decoder_cache if use_cache else None
1025
+
1026
+ if not return_dict:
1027
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1028
+ return BaseModelOutputWithPast(
1029
+ last_hidden_state=hidden_states,
1030
+ past_key_values=next_cache,
1031
+ hidden_states=all_hidden_states,
1032
+ attentions=all_self_attns,
1033
+ )
1034
+
1035
+ def _update_causal_mask(
1036
+ self,
1037
+ attention_mask: torch.Tensor,
1038
+ input_tensor: torch.Tensor,
1039
+ cache_position: torch.Tensor,
1040
+ past_key_values: Cache,
1041
+ output_attentions: bool,
1042
+ ):
1043
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1044
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1045
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1046
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1047
+
1048
+ if self.config._attn_implementation == "flash_attention_2":
1049
+ if attention_mask is not None and 0.0 in attention_mask:
1050
+ return attention_mask
1051
+ return None
1052
+
1053
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1054
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1055
+ # to infer the attention mask.
1056
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1057
+ assert not isinstance(past_key_values, StaticCache), "DeciLM does not support StaticCache"
1058
+ using_static_cache = isinstance(past_key_values, StaticCache)
1059
+
1060
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1061
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1062
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1063
+ attention_mask,
1064
+ inputs_embeds=input_tensor,
1065
+ past_key_values_length=past_seen_tokens,
1066
+ is_training=self.training,
1067
+ ) and all([not layer.is_sliding for layer in self.layers]):
1068
+ return None
1069
+
1070
+ dtype, device = input_tensor.dtype, input_tensor.device
1071
+ min_dtype = torch.finfo(dtype).min
1072
+ sequence_length = input_tensor.shape[1]
1073
+ if using_static_cache:
1074
+ target_length = past_key_values.get_max_length()
1075
+ else:
1076
+ target_length = (
1077
+ attention_mask.shape[-1]
1078
+ if isinstance(attention_mask, torch.Tensor)
1079
+ else past_seen_tokens + sequence_length + 1
1080
+ )
1081
+
1082
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1083
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1084
+ attention_mask,
1085
+ sequence_length=sequence_length,
1086
+ target_length=target_length,
1087
+ dtype=dtype,
1088
+ device=device,
1089
+ min_dtype=min_dtype,
1090
+ cache_position=cache_position,
1091
+ batch_size=input_tensor.shape[0],
1092
+ )
1093
+
1094
+ if (
1095
+ self.config._attn_implementation == "sdpa"
1096
+ and attention_mask is not None
1097
+ and attention_mask.device.type == "cuda"
1098
+ and not output_attentions
1099
+ ):
1100
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1101
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1102
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1103
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1104
+
1105
+ return causal_mask
1106
+
1107
+
1108
+ class DeciLMForCausalLM(DeciLMPreTrainedModel, GenerationMixin):
1109
+ _tied_weights_keys = ["lm_head.weight"]
1110
+
1111
+ def __init__(self, config):
1112
+ super().__init__(config)
1113
+ self.model = DeciLMModel(config)
1114
+ self.vocab_size = config.vocab_size
1115
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1116
+
1117
+ # Initialize weights and apply final processing
1118
+ self.post_init()
1119
+
1120
+ def get_input_embeddings(self):
1121
+ return self.model.embed_tokens
1122
+
1123
+ def set_input_embeddings(self, value):
1124
+ self.model.embed_tokens = value
1125
+
1126
+ def get_output_embeddings(self):
1127
+ return self.lm_head
1128
+
1129
+ def set_output_embeddings(self, new_embeddings):
1130
+ self.lm_head = new_embeddings
1131
+
1132
+ def set_decoder(self, decoder):
1133
+ self.model = decoder
1134
+
1135
+ def get_decoder(self):
1136
+ return self.model
1137
+
1138
+ @add_start_docstrings_to_model_forward(DECILM_INPUTS_DOCSTRING)
1139
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1140
+ def forward(
1141
+ self,
1142
+ input_ids: torch.LongTensor = None,
1143
+ attention_mask: Optional[torch.Tensor] = None,
1144
+ position_ids: Optional[torch.LongTensor] = None,
1145
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1146
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1147
+ labels: Optional[torch.LongTensor] = None,
1148
+ use_cache: Optional[bool] = None,
1149
+ output_attentions: Optional[bool] = None,
1150
+ output_hidden_states: Optional[bool] = None,
1151
+ return_dict: Optional[bool] = None,
1152
+ cache_position: Optional[torch.LongTensor] = None,
1153
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1154
+ r"""
1155
+ Args:
1156
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1157
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1158
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1159
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1160
+
1161
+ Return:
1162
+ """
1163
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1164
+ output_hidden_states = (
1165
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1166
+ )
1167
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1168
+
1169
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1170
+ outputs = self.model(
1171
+ input_ids=input_ids,
1172
+ attention_mask=attention_mask,
1173
+ position_ids=position_ids,
1174
+ past_key_values=past_key_values,
1175
+ inputs_embeds=inputs_embeds,
1176
+ use_cache=use_cache,
1177
+ output_attentions=output_attentions,
1178
+ output_hidden_states=output_hidden_states,
1179
+ return_dict=return_dict,
1180
+ cache_position=cache_position,
1181
+ )
1182
+
1183
+ ENABLE_LIGER = True
1184
+ hidden_states = outputs[0]
1185
+ loss = None
1186
+ logits = None
1187
+ if ENABLE_LIGER and self.training and (labels is not None):
1188
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
1189
+ shift_labels = labels[..., 1:].contiguous()
1190
+
1191
+ # flatten tokens
1192
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
1193
+ shift_labels = shift_labels.view(-1)
1194
+
1195
+ lce = LigerFusedLinearCrossEntropyLoss()
1196
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
1197
+ else:
1198
+ if self.config.pretraining_tp > 1:
1199
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1200
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1201
+ logits = torch.cat(logits, dim=-1)
1202
+ else:
1203
+ logits = self.lm_head(hidden_states)
1204
+ logits = logits.float()
1205
+
1206
+ loss = None
1207
+ if labels is not None:
1208
+ # Shift so that tokens < n predict n
1209
+ shift_logits = logits[..., :-1, :].contiguous()
1210
+ shift_labels = labels[..., 1:].contiguous()
1211
+ # Flatten the tokens
1212
+ loss_fct = CrossEntropyLoss()
1213
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1214
+ shift_labels = shift_labels.view(-1)
1215
+ # Enable model parallelism
1216
+ shift_labels = shift_labels.to(shift_logits.device)
1217
+ loss = loss_fct(shift_logits, shift_labels)
1218
+
1219
+ if not return_dict:
1220
+ output = (logits,) + outputs[1:]
1221
+ return (loss,) + output if loss is not None else output
1222
+
1223
+ return CausalLMOutputWithPast(
1224
+ loss=loss,
1225
+ logits=logits,
1226
+ past_key_values=outputs.past_key_values,
1227
+ hidden_states=outputs.hidden_states,
1228
+ attentions=outputs.attentions,
1229
+ )
1230
+
1231
+ def prepare_inputs_for_generation(
1232
+ self,
1233
+ input_ids,
1234
+ past_key_values=None,
1235
+ attention_mask=None,
1236
+ inputs_embeds=None,
1237
+ cache_position=None,
1238
+ position_ids=None,
1239
+ use_cache=True,
1240
+ **kwargs,
1241
+ ):
1242
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1243
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1244
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1245
+ if past_key_values is not None:
1246
+ if inputs_embeds is not None: # Exception 1
1247
+ input_ids = input_ids[:, -cache_position.shape[0]:]
1248
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1249
+ input_ids = input_ids[:, cache_position]
1250
+
1251
+ if attention_mask is not None and position_ids is None:
1252
+ # create position_ids on the fly for batch generation
1253
+ position_ids = attention_mask.long().cumsum(-1) - 1
1254
+ position_ids.masked_fill_(attention_mask == 0, 1)
1255
+ if past_key_values:
1256
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1257
+
1258
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1259
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1260
+
1261
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1262
+ if inputs_embeds is not None and cache_position[0] == 0:
1263
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1264
+ else:
1265
+ # The clone here is for the same reason as for `position_ids`.
1266
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1267
+
1268
+ assert not isinstance(past_key_values, StaticCache), "DeciLM does not support StaticCache"
1269
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1270
+ if model_inputs["inputs_embeds"] is not None:
1271
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1272
+ device = model_inputs["inputs_embeds"].device
1273
+ else:
1274
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1275
+ device = model_inputs["input_ids"].device
1276
+
1277
+ dtype = self.lm_head.weight.dtype
1278
+ min_dtype = torch.finfo(dtype).min
1279
+
1280
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1281
+ attention_mask,
1282
+ sequence_length=sequence_length,
1283
+ target_length=past_key_values.get_max_length(),
1284
+ dtype=dtype,
1285
+ device=device,
1286
+ min_dtype=min_dtype,
1287
+ cache_position=cache_position,
1288
+ batch_size=batch_size,
1289
+ )
1290
+
1291
+ model_inputs.update(
1292
+ {
1293
+ "position_ids": position_ids,
1294
+ "cache_position": cache_position,
1295
+ "past_key_values": past_key_values,
1296
+ "use_cache": use_cache,
1297
+ "attention_mask": attention_mask,
1298
+ }
1299
+ )
1300
+ return model_inputs
1301
+
1302
+ def _maybe_initialize_input_ids_for_generation(
1303
+ self,
1304
+ inputs: Optional[torch.Tensor] = None,
1305
+ bos_token_id: Optional[torch.Tensor] = None,
1306
+ model_kwargs: Optional[dict[str, torch.Tensor]] = None,
1307
+ ) -> torch.LongTensor:
1308
+ """
1309
+ Patching hf bug that creates wrong cache length if only inputs_embeds are passed to the model
1310
+ """
1311
+ input_ids = super()._maybe_initialize_input_ids_for_generation(
1312
+ inputs=inputs, bos_token_id=bos_token_id, model_kwargs=model_kwargs)
1313
+ if (
1314
+ "inputs_embeds" in model_kwargs
1315
+ and input_ids is not None
1316
+ and input_ids.shape[1] == 0
1317
+ ):
1318
+ batch_size, input_sequence_length = model_kwargs["inputs_embeds"].shape[:2]
1319
+ input_ids = torch.zeros((batch_size, input_sequence_length), dtype=torch.long, device=self.device)
1320
+ return input_ids
1321
+
1322
+ def generate(
1323
+ self,
1324
+ inputs: Optional[torch.Tensor] = None,
1325
+ *args,
1326
+ **kwargs,
1327
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1328
+ """
1329
+ Patching hf bug that creates wrong cache length if only inputs_embeds are passed to the model
1330
+ """
1331
+ only_passed_inputs_embeds = (
1332
+ "inputs_embeds" in kwargs and
1333
+ "input_ids" not in kwargs and
1334
+ inputs is None
1335
+ )
1336
+ if only_passed_inputs_embeds:
1337
+ input_sequence_length = kwargs["inputs_embeds"].shape[1]
1338
+
1339
+ generation_output = super().generate(inputs=inputs, *args, **kwargs)
1340
+
1341
+ if only_passed_inputs_embeds and isinstance(generation_output, torch.Tensor):
1342
+ generation_output = generation_output[:, input_sequence_length:]
1343
+
1344
+ return generation_output
1345
+
1346
+
1347
+ @add_start_docstrings(
1348
+ """
1349
+ The DeciLM Model transformer with a sequence classification head on top (linear layer).
1350
+
1351
+ [`DeciLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1352
+ (e.g. GPT-2) do.
1353
+
1354
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1355
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1356
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1357
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1358
+ each row of the batch).
1359
+ """,
1360
+ DECILM_START_DOCSTRING,
1361
+ )
1362
+ class DeciLMForSequenceClassification(DeciLMPreTrainedModel):
1363
+ def __init__(self, config):
1364
+ super().__init__(config)
1365
+ self.num_labels = config.num_labels
1366
+ self.model = DeciLMModel(config)
1367
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1368
+
1369
+ # Initialize weights and apply final processing
1370
+ self.post_init()
1371
+
1372
+ def get_input_embeddings(self):
1373
+ return self.model.embed_tokens
1374
+
1375
+ def set_input_embeddings(self, value):
1376
+ self.model.embed_tokens = value
1377
+
1378
+ @add_start_docstrings_to_model_forward(DECILM_INPUTS_DOCSTRING)
1379
+ def forward(
1380
+ self,
1381
+ input_ids: Optional[torch.LongTensor] = None,
1382
+ attention_mask: Optional[torch.Tensor] = None,
1383
+ position_ids: Optional[torch.LongTensor] = None,
1384
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1385
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1386
+ labels: Optional[torch.LongTensor] = None,
1387
+ use_cache: Optional[bool] = None,
1388
+ output_attentions: Optional[bool] = None,
1389
+ output_hidden_states: Optional[bool] = None,
1390
+ return_dict: Optional[bool] = None,
1391
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1392
+ r"""
1393
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1394
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1395
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1396
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1397
+ """
1398
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1399
+
1400
+ transformer_outputs = self.model(
1401
+ input_ids,
1402
+ attention_mask=attention_mask,
1403
+ position_ids=position_ids,
1404
+ past_key_values=past_key_values,
1405
+ inputs_embeds=inputs_embeds,
1406
+ use_cache=use_cache,
1407
+ output_attentions=output_attentions,
1408
+ output_hidden_states=output_hidden_states,
1409
+ return_dict=return_dict,
1410
+ )
1411
+ hidden_states = transformer_outputs[0]
1412
+ logits = self.score(hidden_states)
1413
+
1414
+ if input_ids is not None:
1415
+ batch_size = input_ids.shape[0]
1416
+ else:
1417
+ batch_size = inputs_embeds.shape[0]
1418
+
1419
+ if self.config.pad_token_id is None and batch_size != 1:
1420
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1421
+ if self.config.pad_token_id is None:
1422
+ sequence_lengths = -1
1423
+ else:
1424
+ if input_ids is not None:
1425
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1426
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1427
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1428
+ sequence_lengths = sequence_lengths.to(logits.device)
1429
+ else:
1430
+ sequence_lengths = -1
1431
+
1432
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1433
+
1434
+ loss = None
1435
+ if labels is not None:
1436
+ labels = labels.to(logits.device)
1437
+ if self.config.problem_type is None:
1438
+ if self.num_labels == 1:
1439
+ self.config.problem_type = "regression"
1440
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1441
+ self.config.problem_type = "single_label_classification"
1442
+ else:
1443
+ self.config.problem_type = "multi_label_classification"
1444
+
1445
+ if self.config.problem_type == "regression":
1446
+ loss_fct = MSELoss()
1447
+ if self.num_labels == 1:
1448
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1449
+ else:
1450
+ loss = loss_fct(pooled_logits, labels)
1451
+ elif self.config.problem_type == "single_label_classification":
1452
+ loss_fct = CrossEntropyLoss()
1453
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1454
+ elif self.config.problem_type == "multi_label_classification":
1455
+ loss_fct = BCEWithLogitsLoss()
1456
+ loss = loss_fct(pooled_logits, labels)
1457
+ if not return_dict:
1458
+ output = (pooled_logits,) + transformer_outputs[1:]
1459
+ return ((loss,) + output) if loss is not None else output
1460
+
1461
+ return SequenceClassifierOutputWithPast(
1462
+ loss=loss,
1463
+ logits=pooled_logits,
1464
+ past_key_values=transformer_outputs.past_key_values,
1465
+ hidden_states=transformer_outputs.hidden_states,
1466
+ attentions=transformer_outputs.attentions,
1467
+ )
1468
+
1469
+
1470
+ @add_start_docstrings(
1471
+ """
1472
+ The DeciLM Model transformer with a span classification head on top for extractive question-answering tasks like
1473
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1474
+ """,
1475
+ DECILM_START_DOCSTRING,
1476
+ )
1477
+ class DeciLMForQuestionAnswering(DeciLMPreTrainedModel):
1478
+ base_model_prefix = "transformer"
1479
+
1480
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->DeciLM
1481
+ def __init__(self, config):
1482
+ super().__init__(config)
1483
+ self.transformer = DeciLMModel(config)
1484
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1485
+
1486
+ # Initialize weights and apply final processing
1487
+ self.post_init()
1488
+
1489
+ def get_input_embeddings(self):
1490
+ return self.transformer.embed_tokens
1491
+
1492
+ def set_input_embeddings(self, value):
1493
+ self.transformer.embed_tokens = value
1494
+
1495
+ @add_start_docstrings_to_model_forward(DECILM_INPUTS_DOCSTRING)
1496
+ def forward(
1497
+ self,
1498
+ input_ids: Optional[torch.LongTensor] = None,
1499
+ attention_mask: Optional[torch.FloatTensor] = None,
1500
+ position_ids: Optional[torch.LongTensor] = None,
1501
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1502
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1503
+ start_positions: Optional[torch.LongTensor] = None,
1504
+ end_positions: Optional[torch.LongTensor] = None,
1505
+ output_attentions: Optional[bool] = None,
1506
+ output_hidden_states: Optional[bool] = None,
1507
+ return_dict: Optional[bool] = None,
1508
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1509
+ r"""
1510
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1511
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1512
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1513
+ are not taken into account for computing the loss.
1514
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1515
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1516
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1517
+ are not taken into account for computing the loss.
1518
+ """
1519
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1520
+
1521
+ outputs = self.transformer(
1522
+ input_ids,
1523
+ attention_mask=attention_mask,
1524
+ position_ids=position_ids,
1525
+ past_key_values=past_key_values,
1526
+ inputs_embeds=inputs_embeds,
1527
+ output_attentions=output_attentions,
1528
+ output_hidden_states=output_hidden_states,
1529
+ return_dict=return_dict,
1530
+ )
1531
+
1532
+ sequence_output = outputs[0]
1533
+
1534
+ logits = self.qa_outputs(sequence_output)
1535
+ start_logits, end_logits = logits.split(1, dim=-1)
1536
+ start_logits = start_logits.squeeze(-1).contiguous()
1537
+ end_logits = end_logits.squeeze(-1).contiguous()
1538
+
1539
+ total_loss = None
1540
+ if start_positions is not None and end_positions is not None:
1541
+ # If we are on multi-GPU, split add a dimension
1542
+ if len(start_positions.size()) > 1:
1543
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1544
+ if len(end_positions.size()) > 1:
1545
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1546
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1547
+ ignored_index = start_logits.size(1)
1548
+ start_positions = start_positions.clamp(0, ignored_index)
1549
+ end_positions = end_positions.clamp(0, ignored_index)
1550
+
1551
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1552
+ start_loss = loss_fct(start_logits, start_positions)
1553
+ end_loss = loss_fct(end_logits, end_positions)
1554
+ total_loss = (start_loss + end_loss) / 2
1555
+
1556
+ if not return_dict:
1557
+ output = (start_logits, end_logits) + outputs[2:]
1558
+ return ((total_loss,) + output) if total_loss is not None else output
1559
+
1560
+ return QuestionAnsweringModelOutput(
1561
+ loss=total_loss,
1562
+ start_logits=start_logits,
1563
+ end_logits=end_logits,
1564
+ hidden_states=outputs.hidden_states,
1565
+ attentions=outputs.attentions,
1566
+ )
1567
+
1568
+
1569
+ @add_start_docstrings(
1570
+ """
1571
+ The DeciLM Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1572
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1573
+ """,
1574
+ DECILM_START_DOCSTRING,
1575
+ )
1576
+ class DeciLMForTokenClassification(DeciLMPreTrainedModel):
1577
+ def __init__(self, config):
1578
+ super().__init__(config)
1579
+ self.num_labels = config.num_labels
1580
+ self.model = DeciLMModel(config)
1581
+ if getattr(config, "classifier_dropout", None) is not None:
1582
+ classifier_dropout = config.classifier_dropout
1583
+ elif getattr(config, "hidden_dropout", None) is not None:
1584
+ classifier_dropout = config.hidden_dropout
1585
+ else:
1586
+ classifier_dropout = 0.1
1587
+ self.dropout = nn.Dropout(classifier_dropout)
1588
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1589
+
1590
+ # Initialize weights and apply final processing
1591
+ self.post_init()
1592
+
1593
+ def get_input_embeddings(self):
1594
+ return self.model.embed_tokens
1595
+
1596
+ def set_input_embeddings(self, value):
1597
+ self.model.embed_tokens = value
1598
+
1599
+ @add_start_docstrings_to_model_forward(DECILM_INPUTS_DOCSTRING)
1600
+ def forward(
1601
+ self,
1602
+ input_ids: Optional[torch.LongTensor] = None,
1603
+ attention_mask: Optional[torch.Tensor] = None,
1604
+ position_ids: Optional[torch.LongTensor] = None,
1605
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1606
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1607
+ labels: Optional[torch.LongTensor] = None,
1608
+ use_cache: Optional[bool] = None,
1609
+ output_attentions: Optional[bool] = None,
1610
+ output_hidden_states: Optional[bool] = None,
1611
+ return_dict: Optional[bool] = None,
1612
+ ) -> Union[Tuple, TokenClassifierOutput]:
1613
+ r"""
1614
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1615
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1616
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1617
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1618
+ """
1619
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1620
+
1621
+ outputs = self.model(
1622
+ input_ids,
1623
+ attention_mask=attention_mask,
1624
+ position_ids=position_ids,
1625
+ past_key_values=past_key_values,
1626
+ inputs_embeds=inputs_embeds,
1627
+ use_cache=use_cache,
1628
+ output_attentions=output_attentions,
1629
+ output_hidden_states=output_hidden_states,
1630
+ return_dict=return_dict,
1631
+ )
1632
+ sequence_output = outputs[0]
1633
+ sequence_output = self.dropout(sequence_output)
1634
+ logits = self.score(sequence_output)
1635
+
1636
+ loss = None
1637
+ if labels is not None:
1638
+ loss_fct = CrossEntropyLoss()
1639
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1640
+
1641
+ if not return_dict:
1642
+ output = (logits,) + outputs[2:]
1643
+ return ((loss,) + output) if loss is not None else output
1644
+
1645
+ return TokenClassifierOutput(
1646
+ loss=loss,
1647
+ logits=logits,
1648
+ hidden_states=outputs.hidden_states,
1649
+ attentions=outputs.attentions,
1650
+ )
1651
+
1652
+
1653
+ ########################################################################
1654
+ # DeciLM-specific code
1655
+ ########################################################################
1656
+
1657
+
1658
+ def _ffn_mult_to_intermediate_size(ffn_mult: float, n_embd: int) -> int:
1659
+ # DeciLM-specific code
1660
+ intermediate_size = int(2 * ffn_mult * n_embd / 3)
1661
+ return _find_multiple(intermediate_size, 256)
1662
+
1663
+
1664
+ def _find_multiple(n: int, k: int) -> int:
1665
+ # DeciLM-specific code
1666
+ if n % k == 0:
1667
+ return n
1668
+ return n + k - (n % k)
1669
+
1670
+
1671
+ class DeciLMLinearMLP(nn.Module):
1672
+ # DeciLM-specific code
1673
+ def __init__(self,
1674
+ config: DeciLMConfig,
1675
+ ):
1676
+ super().__init__()
1677
+ self.linear_mlp = nn.Linear(in_features=config.hidden_size,
1678
+ out_features=config.hidden_size,
1679
+ bias=False)
1680
+
1681
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1682
+ return self.linear_mlp.forward(x)
1683
+
1684
+
1685
+ class DeciLMLinearAttention(nn.Module):
1686
+ # DeciLM-specific code
1687
+ def __init__(self,
1688
+ config: DeciLMConfig,
1689
+ ):
1690
+ super().__init__()
1691
+ self.linear_attn = nn.Linear(in_features=config.hidden_size,
1692
+ out_features=config.hidden_size,
1693
+ bias=False)
1694
+
1695
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1696
+ return self.linear_attn.forward(x)
1697
+
1698
+
1699
+ def sparsity_backward_hook(*args, **kwargs):
1700
+ raise NotImplementedError("No support for sparsity when training HF DeciLM (inference is ok though)")