Text Generation
Transformers
Safetensors
English
ddllama
conversational
custom_code
xuan-luo commited on
Commit
331deaa
·
verified ·
1 Parent(s): fe05172

Create modeling_ddllama.py

Browse files
Files changed (1) hide show
  1. modeling_ddllama.py +1225 -0
modeling_ddllama.py ADDED
@@ -0,0 +1,1225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ import inspect
21
+ import os
22
+ import math
23
+ from einops import repeat
24
+ from typing import List, Optional, Tuple, Union, Dict, Callable
25
+
26
+ import torch
27
+ import torch.distributed as dist
28
+ from torch.distributions.uniform import Uniform
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
36
+ from transformers.generation import GenerationMixin
37
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
38
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs, _flash_attention_forward
39
+ from transformers.modeling_outputs import (
40
+ BaseModelOutputWithPast,
41
+ CausalLMOutputWithPast,
42
+ QuestionAnsweringModelOutput,
43
+ SequenceClassifierOutputWithPast,
44
+ TokenClassifierOutput,
45
+ )
46
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
47
+ from transformers.modeling_utils import PreTrainedModel
48
+ from transformers.processing_utils import Unpack
49
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
50
+ from transformers.utils import (
51
+ LossKwargs,
52
+ add_code_sample_docstrings,
53
+ add_start_docstrings,
54
+ add_start_docstrings_to_model_forward,
55
+ is_flash_attn_greater_or_equal_2_10,
56
+ logging,
57
+ replace_return_docstrings,
58
+ )
59
+ import wandb
60
+ from .configuration_ddllama import DDLlamaConfig
61
+
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+ uniform_map: Dict[torch.device, Callable] = {}
66
+ def multiplicative_jitter(input, epsilon, training):
67
+
68
+ if epsilon == 0 or not training:
69
+ return input
70
+
71
+ uniform = uniform_map.get(input.device)
72
+
73
+ if uniform is None:
74
+ uniform = Uniform(low=torch.tensor(1.0 - epsilon, device=input.device, dtype=input.dtype),
75
+ high=torch.tensor(1.0 + epsilon, device=input.device, dtype=input.dtype)
76
+ ).rsample
77
+ uniform_map[input.device] = uniform
78
+
79
+ return input * uniform(input.shape)
80
+
81
+ class v2core(torch.autograd.Function):
82
+ @staticmethod
83
+ def forward(
84
+ ctx,
85
+ scores: torch.Tensor,
86
+ multiplier: torch.Tensor,
87
+ selected_experts: torch.Tensor,
88
+ masked_gates: torch.Tensor,
89
+ mask_for_one: torch.Tensor,
90
+ ):
91
+ ctx.save_for_backward(multiplier, selected_experts, masked_gates)
92
+ return multiplier * mask_for_one
93
+
94
+ @staticmethod
95
+ def backward(
96
+ ctx,
97
+ grad_at_output: torch.Tensor,
98
+ ):
99
+ multiplier, selected_experts, masked_gates = ctx.saved_tensors
100
+
101
+ grad_at_output = grad_at_output * multiplier
102
+
103
+ grad_at_scores_expaned = masked_gates * grad_at_output.mul(-1)
104
+ grad_at_scores_expaned.scatter_add_(
105
+ dim=-1,
106
+ index=selected_experts,
107
+ src=grad_at_output,
108
+ )
109
+
110
+ return (
111
+ grad_at_scores_expaned,
112
+ None,
113
+ None,
114
+ None,
115
+ None,
116
+ )
117
+
118
+ def sparsemixerv2_routing(scores, top_k, jitter_eps, training):
119
+ assert top_k in [1, 2], "only top-1/2 gating has been tested!"
120
+
121
+ original_gates = torch.softmax(scores, dim=-1)
122
+ ################ first expert ################
123
+
124
+ with torch.no_grad():
125
+ # compute mask for sparsity
126
+ mask_logits_threshold, max_ind = scores.max(dim=-1, keepdim=True)
127
+ factor = scores.abs().clamp(min=mask_logits_threshold)
128
+ mask_logits_threshold = (
129
+ (mask_logits_threshold - scores) / factor
130
+ ) > (2 * jitter_eps)
131
+
132
+ # apply mask
133
+ masked_gates = scores.masked_fill(mask_logits_threshold, float('-inf'))
134
+ if training:
135
+ selected_experts = (
136
+ masked_gates - torch.empty_like(masked_gates, memory_format=torch.legacy_contiguous_format).exponential_().log()
137
+ ).max(dim=-1)[1].unsqueeze(-1) # gumbel sampling, more robust than than the multinomial method
138
+ else:
139
+ selected_experts = max_ind
140
+
141
+ # compute scores for gradients
142
+ masked_gates = torch.softmax(masked_gates, dim=-1)
143
+
144
+ # compute midpoint mask
145
+ max_scores, max_ind = masked_gates.max(dim=-1, keepdim=True)
146
+ mask_for_one = torch.logical_or(
147
+ selected_experts == max_ind,
148
+ torch.rand_like(max_scores) > 0.75 # Heun's third-order method: f(x) - f(0) = .25 f'(x) + .75 f'(x/3.)
149
+ )
150
+ # 1 -> 1.0 & 0 -> 1./3: lambda x: (x + 0.5) / 1.5
151
+ mask_for_one = torch.add(0.3333, mask_for_one, alpha=0.6667).type_as(masked_gates)
152
+
153
+ multiplier_o = masked_gates.gather(dim=-1, index=selected_experts)
154
+ multiplier = v2core.apply(
155
+ scores,
156
+ multiplier_o,
157
+ selected_experts,
158
+ masked_gates,
159
+ mask_for_one,
160
+ )
161
+
162
+ ################ second expert ################
163
+ if top_k > 1:
164
+ # masked out first expert
165
+ masked_scores = torch.scatter(
166
+ scores,
167
+ -1,
168
+ selected_experts,
169
+ float('-inf'),
170
+ )
171
+ with torch.no_grad():
172
+ # compute mask for sparsity
173
+ mask_logits_threshold, max_ind = masked_scores.max(dim=-1, keepdim=True)
174
+ factor = scores.abs().clamp(min=mask_logits_threshold)
175
+ mask_logits_threshold = (
176
+ (mask_logits_threshold - scores) / factor
177
+ ) > (2 * jitter_eps)
178
+
179
+ # apply mask
180
+ masked_gates_top2 = masked_scores.masked_fill(mask_logits_threshold, float('-inf'))
181
+ if training:
182
+ selected_experts_top2 = (
183
+ masked_gates_top2 - torch.empty_like(masked_gates_top2, memory_format=torch.legacy_contiguous_format).exponential_().log()
184
+ ).max(dim=-1)[1].unsqueeze(-1) # gumbel sampling, more robust than than the multinomial method
185
+ else:
186
+ selected_experts_top2 = max_ind
187
+ # compute scores for gradients
188
+ masked_gates_top2 = torch.softmax(masked_gates_top2, dim=-1)
189
+
190
+ # compute midpoint mask
191
+ max_scores, max_ind = masked_gates_top2.max(dim=-1, keepdim=True)
192
+ mask_for_one_top2 = torch.logical_or(
193
+ selected_experts_top2 == max_ind,
194
+ torch.rand_like(max_scores).uniform_() > 0.75 # Heun's third-order method: f(x) - f(0) = .25 f'(x) + .75 f'(x/3.)
195
+ )
196
+ # 1 -> 1.0 & 0 -> 1./3: lambda x: (x + 0.5) / 1.5
197
+ mask_for_one_top2 = torch.add(0.3333, mask_for_one_top2, alpha=0.6667).type_as(masked_gates_top2)
198
+
199
+ multiplier_top2_o = masked_gates_top2.gather(dim=-1, index=selected_experts_top2)
200
+ multiplier_top2 = v2core.apply(
201
+ scores,
202
+ multiplier_top2_o,
203
+ selected_experts_top2,
204
+ masked_gates_top2,
205
+ mask_for_one_top2,
206
+ )
207
+
208
+ multiplier = torch.concat((multiplier, multiplier_top2), dim=-1)
209
+ selected_experts = torch.concat((selected_experts, selected_experts_top2), dim=-1)
210
+
211
+ return (
212
+ multiplier,
213
+ original_gates,
214
+ selected_experts,
215
+ )
216
+
217
+ class SparseMixer(nn.Module):
218
+ def __init__(self, num_experts, embed_dim, jitter_eps=0.1):
219
+ super(SparseMixer, self).__init__()
220
+ self.num_experts = num_experts
221
+ self.jitter_eps = jitter_eps
222
+
223
+ def forward(self, logits):
224
+ multiplier, original_gates, sample = sparsemixerv2_routing(logits, 1, self.jitter_eps, self.training)
225
+ return sample, multiplier
226
+
227
+ class DDModelOutputWithPast(BaseModelOutputWithPast):
228
+ def __init__(self, last_hidden_state, past_key_values=None, hidden_states=None, attentions=None, router_weights=None, router_masks=None):
229
+ super().__init__(last_hidden_state=last_hidden_state, past_key_values=past_key_values, hidden_states=hidden_states, attentions=attentions)
230
+ self.router_weights = router_weights
231
+ self.router_masks = router_masks
232
+
233
+ class DDLlamaRMSNorm(nn.Module):
234
+ def __init__(self, hidden_size, eps=1e-6):
235
+ super().__init__()
236
+ self.weight = nn.Parameter(torch.ones(hidden_size))
237
+ self.variance_epsilon = eps
238
+
239
+ def forward(self, hidden_states):
240
+ input_dtype = hidden_states.dtype
241
+ hidden_states = hidden_states.to(torch.float32)
242
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
243
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
244
+ return self.weight * hidden_states.to(input_dtype)
245
+
246
+ def extra_repr(self):
247
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
248
+
249
+
250
+ ALL_LAYERNORM_LAYERS.append(DDLlamaRMSNorm)
251
+
252
+
253
+ class DDLlamaRotaryEmbedding(nn.Module):
254
+ def __init__(
255
+ self,
256
+ dim=None,
257
+ max_position_embeddings=2048,
258
+ base=10000,
259
+ device=None,
260
+ scaling_factor=1.0,
261
+ rope_type="default",
262
+ config: Optional[DDLlamaConfig] = None,
263
+ ):
264
+ super().__init__()
265
+ # TODO (joao): remove the `if` below, only used for BC
266
+ self.rope_kwargs = {}
267
+ if config is None:
268
+ logger.warning_once(
269
+ "`MoDLlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
270
+ "`config` argument. All other arguments will be removed in v4.46"
271
+ )
272
+ self.rope_kwargs = {
273
+ "rope_type": rope_type,
274
+ "factor": scaling_factor,
275
+ "dim": dim,
276
+ "base": base,
277
+ "max_position_embeddings": max_position_embeddings,
278
+ }
279
+ self.rope_type = rope_type
280
+ self.max_seq_len_cached = max_position_embeddings
281
+ self.original_max_seq_len = max_position_embeddings
282
+ else:
283
+ # BC: "rope_type" was originally "type"
284
+ if config.rope_scaling is not None:
285
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
286
+ else:
287
+ self.rope_type = "default"
288
+ self.max_seq_len_cached = config.max_position_embeddings
289
+ self.original_max_seq_len = config.max_position_embeddings
290
+
291
+ self.config = config
292
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
293
+
294
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
295
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
296
+ self.original_inv_freq = self.inv_freq
297
+
298
+ def _dynamic_frequency_update(self, position_ids, device):
299
+ """
300
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
301
+ 1 - growing beyond the cached sequence length (allow scaling)
302
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
303
+ """
304
+ seq_len = torch.max(position_ids) + 1
305
+ if seq_len > self.max_seq_len_cached: # growth
306
+ inv_freq, self.attention_scaling = self.rope_init_fn(
307
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
308
+ )
309
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
310
+ self.max_seq_len_cached = seq_len
311
+
312
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
313
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
314
+ self.max_seq_len_cached = self.original_max_seq_len
315
+
316
+ @torch.no_grad()
317
+ def forward(self, x, position_ids):
318
+ if "dynamic" in self.rope_type:
319
+ self._dynamic_frequency_update(position_ids, device=x.device)
320
+
321
+ # Core RoPE block
322
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
323
+ position_ids_expanded = position_ids[:, None, :].float()
324
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
325
+ device_type = x.device.type
326
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
327
+ with torch.autocast(device_type=device_type, enabled=False):
328
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
329
+ emb = torch.cat((freqs, freqs), dim=-1)
330
+ cos = emb.cos()
331
+ sin = emb.sin()
332
+
333
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
334
+ cos = cos * self.attention_scaling
335
+ sin = sin * self.attention_scaling
336
+
337
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
338
+
339
+
340
+ def rotate_half(x):
341
+ """Rotates half the hidden dims of the input."""
342
+ x1 = x[..., : x.shape[-1] // 2]
343
+ x2 = x[..., x.shape[-1] // 2 :]
344
+ return torch.cat((-x2, x1), dim=-1)
345
+
346
+
347
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
348
+ cos = cos.unsqueeze(unsqueeze_dim)
349
+ sin = sin.unsqueeze(unsqueeze_dim)
350
+ q_embed = (q * cos) + (rotate_half(q) * sin)
351
+ k_embed = (k * cos) + (rotate_half(k) * sin)
352
+ return q_embed, k_embed
353
+
354
+
355
+ class DDLlamaMLP(nn.Module):
356
+ def __init__(self, config):
357
+ super().__init__()
358
+ self.config = config
359
+ self.hidden_size = config.hidden_size
360
+ self.intermediate_size = config.intermediate_size
361
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
362
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
363
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
364
+ self.act_fn = ACT2FN[config.hidden_act]
365
+
366
+ def forward(self, x):
367
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
368
+ return down_proj
369
+
370
+
371
+ class DDLlamaRouter(nn.Module):
372
+ def __init__(self, config):
373
+ super().__init__()
374
+ self.config = config
375
+ self.reduction_factor = config.router_reduction_factor
376
+ self.router_enc = nn.Linear(config.hidden_size, config.hidden_size // self.reduction_factor, bias=config.mlp_bias)
377
+ self.router_norm = DDLlamaRMSNorm(config.hidden_size // self.reduction_factor, eps=config.rms_norm_eps)
378
+ self.router_act = nn.Tanh()
379
+ self.router_dec = nn.Linear(config.hidden_size // self.reduction_factor, config.hidden_size, bias=config.mlp_bias)
380
+ self.router_head = nn.Linear(config.hidden_size, 1, bias=config.mlp_bias)
381
+
382
+ def forward(self, hidden_states):
383
+ router_logits = self.router_head(self.router_dec(self.router_act(self.router_norm(self.router_enc(hidden_states)))))
384
+ return router_logits
385
+
386
+
387
+ class DDLlamaProj(nn.Module):
388
+ def __init__(self, config):
389
+ super().__init__()
390
+ self.config = config
391
+ self.hidden_size = config.hidden_size
392
+ self.intermediate_size = config.intermediate_size
393
+ self.reduction_factor = config.proj_reduction_factor
394
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size // self.reduction_factor, bias=config.mlp_bias)
395
+ self.down_proj = nn.Linear(self.hidden_size, self.intermediate_size // self.reduction_factor, bias=config.mlp_bias)
396
+ self.up_proj = nn.Linear(self.intermediate_size // self.reduction_factor, self.hidden_size, bias=config.mlp_bias)
397
+ self.act_fn = ACT2FN[config.hidden_act]
398
+
399
+ def forward(self, x):
400
+ up_proj = self.up_proj(self.act_fn(self.gate_proj(x)) * self.down_proj(x))
401
+ return up_proj
402
+
403
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
404
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
405
+ if n_rep == 1:
406
+ return hidden_states
407
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
408
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
409
+
410
+
411
+ class DDLlamaAttention(nn.Module):
412
+ def __init__(self, config: DDLlamaConfig, layer_idx: Optional[int] = None):
413
+ super().__init__()
414
+ self.config = config
415
+ self.layer_idx = layer_idx
416
+ if layer_idx is None:
417
+ logger.warning_once(
418
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
419
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
420
+ "when creating this class."
421
+ )
422
+
423
+ self.attention_dropout = config.attention_dropout
424
+ self.hidden_size = config.hidden_size
425
+ self.num_heads = config.num_attention_heads
426
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
427
+ self.num_key_value_heads = config.num_key_value_heads
428
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
429
+ self.max_position_embeddings = config.max_position_embeddings
430
+ self.rope_theta = config.rope_theta
431
+ self.is_causal = True
432
+
433
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
434
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
435
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
436
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
437
+
438
+ def forward(
439
+ self,
440
+ hidden_states: torch.Tensor,
441
+ attention_mask: Optional[torch.Tensor] = None,
442
+ position_ids: Optional[torch.LongTensor] = None,
443
+ past_key_value: Optional[Cache] = None,
444
+ output_attentions: bool = False,
445
+ use_cache: bool = False,
446
+ cache_position: Optional[torch.LongTensor] = None,
447
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
448
+ **kwargs,
449
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
450
+ bsz, q_len, _ = hidden_states.size()
451
+
452
+ query_states = self.q_proj(hidden_states)
453
+ key_states = self.k_proj(hidden_states)
454
+ value_states = self.v_proj(hidden_states)
455
+
456
+ # use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
457
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
458
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
459
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
460
+
461
+ cos, sin = position_embeddings
462
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
463
+
464
+ if past_key_value is not None:
465
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
466
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
467
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
468
+
469
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
470
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
471
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
472
+
473
+ if attention_mask is not None: # no matter the length, we just slice it
474
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
475
+ attn_weights = attn_weights + causal_mask
476
+
477
+ # upcast attention to fp32
478
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
479
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
480
+ attn_output = torch.matmul(attn_weights, value_states)
481
+
482
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
483
+ raise ValueError(
484
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
485
+ f" {attn_output.size()}"
486
+ )
487
+
488
+ attn_output = attn_output.transpose(1, 2).contiguous()
489
+
490
+ attn_output = attn_output.reshape(bsz, q_len, -1)
491
+
492
+ attn_output = self.o_proj(attn_output)
493
+
494
+ if not output_attentions:
495
+ attn_weights = None
496
+
497
+ return attn_output, attn_weights, past_key_value
498
+
499
+
500
+ class DDLlamaFlashAttention2(DDLlamaAttention):
501
+ def __init__(self, *args, **kwargs):
502
+ super().__init__(*args, **kwargs)
503
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
504
+
505
+ def forward(
506
+ self,
507
+ hidden_states: torch.Tensor,
508
+ attention_mask: Optional[torch.LongTensor] = None,
509
+ position_ids: Optional[torch.LongTensor] = None,
510
+ past_key_value: Optional[Cache] = None,
511
+ output_attentions: bool = False,
512
+ use_cache: bool = False,
513
+ cache_position: Optional[torch.LongTensor] = None,
514
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
515
+ **kwargs: Unpack[FlashAttentionKwargs],
516
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
517
+ if isinstance(past_key_value, StaticCache):
518
+ raise ValueError(
519
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
520
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
521
+ )
522
+
523
+ output_attentions = False
524
+
525
+ bsz, q_len, _ = hidden_states.size()
526
+
527
+ query_states = self.q_proj(hidden_states)
528
+ key_states = self.k_proj(hidden_states)
529
+ value_states = self.v_proj(hidden_states)
530
+
531
+ # Flash attention requires the input to have the shape
532
+ # batch_size x seq_length x head_dim x hidden_dim
533
+ # therefore we just need to keep the original shape
534
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
535
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
536
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
537
+
538
+ cos, sin = position_embeddings
539
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
540
+
541
+ if past_key_value is not None:
542
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
543
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
544
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
545
+
546
+ # 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
547
+ # to be able to avoid many of these transpose/reshape/view.
548
+ query_states = query_states.transpose(1, 2)
549
+ key_states = key_states.transpose(1, 2)
550
+ value_states = value_states.transpose(1, 2)
551
+
552
+ dropout_rate = self.attention_dropout if self.training else 0.0
553
+
554
+ input_dtype = query_states.dtype
555
+ if input_dtype == torch.float32:
556
+ if torch.is_autocast_enabled():
557
+ target_dtype = torch.get_autocast_gpu_dtype()
558
+ # Handle the case where the model is quantized
559
+ elif hasattr(self.config, "_pre_quantization_dtype"):
560
+ target_dtype = self.config._pre_quantization_dtype
561
+ else:
562
+ target_dtype = self.q_proj.weight.dtype
563
+
564
+ logger.warning_once(
565
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
566
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
567
+ f" {target_dtype}."
568
+ )
569
+
570
+ query_states = query_states.to(target_dtype)
571
+ key_states = key_states.to(target_dtype)
572
+ value_states = value_states.to(target_dtype)
573
+
574
+ attn_output = _flash_attention_forward(
575
+ query_states,
576
+ key_states,
577
+ value_states,
578
+ attention_mask,
579
+ q_len,
580
+ position_ids=position_ids,
581
+ dropout=dropout_rate,
582
+ sliding_window=getattr(self, "sliding_window", None),
583
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
584
+ is_causal=self.is_causal,
585
+ **kwargs,
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
+ class DDLlamaSdpaAttention(DDLlamaAttention):
598
+ def forward(
599
+ self,
600
+ hidden_states: torch.Tensor,
601
+ attention_mask: Optional[torch.Tensor] = None,
602
+ position_ids: Optional[torch.LongTensor] = None,
603
+ past_key_value: Optional[Cache] = None,
604
+ output_attentions: bool = False,
605
+ use_cache: bool = False,
606
+ cache_position: Optional[torch.LongTensor] = None,
607
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
608
+ **kwargs,
609
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
610
+ if output_attentions:
611
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
612
+ logger.warning_once(
613
+ "DDLlamaModel is using DDLlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
614
+ '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.'
615
+ )
616
+ return super().forward(
617
+ hidden_states=hidden_states,
618
+ attention_mask=attention_mask,
619
+ position_ids=position_ids,
620
+ past_key_value=past_key_value,
621
+ output_attentions=output_attentions,
622
+ use_cache=use_cache,
623
+ cache_position=cache_position,
624
+ position_embeddings=position_embeddings,
625
+ )
626
+
627
+ bsz, q_len, _ = hidden_states.size()
628
+
629
+ query_states = self.q_proj(hidden_states)
630
+ key_states = self.k_proj(hidden_states)
631
+ value_states = self.v_proj(hidden_states)
632
+
633
+ # use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
634
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
635
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
636
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
637
+
638
+ cos, sin = position_embeddings
639
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
640
+
641
+ if past_key_value is not None:
642
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
643
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
644
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
645
+
646
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
647
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
648
+
649
+ causal_mask = attention_mask
650
+ if attention_mask is not None:
651
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
652
+
653
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
654
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
655
+ if query_states.device.type == "cuda" and causal_mask is not None:
656
+ query_states = query_states.contiguous()
657
+ key_states = key_states.contiguous()
658
+ value_states = value_states.contiguous()
659
+
660
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
661
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
662
+ is_causal = True if causal_mask is None and q_len > 1 else False
663
+
664
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
665
+ query_states,
666
+ key_states,
667
+ value_states,
668
+ attn_mask=causal_mask,
669
+ dropout_p=self.attention_dropout if self.training else 0.0,
670
+ is_causal=is_causal,
671
+ )
672
+
673
+ attn_output = attn_output.transpose(1, 2).contiguous()
674
+ attn_output = attn_output.view(bsz, q_len, -1)
675
+
676
+ attn_output = self.o_proj(attn_output)
677
+
678
+ return attn_output, None, past_key_value
679
+
680
+
681
+ DDLLAMA_ATTENTION_CLASSES = {
682
+ "eager": DDLlamaAttention,
683
+ "flash_attention_2": DDLlamaFlashAttention2,
684
+ "sdpa": DDLlamaSdpaAttention,
685
+ }
686
+
687
+
688
+ class DDLlamaDecoderLayer(nn.Module):
689
+ def __init__(self, config: DDLlamaConfig, layer_idx: int):
690
+ super().__init__()
691
+ self.hidden_size = config.hidden_size
692
+ self.self_attn = DDLLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
693
+ self.mlp = DDLlamaMLP(config)
694
+ self.input_layernorm = DDLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
695
+ self.post_attention_layernorm = DDLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
696
+
697
+ self.routing = layer_idx in config.router_layers
698
+ if self.routing:
699
+ self.router = DDLlamaRouter(config)
700
+ self.mixer = SparseMixer(2, config.hidden_size, 0.1)
701
+ self.router_proj = DDLlamaProj(config)
702
+
703
+ def forward(
704
+ self,
705
+ hidden_states: torch.Tensor,
706
+ attention_mask: Optional[torch.Tensor] = None,
707
+ position_ids: Optional[torch.LongTensor] = None,
708
+ past_key_value: Optional[Cache] = None,
709
+ output_attentions: Optional[bool] = False,
710
+ use_cache: Optional[bool] = False,
711
+ cache_position: Optional[torch.LongTensor] = None,
712
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
713
+ **kwargs,
714
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
715
+ """
716
+ Args:
717
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
718
+ attention_mask (`torch.FloatTensor`, *optional*):
719
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
720
+ query_sequence_length, key_sequence_length)` if default attention is used.
721
+ output_attentions (`bool`, *optional*):
722
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
723
+ returned tensors for more detail.
724
+ use_cache (`bool`, *optional*):
725
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
726
+ (see `past_key_values`).
727
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
728
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
729
+ Indices depicting the position of the input sequence tokens in the sequence
730
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
731
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
732
+ with `head_dim` being the embedding dimension of each attention head.
733
+ kwargs (`dict`, *optional*):
734
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
735
+ into the model
736
+ """
737
+ bsz, seq_len, hidden_size = hidden_states.shape
738
+ residual = hidden_states
739
+ hidden_states = self.input_layernorm(hidden_states)
740
+
741
+ # Our implementation is based on masking the hidden_states skip this layer
742
+ # This approach is faster than fetching the indices of the hidden_states for conditional computation
743
+ # Further improvement could be done by implmenting a hardware-friendly conditional computation
744
+ if self.routing:
745
+ router_logits = self.router(hidden_states.view(-1, hidden_size))
746
+ router_probs = torch.sigmoid(router_logits).squeeze(dim=-1) # 计算 sigmoid
747
+ router_logits = torch.stack([1 - router_probs, router_probs], dim=-1) # 堆叠到最后一维
748
+ router_mask, router_weights = self.mixer(router_logits)
749
+ router_mask = router_mask.view(bsz, seq_len, 1)
750
+ router_weights = router_weights.view(bsz, seq_len, 1)
751
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
752
+ hidden_states=hidden_states,
753
+ attention_mask=attention_mask,
754
+ position_ids=position_ids,
755
+ past_key_value=past_key_value,
756
+ output_attentions=output_attentions,
757
+ use_cache=use_cache,
758
+ cache_position=cache_position,
759
+ position_embeddings=position_embeddings,
760
+ **kwargs,
761
+ )
762
+ if self.routing:
763
+ # masking the hidden_states skip this layer
764
+ hidden_states = residual + hidden_states * router_mask
765
+ else:
766
+ hidden_states = residual + hidden_states
767
+
768
+ # Fully Connected
769
+ residual = hidden_states
770
+ hidden_states = self.post_attention_layernorm(hidden_states)
771
+ if self.routing:
772
+ # masking the hidden_states skip this layer
773
+ preserved_hidden_states = self.mlp(hidden_states) * router_mask * router_weights
774
+ skipped_hidden_states = self.router_proj(hidden_states) * (1-router_mask) * (1-router_weights)
775
+ hidden_states = residual + preserved_hidden_states + skipped_hidden_states
776
+ else:
777
+ hidden_states = self.mlp(hidden_states)
778
+ hidden_states = residual + hidden_states
779
+
780
+ outputs = (hidden_states,)
781
+
782
+ if self.routing:
783
+ outputs += (router_probs.reshape(bsz, seq_len),)
784
+ outputs += (router_mask.reshape(bsz, seq_len),)
785
+
786
+ if output_attentions:
787
+ outputs += (self_attn_weights,)
788
+
789
+ if use_cache:
790
+ outputs += (present_key_value,)
791
+
792
+ return outputs
793
+
794
+
795
+ class DDLlamaPreTrainedModel(PreTrainedModel):
796
+ config_class = DDLlamaConfig
797
+ base_model_prefix = "model"
798
+ supports_gradient_checkpointing = True
799
+ _no_split_modules = ["DDLlamaDecoderLayer"]
800
+ _skip_keys_device_placement = ["past_key_values"]
801
+ _supports_flash_attn_2 = True
802
+ _supports_sdpa = True
803
+ _supports_cache_class = True
804
+ _supports_quantized_cache = True
805
+ _supports_static_cache = True
806
+
807
+ def _init_weights(self, module):
808
+ std = self.config.initializer_range
809
+ if isinstance(module, nn.Linear):
810
+ module.weight.data.normal_(mean=0.0, std=std)
811
+ if module.bias is not None:
812
+ module.bias.data.zero_()
813
+ elif isinstance(module, nn.Embedding):
814
+ module.weight.data.normal_(mean=0.0, std=std)
815
+ if module.padding_idx is not None:
816
+ module.weight.data[module.padding_idx].zero_()
817
+
818
+ class DDLlamaModel(DDLlamaPreTrainedModel):
819
+ config_class = DDLlamaConfig
820
+ def __init__(self, config: DDLlamaConfig):
821
+ super().__init__(config)
822
+ self.padding_idx = config.pad_token_id
823
+ self.vocab_size = config.vocab_size
824
+
825
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
826
+ self.layers = nn.ModuleList(
827
+ [DDLlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
828
+ )
829
+ self.norm = DDLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
830
+ self.rotary_emb = DDLlamaRotaryEmbedding(config=config)
831
+
832
+ self.gradient_checkpointing = False
833
+ if getattr(config, "pretraining_tp", 1) != 1:
834
+ logger.warn("`pretraining_tp` is deprecated, please use `model.tensor_parallel` instead.")
835
+
836
+ # Initialize weights and apply final processing
837
+ self.post_init()
838
+
839
+ def get_input_embeddings(self):
840
+ return self.embed_tokens
841
+
842
+ def set_input_embeddings(self, value):
843
+ self.embed_tokens = value
844
+
845
+ def forward(
846
+ self,
847
+ input_ids: torch.LongTensor = None,
848
+ attention_mask: Optional[torch.Tensor] = None,
849
+ position_ids: Optional[torch.LongTensor] = None,
850
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
851
+ inputs_embeds: Optional[torch.FloatTensor] = None,
852
+ use_cache: Optional[bool] = None,
853
+ output_attentions: Optional[bool] = None,
854
+ output_hidden_states: Optional[bool] = None,
855
+ return_dict: Optional[bool] = None,
856
+ cache_position: Optional[torch.LongTensor] = None,
857
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
858
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
859
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
860
+ output_hidden_states = (
861
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
862
+ )
863
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
864
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
865
+
866
+ if (input_ids is None) ^ (inputs_embeds is not None):
867
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
868
+
869
+ if self.gradient_checkpointing and self.training and use_cache:
870
+ logger.warning_once(
871
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
872
+ )
873
+ use_cache = False
874
+
875
+ if inputs_embeds is None:
876
+ inputs_embeds = self.embed_tokens(input_ids)
877
+
878
+ # kept for BC (non `Cache` `past_key_values` inputs)
879
+ return_legacy_cache = False
880
+ if use_cache and not isinstance(past_key_values, Cache):
881
+ return_legacy_cache = True
882
+ if past_key_values is None:
883
+ past_key_values = DynamicCache()
884
+ else:
885
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
886
+ logger.warning_once(
887
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
888
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
889
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
890
+ )
891
+
892
+ if cache_position is None:
893
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
894
+ cache_position = torch.arange(
895
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
896
+ )
897
+ if position_ids is None:
898
+ position_ids = cache_position.unsqueeze(0)
899
+
900
+ causal_mask = self._update_causal_mask(
901
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
902
+ )
903
+ hidden_states = inputs_embeds
904
+
905
+ # create position embeddings to be shared across the decoder layers
906
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
907
+
908
+ # decoder layers
909
+ all_hidden_states = () if output_hidden_states else None
910
+ all_self_attns = () if output_attentions else None
911
+ all_router_weights = ()
912
+ all_router_masks = ()
913
+ next_decoder_cache = None
914
+
915
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
916
+ if output_hidden_states:
917
+ all_hidden_states += (hidden_states,)
918
+
919
+ if self.gradient_checkpointing and self.training:
920
+ layer_outputs = self._gradient_checkpointing_func(
921
+ decoder_layer.__call__,
922
+ hidden_states,
923
+ causal_mask,
924
+ position_ids,
925
+ past_key_values,
926
+ output_attentions,
927
+ use_cache,
928
+ cache_position,
929
+ position_embeddings,
930
+ )
931
+ else:
932
+ layer_outputs = decoder_layer(
933
+ hidden_states,
934
+ attention_mask=causal_mask,
935
+ position_ids=position_ids,
936
+ past_key_value=past_key_values,
937
+ output_attentions=output_attentions,
938
+ use_cache=use_cache,
939
+ cache_position=cache_position,
940
+ position_embeddings=position_embeddings,
941
+ **flash_attn_kwargs,
942
+ )
943
+
944
+ hidden_states = layer_outputs[0]
945
+
946
+ output_idx = 1
947
+ if decoder_layer.routing:
948
+ all_router_weights += (layer_outputs[output_idx],)
949
+ output_idx += 1
950
+ all_router_masks += (layer_outputs[output_idx],)
951
+ output_idx += 1
952
+
953
+ if output_attentions:
954
+ all_self_attns += (layer_outputs[output_idx],)
955
+ output_idx += 1
956
+
957
+ if use_cache:
958
+ next_decoder_cache = layer_outputs[output_idx]
959
+
960
+ hidden_states = self.norm(hidden_states)
961
+
962
+ # add hidden states from the last decoder layer
963
+ if output_hidden_states:
964
+ all_hidden_states += (hidden_states,)
965
+
966
+ next_cache = next_decoder_cache if use_cache else None
967
+ if return_legacy_cache:
968
+ next_cache = next_cache.to_legacy_cache()
969
+
970
+ if not return_dict:
971
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
972
+ return DDModelOutputWithPast(
973
+ last_hidden_state=hidden_states,
974
+ past_key_values=next_cache,
975
+ hidden_states=all_hidden_states,
976
+ attentions=all_self_attns,
977
+ router_weights=all_router_weights,
978
+ router_masks=all_router_masks,
979
+ )
980
+
981
+ def _update_causal_mask(
982
+ self,
983
+ attention_mask: torch.Tensor,
984
+ input_tensor: torch.Tensor,
985
+ cache_position: torch.Tensor,
986
+ past_key_values: Cache,
987
+ output_attentions: bool,
988
+ ):
989
+ if self.config._attn_implementation == "flash_attention_2":
990
+ if attention_mask is not None and 0.0 in attention_mask:
991
+ return attention_mask
992
+ return None
993
+
994
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
995
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
996
+ # to infer the attention mask.
997
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
998
+ using_static_cache = isinstance(past_key_values, StaticCache)
999
+
1000
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1001
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1002
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1003
+ attention_mask,
1004
+ inputs_embeds=input_tensor,
1005
+ past_key_values_length=past_seen_tokens,
1006
+ is_training=self.training,
1007
+ ):
1008
+ return None
1009
+
1010
+ dtype, device = input_tensor.dtype, input_tensor.device
1011
+ sequence_length = input_tensor.shape[1]
1012
+ if using_static_cache:
1013
+ target_length = past_key_values.get_max_cache_shape()
1014
+ else:
1015
+ target_length = (
1016
+ attention_mask.shape[-1]
1017
+ if isinstance(attention_mask, torch.Tensor)
1018
+ else past_seen_tokens + sequence_length + 1
1019
+ )
1020
+
1021
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1022
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1023
+ attention_mask,
1024
+ sequence_length=sequence_length,
1025
+ target_length=target_length,
1026
+ dtype=dtype,
1027
+ device=device,
1028
+ cache_position=cache_position,
1029
+ batch_size=input_tensor.shape[0],
1030
+ )
1031
+
1032
+ if (
1033
+ self.config._attn_implementation == "sdpa"
1034
+ and attention_mask is not None
1035
+ and attention_mask.device.type == "cuda"
1036
+ and not output_attentions
1037
+ ):
1038
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1039
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1040
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1041
+ min_dtype = torch.finfo(dtype).min
1042
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1043
+
1044
+ return causal_mask
1045
+
1046
+ @staticmethod
1047
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1048
+ attention_mask: torch.Tensor,
1049
+ sequence_length: int,
1050
+ target_length: int,
1051
+ dtype: torch.dtype,
1052
+ device: torch.device,
1053
+ cache_position: torch.Tensor,
1054
+ batch_size: int,
1055
+ **kwargs,
1056
+ ):
1057
+ """
1058
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1059
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1060
+
1061
+ Args:
1062
+ attention_mask (`torch.Tensor`):
1063
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1064
+ `(batch_size, 1, query_length, key_value_length)`.
1065
+ sequence_length (`int`):
1066
+ The sequence length being processed.
1067
+ target_length (`int`):
1068
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1069
+ to account for the 0 padding, the part of the cache that is not filled yet.
1070
+ dtype (`torch.dtype`):
1071
+ The dtype to use for the 4D attention mask.
1072
+ device (`torch.device`):
1073
+ The device to plcae the 4D attention mask on.
1074
+ cache_position (`torch.Tensor`):
1075
+ Indices depicting the position of the input sequence tokens in the sequence.
1076
+ batch_size (`torch.Tensor`):
1077
+ Batch size.
1078
+ """
1079
+ if attention_mask is not None and attention_mask.dim() == 4:
1080
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1081
+ causal_mask = attention_mask
1082
+ else:
1083
+ min_dtype = torch.finfo(dtype).min
1084
+ causal_mask = torch.full(
1085
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1086
+ )
1087
+ if sequence_length != 1:
1088
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1089
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1090
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1091
+ if attention_mask is not None:
1092
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1093
+ mask_length = attention_mask.shape[-1]
1094
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1095
+ padding_mask = padding_mask == 0
1096
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1097
+ padding_mask, min_dtype
1098
+ )
1099
+
1100
+ return causal_mask
1101
+
1102
+
1103
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
1104
+
1105
+
1106
+ class DDLlamaForCausalLM(DDLlamaPreTrainedModel, GenerationMixin):
1107
+ config_class = DDLlamaConfig
1108
+ _tied_weights_keys = ["lm_head.weight"]
1109
+ _tp_plan = {"lm_head": "colwise_rep"}
1110
+
1111
+ def __init__(self, config):
1112
+ super().__init__(config)
1113
+ self.model = DDLlamaModel(config)
1114
+ self.vocab_size = config.vocab_size
1115
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1116
+ self.post_init()
1117
+
1118
+ def get_input_embeddings(self):
1119
+ return self.model.embed_tokens
1120
+
1121
+ def set_input_embeddings(self, value):
1122
+ self.model.embed_tokens = value
1123
+
1124
+ def get_output_embeddings(self):
1125
+ return self.lm_head
1126
+
1127
+ def set_output_embeddings(self, new_embeddings):
1128
+ self.lm_head = new_embeddings
1129
+
1130
+ def set_decoder(self, decoder):
1131
+ self.model = decoder
1132
+
1133
+ def get_decoder(self):
1134
+ return self.model
1135
+
1136
+ def forward(
1137
+ self,
1138
+ input_ids: torch.LongTensor = None,
1139
+ attention_mask: Optional[torch.Tensor] = None,
1140
+ position_ids: Optional[torch.LongTensor] = None,
1141
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1142
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1143
+ labels: Optional[torch.LongTensor] = None,
1144
+ use_cache: Optional[bool] = None,
1145
+ output_attentions: Optional[bool] = None,
1146
+ output_hidden_states: Optional[bool] = None,
1147
+ return_dict: Optional[bool] = None,
1148
+ cache_position: Optional[torch.LongTensor] = None,
1149
+ num_logits_to_keep: int = 0,
1150
+ **kwargs: Unpack[KwargsForCausalLM],
1151
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1152
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1153
+ output_hidden_states = (
1154
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1155
+ )
1156
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1157
+
1158
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1159
+ outputs = self.model(
1160
+ input_ids=input_ids,
1161
+ attention_mask=attention_mask,
1162
+ position_ids=position_ids,
1163
+ past_key_values=past_key_values,
1164
+ inputs_embeds=inputs_embeds,
1165
+ use_cache=use_cache,
1166
+ output_attentions=output_attentions,
1167
+ output_hidden_states=output_hidden_states,
1168
+ return_dict=return_dict,
1169
+ cache_position=cache_position,
1170
+ **kwargs,
1171
+ )
1172
+
1173
+ hidden_states = outputs[0]
1174
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1175
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1176
+
1177
+ loss = None
1178
+ if labels is not None:
1179
+ logits = logits.float()
1180
+ # Shift so that tokens < n predict n
1181
+ shift_logits = logits[..., :-1, :].contiguous()
1182
+ shift_labels = labels[..., 1:].contiguous()
1183
+ # Flatten the tokens
1184
+ loss_fct = CrossEntropyLoss(reduction='none')
1185
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1186
+ shift_labels = shift_labels.view(-1)
1187
+ # Enable model parallelism
1188
+ shift_labels = shift_labels.to(shift_logits.device)
1189
+ shift_loss = loss_fct(shift_logits, shift_labels)
1190
+ loss = torch.mean(shift_loss)
1191
+
1192
+ router_weights = outputs.router_weights
1193
+ router_masks = outputs.router_masks
1194
+ if len(router_weights) > 0:
1195
+ router_weights = [weight.to(hidden_states.device) for weight in router_weights]
1196
+ router_weights = torch.stack(router_weights, dim=-1).float()
1197
+
1198
+ router_masks = [mask.to(hidden_states.device) for mask in router_masks]
1199
+ router_masks = torch.stack(router_masks, dim=-1).float()
1200
+
1201
+ # print the number of layers used
1202
+ n_layers = torch.mean(torch.sum(router_masks, dim=2))
1203
+ print(16+int(n_layers.item()), end='')
1204
+
1205
+ if self.training and labels is not None:
1206
+ router_weights *= router_masks
1207
+ shift_router_weights = router_weights[:, :-1, :].contiguous()
1208
+ shift_router_weights = shift_router_weights.view(-1, shift_router_weights.shape[-1])
1209
+ router_penalty_loss = torch.sum(shift_router_weights, dim=1)
1210
+ router_penalty_loss = 1e-3 * torch.mean((router_penalty_loss) ** 2)
1211
+ loss += router_penalty_loss
1212
+ # normalize the loss by your gradient accumulation steps
1213
+ loss /= 4
1214
+
1215
+ if not return_dict:
1216
+ output = (logits,) + outputs[1:]
1217
+ return (loss,) + output if loss is not None else output
1218
+
1219
+ return CausalLMOutputWithPast(
1220
+ loss=loss,
1221
+ logits=logits,
1222
+ past_key_values=outputs.past_key_values,
1223
+ hidden_states=outputs.hidden_states,
1224
+ attentions=outputs.attentions,
1225
+ )