modeling_deepseekv2.py
88.0 KB · 2142 lines · python Raw
1 # coding=utf-8
2 # Copyright 2023 DeepSeek-AI 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 """ PyTorch DeepSeek model and compatible with both DeepSeekV2 and DeepSeekV3"""
21 import math
22 import warnings
23 from typing import List, Optional, Tuple, Union
24 import numpy as np
25
26 import torch
27 import torch.nn.functional as F
28 import torch.utils.checkpoint
29 import torch.distributed as dist
30 from einops import repeat
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
36 from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
37 from transformers.models.llama.modeling_llama import (
38 LlamaAttention,
39 apply_rotary_pos_emb as _llama_apply_rotary_pos_emb,
40 repeat_kv as _llama_repeat_kv,
41 # LlamaFlashAttention2
42 )
43 from transformers.modeling_outputs import (
44 BaseModelOutputWithPast,
45 CausalLMOutputWithPast,
46 SequenceClassifierOutputWithPast,
47 )
48 from transformers.modeling_utils import PreTrainedModel
49 from transformers.pytorch_utils import (
50 ALL_LAYERNORM_LAYERS,
51 is_torch_greater_or_equal_than_1_13,
52 )
53 from transformers.utils import (
54 add_start_docstrings,
55 add_start_docstrings_to_model_forward,
56 is_flash_attn_2_available,
57 is_flash_attn_greater_or_equal_2_10,
58 logging,
59 replace_return_docstrings,
60 )
61 from transformers.utils.import_utils import is_torch_fx_available
62
63 from .configuration_deepseek_v2 import DeepseekV2Config
64
65 if is_flash_attn_2_available():
66 from flash_attn import flash_attn_func, flash_attn_varlen_func
67 from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
68
69 # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
70 # It means that the function will not be traced through and simply appear as a node in the graph.
71 if is_torch_fx_available():
72 if not is_torch_greater_or_equal_than_1_13:
73 import torch.fx
74
75 _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
76
77 logger = logging.get_logger(__name__)
78
79 _CONFIG_FOR_DOC = "DeepseekV2Config"
80
81
82 def _get_unpad_data(attention_mask):
83 seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
84 indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
85 max_seqlen_in_batch = seqlens_in_batch.max().item()
86 cu_seqlens = F.pad(
87 torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
88 )
89 return (
90 indices,
91 cu_seqlens,
92 max_seqlen_in_batch,
93 )
94
95
96 class DeepseekV2RMSNorm(nn.Module):
97 def __init__(self, hidden_size, eps=1e-6):
98 """
99 DeepseekV2RMSNorm is equivalent to T5LayerNorm
100 """
101 super().__init__()
102 self.weight = nn.Parameter(torch.ones(hidden_size))
103 self.variance_epsilon = eps
104
105 def forward(self, hidden_states):
106 input_dtype = hidden_states.dtype
107 hidden_states = hidden_states.to(torch.float32)
108 variance = hidden_states.pow(2).mean(-1, keepdim=True)
109 hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
110 return self.weight * hidden_states.to(input_dtype)
111
112
113 ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
114
115
116
117
118 class DeepseekV2RotaryEmbedding(nn.Module):
119 def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
120 super().__init__()
121
122 self.dim = dim
123 self.max_position_embeddings = max_position_embeddings
124 self.base = base
125 inv_freq = 1.0 / (
126 self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
127 )
128 self.register_buffer("inv_freq", inv_freq, persistent=False)
129
130 # Build here to make `torch.jit.trace` work.
131 self._set_cos_sin_cache(
132 seq_len=max_position_embeddings,
133 device=self.inv_freq.device,
134 dtype=torch.get_default_dtype(),
135 )
136 self.max_seq_len_cached = None
137
138 def _set_cos_sin_cache(self, seq_len, device, dtype):
139 self.max_seq_len_cached = seq_len
140 t = torch.arange(
141 self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
142 )
143
144 freqs = torch.outer(t, self.inv_freq.to(t.device))
145 # Different from paper, but it uses a different permutation in order to obtain the same calculation
146 emb = torch.cat((freqs, freqs), dim=-1)
147 self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
148 self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
149
150 def forward(self, x, seq_len=None):
151 # x: [bs, num_attention_heads, seq_len, head_size]
152 if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
153 self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
154
155 return (
156 self.cos_cached[:seq_len].to(dtype=x.dtype),
157 self.sin_cached[:seq_len].to(dtype=x.dtype),
158 )
159
160
161 # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
162 class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
163 """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
164
165 def __init__(
166 self,
167 dim,
168 max_position_embeddings=2048,
169 base=10000,
170 device=None,
171 scaling_factor=1.0,
172 ):
173 self.scaling_factor = scaling_factor
174 super().__init__(dim, max_position_embeddings, base, device)
175
176 def _set_cos_sin_cache(self, seq_len, device, dtype):
177 self.max_seq_len_cached = seq_len
178 t = torch.arange(
179 self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
180 )
181 t = t / self.scaling_factor
182
183 freqs = torch.outer(t, self.inv_freq)
184 # Different from paper, but it uses a different permutation in order to obtain the same calculation
185 emb = torch.cat((freqs, freqs), dim=-1)
186 self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
187 self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
188
189
190 # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
191 class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
192 """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
193
194 def __init__(
195 self,
196 dim,
197 max_position_embeddings=2048,
198 base=10000,
199 device=None,
200 scaling_factor=1.0,
201 ):
202 self.scaling_factor = scaling_factor
203 super().__init__(dim, max_position_embeddings, base, device)
204
205 def _set_cos_sin_cache(self, seq_len, device, dtype):
206 self.max_seq_len_cached = seq_len
207
208 if seq_len > self.max_position_embeddings:
209 base = self.base * (
210 (self.scaling_factor * seq_len / self.max_position_embeddings)
211 - (self.scaling_factor - 1)
212 ) ** (self.dim / (self.dim - 2))
213 inv_freq = 1.0 / (
214 base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
215 )
216 self.register_buffer("inv_freq", inv_freq, persistent=False)
217
218 t = torch.arange(
219 self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
220 )
221
222 freqs = torch.outer(t, self.inv_freq)
223 # Different from paper, but it uses a different permutation in order to obtain the same calculation
224 emb = torch.cat((freqs, freqs), dim=-1)
225 self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
226 self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
227
228
229 # Inverse dim formula to find dim based on number of rotations
230 def yarn_find_correction_dim(
231 num_rotations, dim, base=10000, max_position_embeddings=2048
232 ):
233 return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
234 2 * math.log(base)
235 )
236
237
238 # Find dim range bounds based on rotations
239 def yarn_find_correction_range(
240 low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
241 ):
242 low = math.floor(
243 yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
244 )
245 high = math.ceil(
246 yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
247 )
248 return max(low, 0), min(high, dim - 1) # Clamp values just in case
249
250
251 def yarn_get_mscale(scale=1, mscale=1):
252 if scale <= 1:
253 return 1.0
254 return 0.1 * mscale * math.log(scale) + 1.0
255
256
257 def yarn_linear_ramp_mask(min, max, dim):
258 if min == max:
259 max += 0.001 # Prevent singularity
260
261 linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
262 ramp_func = torch.clamp(linear_func, 0, 1)
263 return ramp_func
264
265
266 class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
267
268 def __init__(
269 self,
270 dim,
271 max_position_embeddings=2048,
272 base=10000,
273 device=None,
274 scaling_factor=1.0,
275 original_max_position_embeddings=4096,
276 beta_fast=32,
277 beta_slow=1,
278 mscale=1,
279 mscale_all_dim=0,
280 ):
281 self.scaling_factor = scaling_factor
282 self.original_max_position_embeddings = original_max_position_embeddings
283 self.beta_fast = beta_fast
284 self.beta_slow = beta_slow
285 self.mscale = mscale
286 self.mscale_all_dim = mscale_all_dim
287 super().__init__(dim, max_position_embeddings, base, device)
288
289 def _set_cos_sin_cache(self, seq_len, device, dtype):
290 self.max_seq_len_cached = seq_len
291 dim = self.dim
292
293 freq_extra = 1.0 / (
294 self.base
295 ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
296 )
297 freq_inter = 1.0 / (
298 self.scaling_factor
299 * self.base
300 ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
301 )
302
303 low, high = yarn_find_correction_range(
304 self.beta_fast,
305 self.beta_slow,
306 dim,
307 self.base,
308 self.original_max_position_embeddings,
309 )
310 inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
311 device=device, dtype=torch.float32
312 )
313 inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
314 self.register_buffer("inv_freq", inv_freq, persistent=False)
315
316 t = torch.arange(seq_len, device=device, dtype=torch.float32)
317
318 freqs = torch.outer(t, inv_freq)
319
320 _mscale = float(
321 yarn_get_mscale(self.scaling_factor, self.mscale)
322 / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
323 )
324
325 emb = torch.cat((freqs, freqs), dim=-1)
326 self.register_buffer(
327 "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
328 )
329 self.register_buffer(
330 "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
331 )
332
333
334 # Copied from transformers.models.llama.modeling_llama.rotate_half
335 def rotate_half(x):
336 """Rotates half the hidden dims of the input."""
337 x1 = x[..., : x.shape[-1] // 2]
338 x2 = x[..., x.shape[-1] // 2 :]
339 return torch.cat((-x2, x1), dim=-1)
340
341
342 # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
343 def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
344 """Applies Rotary Position Embedding to the query and key tensors.
345
346 Args:
347 q (`torch.Tensor`): The query tensor.
348 k (`torch.Tensor`): The key tensor.
349 cos (`torch.Tensor`): The cosine part of the rotary embedding.
350 sin (`torch.Tensor`): The sine part of the rotary embedding.
351 position_ids (`torch.Tensor`):
352 The position indices of the tokens corresponding to the query and key tensors. For example, this can be
353 used to pass offsetted position ids when working with a KV-cache.
354 unsqueeze_dim (`int`, *optional*, defaults to 1):
355 The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
356 sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
357 that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
358 k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
359 cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
360 the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
361 Returns:
362 `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
363 """
364 cos = cos[position_ids].unsqueeze(unsqueeze_dim)
365 sin = sin[position_ids].unsqueeze(unsqueeze_dim)
366
367
368 # print()
369
370 b, h, s, d = q.shape
371 q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
372
373 b, h, s, d = k.shape
374 k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
375
376 q_embed = (q * cos) + (rotate_half(q) * sin)
377 k_embed = (k * cos) + (rotate_half(k) * sin)
378
379
380 return q_embed, k_embed
381
382
383 class DeepseekV2MLP(nn.Module):
384 def __init__(self, config, hidden_size=None, intermediate_size=None):
385 super().__init__()
386 self.config = config
387 self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
388 self.intermediate_size = (
389 config.intermediate_size if intermediate_size is None else intermediate_size
390 )
391
392 self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
393 self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
394 self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
395 self.act_fn = ACT2FN[config.hidden_act]
396
397 def forward(self, x):
398 down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
399 return down_proj
400
401
402 class MoEGate(nn.Module):
403 def __init__(self, config):
404 super().__init__()
405 self.config = config
406 self.top_k = config.num_experts_per_tok
407 self.n_routed_experts = config.n_routed_experts
408 self.routed_scaling_factor = config.routed_scaling_factor
409 self.scoring_func = config.scoring_func
410 self.alpha = config.aux_loss_alpha
411 self.seq_aux = config.seq_aux
412 self.topk_method = config.topk_method
413 self.n_group = config.n_group
414 self.topk_group = config.topk_group
415
416 # topk selection algorithm
417 self.norm_topk_prob = config.norm_topk_prob
418 self.gating_dim = config.hidden_size
419 self.weight = nn.Parameter(
420 torch.empty((self.n_routed_experts, self.gating_dim))
421 )
422 if self.topk_method == "noaux_tc":
423 self.e_score_correction_bias = nn.Parameter(
424 torch.empty((self.n_routed_experts))
425 )
426 self.reset_parameters()
427
428 def reset_parameters(self) -> None:
429 import torch.nn.init as init
430
431 init.kaiming_uniform_(self.weight, a=math.sqrt(5))
432
433 def forward(self, hidden_states):
434 bsz, seq_len, h = hidden_states.shape
435 ### compute gating score
436 hidden_states = hidden_states.view(-1, h)
437 logits = F.linear(
438 hidden_states.type(torch.float32), self.weight.type(torch.float32), None
439 )
440 if self.scoring_func == "softmax":
441 scores = logits.softmax(dim=-1, dtype=torch.float32)
442 elif self.scoring_func == "sigmoid":
443 scores = logits.sigmoid()
444 else:
445 raise NotImplementedError(
446 f"insupportable scoring function for MoE gating: {self.scoring_func}"
447 )
448
449 ### select top-k experts
450 if self.topk_method == "greedy":
451 topk_weight, topk_idx = torch.topk(
452 scores, k=self.top_k, dim=-1, sorted=False
453 )
454 elif self.topk_method == "group_limited_greedy":
455 group_scores = (
456 scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
457 ) # [n, n_group]
458 group_idx = torch.topk(
459 group_scores, k=self.topk_group, dim=-1, sorted=False
460 )[
461 1
462 ] # [n, top_k_group]
463 group_mask = torch.zeros_like(group_scores) # [n, n_group]
464 group_mask.scatter_(1, group_idx, 1) # [n, n_group]
465 score_mask = (
466 group_mask.unsqueeze(-1)
467 .expand(
468 bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
469 )
470 .reshape(bsz * seq_len, -1)
471 ) # [n, e]
472 tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
473 topk_weight, topk_idx = torch.topk(
474 tmp_scores, k=self.top_k, dim=-1, sorted=False
475 )
476 elif self.topk_method == "noaux_tc":
477 assert not self.training
478 scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
479 group_scores = (
480 scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
481 ) # [n, n_group]
482 group_idx = torch.topk(
483 group_scores, k=self.topk_group, dim=-1, sorted=False
484 )[
485 1
486 ] # [n, top_k_group]
487 group_mask = torch.zeros_like(group_scores) # [n, n_group]
488 group_mask.scatter_(1, group_idx, 1) # [n, n_group]
489 score_mask = (
490 group_mask.unsqueeze(-1)
491 .expand(
492 bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
493 )
494 .reshape(bsz * seq_len, -1)
495 ) # [n, e]
496 tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
497 _, topk_idx = torch.topk(
498 tmp_scores, k=self.top_k, dim=-1, sorted=False
499 )
500 topk_weight = scores.gather(1, topk_idx)
501
502 ### norm gate to sum 1
503 if self.top_k > 1 and self.norm_topk_prob:
504 denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
505 topk_weight = topk_weight / denominator * self.routed_scaling_factor
506 else:
507 topk_weight = topk_weight * self.routed_scaling_factor
508 ### expert-level computation auxiliary loss
509 if self.training and self.alpha > 0.0:
510 scores_for_aux = scores
511 aux_topk = self.top_k
512 # always compute aux loss based on the naive greedy topk method
513 topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
514 if self.seq_aux:
515 scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
516 ce = torch.zeros(
517 bsz, self.n_routed_experts, device=hidden_states.device
518 )
519 ce.scatter_add_(
520 1,
521 topk_idx_for_aux_loss,
522 torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
523 ).div_(seq_len * aux_topk / self.n_routed_experts)
524 aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
525 dim=1
526 ).mean() * self.alpha
527 else:
528 mask_ce = F.one_hot(
529 topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
530 )
531 ce = mask_ce.float().mean(0)
532 Pi = scores_for_aux.mean(0)
533 fi = ce * self.n_routed_experts
534 aux_loss = (Pi * fi).sum() * self.alpha
535 else:
536 aux_loss = None
537 return topk_idx, topk_weight, aux_loss
538
539
540 class AddAuxiliaryLoss(torch.autograd.Function):
541 """
542 The trick function of adding auxiliary (aux) loss,
543 which includes the gradient of the aux loss during backpropagation.
544 """
545
546 @staticmethod
547 def forward(ctx, x, loss):
548 assert loss.numel() == 1
549 ctx.dtype = loss.dtype
550 ctx.required_aux_loss = loss.requires_grad
551 return x
552
553 @staticmethod
554 def backward(ctx, grad_output):
555 grad_loss = None
556 if ctx.required_aux_loss:
557 grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
558 return grad_output, grad_loss
559
560
561 class DeepseekV2MoE(nn.Module):
562 """
563 A mixed expert module containing shared experts.
564 """
565
566 def __init__(self, config):
567 super().__init__()
568 self.config = config
569 self.num_experts_per_tok = config.num_experts_per_tok
570
571 if hasattr(config, "ep_size") and config.ep_size > 1:
572 assert config.ep_size == dist.get_world_size()
573 self.ep_size = config.ep_size
574 self.experts_per_rank = config.n_routed_experts // config.ep_size
575 self.ep_rank = dist.get_rank()
576 self.experts = nn.ModuleList(
577 [
578 (
579 DeepseekV2MLP(
580 config, intermediate_size=config.moe_intermediate_size
581 )
582 if i >= self.ep_rank * self.experts_per_rank
583 and i < (self.ep_rank + 1) * self.experts_per_rank
584 else None
585 )
586 for i in range(config.n_routed_experts)
587 ]
588 )
589 else:
590 self.ep_size = 1
591 self.experts_per_rank = config.n_routed_experts
592 self.ep_rank = 0
593 self.experts = nn.ModuleList(
594 [
595 DeepseekV2MLP(
596 config, intermediate_size=config.moe_intermediate_size
597 )
598 for i in range(config.n_routed_experts)
599 ]
600 )
601 self.gate = MoEGate(config)
602 if config.n_shared_experts is not None:
603 intermediate_size = config.moe_intermediate_size * config.n_shared_experts
604 self.shared_experts = DeepseekV2MLP(
605 config=config, intermediate_size=intermediate_size
606 )
607
608 def forward(self, hidden_states):
609 identity = hidden_states
610 orig_shape = hidden_states.shape
611 topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
612 hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
613 flat_topk_idx = topk_idx.view(-1)
614 if self.training:
615 hidden_states = hidden_states.repeat_interleave(
616 self.num_experts_per_tok, dim=0
617 )
618 y = torch.empty_like(hidden_states)
619 for i, expert in enumerate(self.experts):
620 y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
621 y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
622 y = y.to(hidden_states.dtype).view(*orig_shape)
623 y = AddAuxiliaryLoss.apply(y, aux_loss)
624 else:
625 y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
626 if self.config.n_shared_experts is not None:
627 y = y + self.shared_experts(identity)
628 return y
629
630 @torch.no_grad()
631 def moe_infer(self, x, topk_ids, topk_weight):
632 cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
633 cnts.scatter_(1, topk_ids, 1)
634 tokens_per_expert = cnts.sum(dim=0)
635 idxs = topk_ids.view(-1).argsort()
636 sorted_tokens = x[idxs // topk_ids.shape[1]]
637 sorted_tokens_shape = sorted_tokens.shape
638 if self.ep_size > 1:
639 tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
640 tokens_per_expert_group = tokens_per_expert.new_empty(
641 tokens_per_expert.shape[0]
642 )
643 dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
644 output_splits = (
645 tokens_per_expert_group.view(self.ep_size, -1)
646 .sum(1)
647 .cpu()
648 .numpy()
649 .tolist()
650 )
651 gathered_tokens = sorted_tokens.new_empty(
652 tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
653 )
654 input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
655 dist.all_to_all(
656 list(gathered_tokens.split(output_splits)),
657 list(sorted_tokens.split(input_split_sizes)),
658 )
659 tokens_per_expert_post_gather = tokens_per_expert_group.view(
660 self.ep_size, self.experts_per_rank
661 ).sum(dim=0)
662 gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
663 s = 0
664 for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
665 gatherd_idxs[s : s + k] = i % self.experts_per_rank
666 s += k
667 gatherd_idxs = gatherd_idxs.argsort()
668 sorted_tokens = gathered_tokens[gatherd_idxs]
669 tokens_per_expert = tokens_per_expert_post_gather
670 tokens_per_expert = tokens_per_expert.cpu().numpy()
671
672 outputs = []
673 start_idx = 0
674 for i, num_tokens in enumerate(tokens_per_expert):
675 end_idx = start_idx + num_tokens
676 if num_tokens == 0:
677 continue
678 expert = self.experts[i + self.ep_rank * self.experts_per_rank]
679 tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
680 expert_out = expert(tokens_for_this_expert)
681 outputs.append(expert_out)
682 start_idx = end_idx
683
684 outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
685 if self.ep_size > 1:
686 new_x = torch.empty_like(outs)
687 new_x[gatherd_idxs] = outs
688 gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
689 dist.all_to_all(
690 list(gathered_tokens.split(input_split_sizes)),
691 list(new_x.split(output_splits)),
692 )
693 outs = gathered_tokens
694
695 new_x = torch.empty_like(outs)
696 new_x[idxs] = outs
697 final_out = (
698 new_x.view(*topk_ids.shape, -1)
699 .type(topk_weight.dtype)
700 .mul_(topk_weight.unsqueeze(dim=-1))
701 .sum(dim=1)
702 .type(new_x.dtype)
703 )
704 return final_out
705
706
707 # Copied from transformers.models.llama.modeling_llama.repeat_kv
708 def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
709 """
710 This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
711 num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
712 """
713 batch, num_key_value_heads, slen, head_dim = hidden_states.shape
714 if n_rep == 1:
715 return hidden_states
716 hidden_states = hidden_states[:, :, None, :, :].expand(
717 batch, num_key_value_heads, n_rep, slen, head_dim
718 )
719 return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
720
721
722 # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
723 class DeepseekV2Attention(nn.Module):
724 """Multi-headed attention from 'Attention Is All You Need' paper"""
725
726 def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
727 super().__init__()
728 self.config = config
729 self.layer_idx = layer_idx
730 if layer_idx is None:
731 logger.warning_once(
732 f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
733 "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
734 "when creating this class."
735 )
736
737 self.attention_dropout = config.attention_dropout
738 self.hidden_size = config.hidden_size
739 self.num_heads = config.num_attention_heads
740
741 self.max_position_embeddings = config.max_position_embeddings
742 self.rope_theta = config.rope_theta
743 self.q_lora_rank = config.q_lora_rank
744 self.qk_rope_head_dim = config.qk_rope_head_dim
745 self.kv_lora_rank = config.kv_lora_rank
746 self.v_head_dim = config.v_head_dim
747 self.qk_nope_head_dim = config.qk_nope_head_dim
748 self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
749
750 self.is_causal = True
751
752 if self.q_lora_rank is None:
753 self.q_proj = nn.Linear(
754 self.hidden_size, self.num_heads * self.q_head_dim, bias=False
755 )
756 else:
757 self.q_a_proj = nn.Linear(
758 self.hidden_size, config.q_lora_rank, bias=config.attention_bias
759 )
760 self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
761 self.q_b_proj = nn.Linear(
762 config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
763 )
764 # config.kv_lora_rank + config.qk_rope_head_dim,
765 self.kv_a_proj_with_mqa = nn.Linear(
766 self.hidden_size,
767 config.kv_lora_rank + config.qk_rope_head_dim,
768 bias=config.attention_bias,
769 )
770 self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
771 self.kv_b_proj = nn.Linear(
772 config.kv_lora_rank,
773 self.num_heads
774 * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
775 bias=False,
776 )
777
778 self.o_proj = nn.Linear(
779 self.num_heads * self.v_head_dim,
780 self.hidden_size,
781 bias=config.attention_bias,
782 )
783 self._init_rope()
784
785 self.softmax_scale = self.q_head_dim ** (-0.5)
786 if self.config.rope_scaling is not None:
787 mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
788 scaling_factor = self.config.rope_scaling["factor"]
789 if mscale_all_dim:
790 mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
791 self.softmax_scale = self.softmax_scale * mscale * mscale
792
793 def _init_rope(self):
794 if self.config.rope_scaling is None:
795 self.rotary_emb = DeepseekV2RotaryEmbedding(
796 self.qk_rope_head_dim,
797 max_position_embeddings=self.max_position_embeddings,
798 base=self.rope_theta,
799 )
800 # self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
801 # self.qk_rope_head_dim,
802 # max_position_embeddings=self.max_position_embeddings,
803 # scaling_factor=scaling_factor,
804 # base=self.rope_theta,
805 # )
806 else:
807 scaling_type = self.config.rope_scaling["type"]
808 scaling_factor = self.config.rope_scaling["factor"]
809 if scaling_type == "linear":
810 self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
811 self.qk_rope_head_dim,
812 max_position_embeddings=self.max_position_embeddings,
813 scaling_factor=scaling_factor,
814 base=self.rope_theta,
815 )
816 elif scaling_type == "dynamic":
817 self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
818 self.qk_rope_head_dim,
819 max_position_embeddings=self.max_position_embeddings,
820 scaling_factor=scaling_factor,
821 base=self.rope_theta,
822 )
823 elif scaling_type == "yarn":
824 kwargs = {
825 key: self.config.rope_scaling[key]
826 for key in [
827 "original_max_position_embeddings",
828 "beta_fast",
829 "beta_slow",
830 "mscale",
831 "mscale_all_dim",
832 ]
833 if key in self.config.rope_scaling
834 }
835 self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
836 self.qk_rope_head_dim,
837 max_position_embeddings=self.max_position_embeddings,
838 scaling_factor=scaling_factor,
839 base=self.rope_theta,
840 **kwargs,
841 )
842 else:
843 raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
844
845 def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
846 return (
847 tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
848 .transpose(1, 2)
849 .contiguous()
850 )
851
852 def forward(
853 self,
854 hidden_states: torch.Tensor,
855 attention_mask: Optional[torch.Tensor] = None,
856 position_ids: Optional[torch.LongTensor] = None,
857 past_key_value: Optional[Cache] = None,
858 output_attentions: bool = False,
859 use_cache: bool = False,
860 **kwargs,
861 ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
862 if "padding_mask" in kwargs:
863 warnings.warn(
864 "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
865 )
866 bsz, q_len, _ = hidden_states.size()
867
868 if self.q_lora_rank is None:
869 q = self.q_proj(hidden_states)
870 else:
871 q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
872 q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
873
874
875 q_nope, q_pe = torch.split(
876 q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
877 )
878
879 compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
880 compressed_kv, k_pe = torch.split(
881 compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
882 )
883 compressed_kv = self.kv_a_layernorm(compressed_kv)
884 k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
885
886 kv_seq_len = k_pe.shape[-2]
887 if past_key_value is not None:
888 if self.layer_idx is None:
889 raise ValueError(
890 f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
891 "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
892 "with a layer index."
893 )
894 kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
895
896 cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len)
897 q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
898
899 if past_key_value is not None:
900 cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
901 compressed_kv = compressed_kv.unsqueeze(1)
902 k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
903 compressed_kv = compressed_kv.squeeze(1)
904
905 kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank)
906 q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :]
907 out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
908
909 q_nope = torch.matmul(q_nope, q_absorb)
910 attn_weights = (torch.matmul(q_pe, k_pe.mT) +
911 torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale
912 if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
913 raise ValueError(
914 f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
915 f" {attn_weights.size()}"
916 )
917 assert attention_mask is not None
918 if attention_mask is not None:
919 if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
920 raise ValueError(
921 f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
922 )
923 attn_weights = attn_weights + attention_mask
924
925 # upcast attention to fp32
926 attn_weights = nn.functional.softmax(
927 attn_weights, dim=-1, dtype=torch.float32
928 ).to(q_pe.dtype)
929 attn_weights = nn.functional.dropout(
930 attn_weights, p=self.attention_dropout, training=self.training
931 )
932 attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
933
934 attn_output = torch.matmul(attn_output, out_absorb.mT)
935
936 if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
937 raise ValueError(
938 f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
939 f" {attn_output.size()}"
940 )
941
942 attn_output = attn_output.transpose(1, 2).contiguous()
943
944 attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
945
946 attn_output = self.o_proj(attn_output)
947
948 if not output_attentions:
949 attn_weights = None
950
951 return attn_output, attn_weights, past_key_value
952
953
954 # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
955 class DeepseekV2FlashAttention2(DeepseekV2Attention):
956 """
957 DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
958 untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
959 flash attention and deal with padding tokens in case the input contains any of them.
960 """
961
962 def __init__(self, *args, **kwargs):
963 super().__init__(*args, **kwargs)
964
965 # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
966 # 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.
967 # 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).
968 self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
969
970 def forward(
971 self,
972 hidden_states: torch.Tensor,
973 attention_mask: Optional[torch.LongTensor] = None,
974 position_ids: Optional[torch.LongTensor] = None,
975 past_key_value: Optional[Cache] = None,
976 output_attentions: bool = False,
977 use_cache: bool = False,
978 **kwargs,
979 ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
980 # DeepseekV2FlashAttention2 attention does not support output_attentions
981 if "padding_mask" in kwargs:
982 warnings.warn(
983 "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
984 )
985
986 # overwrite attention_mask with padding_mask
987 attention_mask = kwargs.pop("padding_mask")
988
989 output_attentions = False
990
991 bsz, q_len, _ = hidden_states.size()
992
993 if self.q_lora_rank is None:
994 q = self.q_proj(hidden_states)
995 else:
996 q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
997 q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
998 q_nope, q_pe = torch.split(
999 q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1000 )
1001
1002 # Flash attention requires the input to have the shape
1003 # batch_size x seq_length x head_dim x hidden_dim
1004 # therefore we just need to keep the original shape
1005 compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1006 compressed_kv, k_pe = torch.split(
1007 compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1008 )
1009 k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1010 kv = (
1011 self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1012 .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1013 .transpose(1, 2)
1014 )
1015
1016 k_nope, value_states = torch.split(
1017 kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1018 )
1019 kv_seq_len = value_states.shape[-2]
1020
1021 kv_seq_len = value_states.shape[-2]
1022 if past_key_value is not None:
1023 kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
1024
1025 cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1026 q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1027
1028 query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1029 query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1030 query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1031
1032 key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1033 key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1034 key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1035
1036 if self.q_head_dim != self.v_head_dim:
1037 value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1038
1039 # TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version
1040 if past_key_value is not None:
1041 cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1042 key_states, value_states = past_key_value.update(
1043 key_states, value_states, self.layer_idx, cache_kwargs
1044 )
1045
1046 # 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
1047 # to be able to avoid many of these transpose/reshape/view.
1048 query_states = query_states.transpose(1, 2)
1049 key_states = key_states.transpose(1, 2)
1050 value_states = value_states.transpose(1, 2)
1051
1052 dropout_rate = self.attention_dropout if self.training else 0.0
1053
1054 # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1055 # therefore the input hidden states gets silently casted in float32. Hence, we need
1056 # cast them back in the correct dtype just to be sure everything works as expected.
1057 # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1058 # in fp32. (DeepseekV2RMSNorm handles it correctly)
1059
1060 input_dtype = query_states.dtype
1061 if input_dtype == torch.float32:
1062 # Handle the case where the model is quantized
1063 if hasattr(self.config, "_pre_quantization_dtype"):
1064 target_dtype = self.config._pre_quantization_dtype
1065 elif torch.is_autocast_enabled():
1066 target_dtype = torch.get_autocast_gpu_dtype()
1067 else:
1068 target_dtype = (
1069 self.q_proj.weight.dtype
1070 if self.q_lora_rank is None
1071 else self.q_a_proj.weight.dtype
1072 )
1073
1074 logger.warning_once(
1075 f"The input hidden states seems to be silently casted in float32, this might be related to"
1076 f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1077 f" {target_dtype}."
1078 )
1079
1080 query_states = query_states.to(target_dtype)
1081 key_states = key_states.to(target_dtype)
1082 value_states = value_states.to(target_dtype)
1083
1084 attn_output = self._flash_attention_forward(
1085 query_states,
1086 key_states,
1087 value_states,
1088 attention_mask,
1089 q_len,
1090 dropout=dropout_rate,
1091 softmax_scale=self.softmax_scale,
1092 )
1093 if self.q_head_dim != self.v_head_dim:
1094 attn_output = attn_output[:, :, :, : self.v_head_dim]
1095
1096 attn_output = attn_output.reshape(
1097 bsz, q_len, self.num_heads * self.v_head_dim
1098 ).contiguous()
1099 attn_output = self.o_proj(attn_output)
1100
1101 if not output_attentions:
1102 attn_weights = None
1103
1104 return attn_output, attn_weights, past_key_value
1105
1106 def _flash_attention_forward(
1107 self,
1108 query_states,
1109 key_states,
1110 value_states,
1111 attention_mask,
1112 query_length,
1113 dropout=0.0,
1114 softmax_scale=None,
1115 ):
1116 """
1117 Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1118 first unpad the input, then computes the attention scores and pad the final attention scores.
1119
1120 Args:
1121 query_states (`torch.Tensor`):
1122 Input query states to be passed to Flash Attention API
1123 key_states (`torch.Tensor`):
1124 Input key states to be passed to Flash Attention API
1125 value_states (`torch.Tensor`):
1126 Input value states to be passed to Flash Attention API
1127 attention_mask (`torch.Tensor`):
1128 The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1129 position of padding tokens and 1 for the position of non-padding tokens.
1130 dropout (`int`, *optional*):
1131 Attention dropout
1132 softmax_scale (`float`, *optional*):
1133 The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1134 """
1135 if not self._flash_attn_uses_top_left_mask:
1136 causal = self.is_causal
1137 else:
1138 # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1139 causal = self.is_causal and query_length != 1
1140
1141 # Contains at least one padding token in the sequence
1142 if attention_mask is not None:
1143 batch_size = query_states.shape[0]
1144 (
1145 query_states,
1146 key_states,
1147 value_states,
1148 indices_q,
1149 cu_seq_lens,
1150 max_seq_lens,
1151 ) = self._upad_input(
1152 query_states, key_states, value_states, attention_mask, query_length
1153 )
1154
1155 cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1156 max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1157
1158 attn_output_unpad = flash_attn_varlen_func(
1159 query_states,
1160 key_states,
1161 value_states,
1162 cu_seqlens_q=cu_seqlens_q,
1163 cu_seqlens_k=cu_seqlens_k,
1164 max_seqlen_q=max_seqlen_in_batch_q,
1165 max_seqlen_k=max_seqlen_in_batch_k,
1166 dropout_p=dropout,
1167 softmax_scale=softmax_scale,
1168 causal=causal,
1169 )
1170
1171 attn_output = pad_input(
1172 attn_output_unpad, indices_q, batch_size, query_length
1173 )
1174 else:
1175 attn_output = flash_attn_func(
1176 query_states,
1177 key_states,
1178 value_states,
1179 dropout,
1180 softmax_scale=softmax_scale,
1181 causal=causal,
1182 )
1183
1184 return attn_output
1185
1186 def _upad_input(
1187 self, query_layer, key_layer, value_layer, attention_mask, query_length
1188 ):
1189 indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1190 batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1191
1192 key_layer = index_first_axis(
1193 key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1194 indices_k,
1195 )
1196 value_layer = index_first_axis(
1197 value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1198 indices_k,
1199 )
1200 if query_length == kv_seq_len:
1201 query_layer = index_first_axis(
1202 query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1203 indices_k,
1204 )
1205 cu_seqlens_q = cu_seqlens_k
1206 max_seqlen_in_batch_q = max_seqlen_in_batch_k
1207 indices_q = indices_k
1208 elif query_length == 1:
1209 max_seqlen_in_batch_q = 1
1210 cu_seqlens_q = torch.arange(
1211 batch_size + 1, dtype=torch.int32, device=query_layer.device
1212 ) # There is a memcpy here, that is very bad.
1213 indices_q = cu_seqlens_q[:-1]
1214 query_layer = query_layer.squeeze(1)
1215 else:
1216 # The -q_len: slice assumes left padding.
1217 attention_mask = attention_mask[:, -query_length:]
1218 query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1219 query_layer, attention_mask
1220 )
1221
1222 return (
1223 query_layer,
1224 key_layer,
1225 value_layer,
1226 indices_q,
1227 (cu_seqlens_q, cu_seqlens_k),
1228 (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1229 )
1230
1231
1232 class SlidingWindowLlamaAttention(LlamaAttention):
1233 """LlamaAttention with sliding window KV cache using a ring buffer during decode."""
1234
1235 def __init__(self, config, layer_idx):
1236 super().__init__(config, layer_idx)
1237 # New transformers moved rotary_emb to model level; create our own
1238 if not hasattr(self, 'rotary_emb'):
1239 from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding
1240 self.rotary_emb = LlamaRotaryEmbedding(config=config)
1241 # Save sliding_window separately so we can disable it in config to prevent
1242 # DynamicCache from truncating prefill tokens
1243 self._sliding_window = getattr(config, 'sliding_window', None)
1244
1245 def forward(self, *args, **kwargs):
1246 import math
1247
1248 # Compatibility: new DynamicCache uses .layers[i].keys/.values instead of .key_cache[i]/.value_cache[i]
1249 def _get_kcache(cache, layer_idx):
1250 if hasattr(cache, 'key_cache'):
1251 return cache.key_cache[layer_idx]
1252 return cache.layers[layer_idx].keys
1253
1254 def _get_vcache(cache, layer_idx):
1255 if hasattr(cache, 'value_cache'):
1256 return cache.value_cache[layer_idx]
1257 return cache.layers[layer_idx].values
1258
1259 # Extract args
1260 def _get(name, idx, default=None):
1261 if name in kwargs:
1262 return kwargs[name]
1263 if len(args) > idx:
1264 return args[idx]
1265 return default
1266
1267 hidden_states = _get('hidden_states', 0)
1268 attention_mask = _get('attention_mask', 1)
1269 position_ids = _get('position_ids', 2)
1270 past_kv = _get('past_key_value', 3)
1271 if past_kv is None:
1272 past_kv = kwargs.get('past_key_values', None)
1273 output_attentions = _get('output_attentions', 4, False)
1274
1275 # Dimensions from config (new transformers removed self.num_heads)
1276 num_heads = self.config.num_attention_heads
1277 num_kv_heads = self.config.num_key_value_heads
1278 head_dim = self.head_dim
1279 num_kv_groups = self.num_key_value_groups
1280
1281 bsz, q_len, _ = hidden_states.size()
1282 W = getattr(self.config, '_ring_window', None) # Read from config (set before generate)
1283
1284 # --- Helper: standard QKV attention ---
1285 def _attn_forward(use_cache_update=True):
1286 query_states = self.q_proj(hidden_states).view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1287 key_states = self.k_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1288 value_states = self.v_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1289
1290 cos, sin = self.rotary_emb(value_states, position_ids)
1291 query_states, key_states = _llama_apply_rotary_pos_emb(query_states, key_states, cos, sin)
1292
1293 if past_kv is not None and use_cache_update:
1294 key_states, value_states = past_kv.update(key_states, value_states, self.layer_idx)
1295
1296 k = _llama_repeat_kv(key_states, num_kv_groups)
1297 v = _llama_repeat_kv(value_states, num_kv_groups)
1298
1299 attn_weights = torch.matmul(query_states, k.transpose(2, 3)) / math.sqrt(head_dim)
1300 if attention_mask is not None:
1301 causal_mask = attention_mask[:, :, :, :k.shape[-2]]
1302 attn_weights = attn_weights + causal_mask
1303 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
1304 attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
1305 attn_output = torch.matmul(attn_weights, v)
1306 attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, q_len, -1)
1307 attn_output = self.o_proj(attn_output)
1308 return attn_output, None, past_kv
1309
1310 # Prefill or no sliding window
1311 # True prefill: W disabled, no cache, or first forward (prefill_length not yet recorded)
1312 _is_true_prefill = (W is None or past_kv is None or
1313 (q_len > 1 and (not hasattr(past_kv, '_prefill_length') or
1314 self.layer_idx not in past_kv._prefill_length)))
1315 if _is_true_prefill:
1316 result = _attn_forward()
1317 if W is not None and past_kv is not None and q_len > 1:
1318 # Only record prefill_length the FIRST time (don't overwrite on subsequent q_len>1 calls)
1319 if not hasattr(past_kv, '_prefill_length'):
1320 past_kv._prefill_length = {}
1321 if self.layer_idx not in past_kv._prefill_length:
1322 past_kv._prefill_length[self.layer_idx] = _get_kcache(past_kv, self.layer_idx).shape[-2]
1323 return result
1324
1325 # Decode path: first decode step -> record prefill_length (only once!)
1326 if not hasattr(past_kv, '_prefill_length') or self.layer_idx not in past_kv._prefill_length:
1327 if not hasattr(past_kv, '_prefill_length'):
1328 past_kv._prefill_length = {}
1329 past_kv._prefill_length[self.layer_idx] = _get_kcache(past_kv, self.layer_idx).shape[-2]
1330
1331 prefill_len = past_kv._prefill_length[self.layer_idx]
1332 cur_len = _get_kcache(past_kv, self.layer_idx).shape[-2]
1333
1334 # Warmup: cat-append until ring region is full
1335 if cur_len < prefill_len + W:
1336 result = _attn_forward()
1337 new_len = _get_kcache(past_kv, self.layer_idx).shape[-2]
1338 if new_len >= prefill_len + W:
1339 if not hasattr(past_kv, '_ring_pos'):
1340 past_kv._ring_pos = {}
1341 past_kv._ring_pos[self.layer_idx] = 0
1342 return result
1343
1344 # Steady state: ring in-place overwrite
1345 if not hasattr(past_kv, '_ring_pos') or self.layer_idx not in past_kv._ring_pos:
1346 past_kv._ring_pos = getattr(past_kv, '_ring_pos', {}) or {}
1347 past_kv._ring_pos[self.layer_idx] = 0
1348
1349 # Ring decode: overwrite ring slots, then attention over full cache
1350 ring_pos = past_kv._ring_pos[self.layer_idx]
1351 kcache = _get_kcache(past_kv, self.layer_idx)
1352 vcache = _get_vcache(past_kv, self.layer_idx)
1353
1354 # Compute new K, V and apply RoPE, then overwrite ring slots
1355 query_states = self.q_proj(hidden_states).view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1356 key_states = self.k_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1357 value_states = self.v_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1358 cos, sin = self.rotary_emb(value_states, position_ids)
1359 query_states, key_states = _llama_apply_rotary_pos_emb(query_states, key_states, cos, sin)
1360
1361 # Overwrite ring slots in-place
1362 for t in range(q_len):
1363 slot = prefill_len + ring_pos
1364 kcache[:, :, slot:slot + 1, :] = key_states[:, :, t:t + 1, :]
1365 vcache[:, :, slot:slot + 1, :] = value_states[:, :, t:t + 1, :]
1366 ring_pos = (ring_pos + 1) % W
1367 past_kv._ring_pos[self.layer_idx] = ring_pos
1368
1369 # Attention over full cache (no causal mask needed for decode q_len=1)
1370 k = _llama_repeat_kv(kcache, num_kv_groups)
1371 v = _llama_repeat_kv(vcache, num_kv_groups)
1372 attn_weights = torch.matmul(query_states, k.transpose(2, 3)) / math.sqrt(head_dim)
1373 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
1374 attn_output = torch.matmul(attn_weights, v)
1375 attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, q_len, -1)
1376 attn_output = self.o_proj(attn_output)
1377 return attn_output, None, past_kv
1378
1379
1380 ATTENTION_CLASSES = {
1381 "eager": DeepseekV2Attention,
1382 "flash_attention_2": DeepseekV2FlashAttention2,
1383
1384 "mla_eager": DeepseekV2Attention,
1385 "mla_flash_attention_2": DeepseekV2FlashAttention2,
1386
1387 "mha_eager": SlidingWindowLlamaAttention,
1388 # "mha_flash_attention_2": LlamaFlashAttention2
1389 }
1390
1391
1392 class DeepseekV2DecoderLayer(nn.Module):
1393 def __init__(self, config: DeepseekV2Config, layer_idx: int):
1394 super().__init__()
1395 self.hidden_size = config.hidden_size
1396
1397
1398 if config.use_mla:
1399 attn_implementation = "mla_" + config._attn_implementation
1400 else:
1401 attn_implementation = "mha_" + config._attn_implementation
1402
1403 self.self_attn = ATTENTION_CLASSES[attn_implementation](
1404 config=config, layer_idx=layer_idx
1405 )
1406
1407 self.mlp = (
1408 DeepseekV2MoE(config)
1409 if (
1410 config.n_routed_experts is not None
1411 and layer_idx >= config.first_k_dense_replace
1412 and layer_idx % config.moe_layer_freq == 0
1413 )
1414 else DeepseekV2MLP(config)
1415 )
1416 self.input_layernorm = DeepseekV2RMSNorm(
1417 config.hidden_size, eps=config.rms_norm_eps
1418 )
1419 self.post_attention_layernorm = DeepseekV2RMSNorm(
1420 config.hidden_size, eps=config.rms_norm_eps
1421 )
1422
1423 def forward(
1424 self,
1425 hidden_states: torch.Tensor,
1426 attention_mask: Optional[torch.Tensor] = None,
1427 position_ids: Optional[torch.LongTensor] = None,
1428 past_key_value: Optional[Tuple[torch.Tensor]] = None,
1429 output_attentions: Optional[bool] = False,
1430 use_cache: Optional[bool] = False,
1431 **kwargs,
1432 ) -> Tuple[
1433 torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1434 ]:
1435 """
1436 Args:
1437 hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1438 attention_mask (`torch.FloatTensor`, *optional*):
1439 attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1440 query_sequence_length, key_sequence_length)` if default attention is used.
1441 output_attentions (`bool`, *optional*):
1442 Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1443 returned tensors for more detail.
1444 use_cache (`bool`, *optional*):
1445 If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1446 (see `past_key_values`).
1447 past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1448 """
1449 if "padding_mask" in kwargs:
1450 warnings.warn(
1451 "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1452 )
1453 residual = hidden_states
1454
1455 hidden_states = self.input_layernorm(hidden_states)
1456
1457 # Self Attention
1458 hidden_states, self_attn_weights, present_key_value = self.self_attn(
1459 hidden_states=hidden_states,
1460 attention_mask=attention_mask,
1461 position_ids=position_ids,
1462 past_key_value=past_key_value,
1463 output_attentions=output_attentions,
1464 use_cache=use_cache,
1465 **kwargs,
1466 )
1467 hidden_states = residual + hidden_states
1468
1469 # Fully Connected
1470 residual = hidden_states
1471 hidden_states = self.post_attention_layernorm(hidden_states)
1472 hidden_states = self.mlp(hidden_states)
1473 hidden_states = residual + hidden_states
1474
1475 outputs = (hidden_states,)
1476
1477 if output_attentions:
1478 outputs += (self_attn_weights,)
1479
1480 if use_cache:
1481 outputs += (present_key_value,)
1482
1483 return outputs
1484
1485
1486 DeepseekV2_START_DOCSTRING = r"""
1487 This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1488 library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1489 etc.)
1490
1491 This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1492 Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1493 and behavior.
1494
1495 Parameters:
1496 config ([`DeepseekV2Config`]):
1497 Model configuration class with all the parameters of the model. Initializing with a config file does not
1498 load the weights associated with the model, only the configuration. Check out the
1499 [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1500 """
1501
1502
1503 @add_start_docstrings(
1504 "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1505 DeepseekV2_START_DOCSTRING,
1506 )
1507 class DeepseekV2PreTrainedModel(PreTrainedModel):
1508 config_class = DeepseekV2Config
1509 base_model_prefix = "model"
1510 supports_gradient_checkpointing = True
1511 _no_split_modules = ["DeepseekV2DecoderLayer"]
1512 _skip_keys_device_placement = "past_key_values"
1513 _supports_flash_attn_2 = True
1514 _supports_cache_class = True
1515
1516 def _init_weights(self, module):
1517 std = self.config.initializer_range
1518 if isinstance(module, nn.Linear):
1519 module.weight.data.normal_(mean=0.0, std=std)
1520 if module.bias is not None:
1521 module.bias.data.zero_()
1522 elif isinstance(module, nn.Embedding):
1523 module.weight.data.normal_(mean=0.0, std=std)
1524 if module.padding_idx is not None:
1525 module.weight.data[module.padding_idx].zero_()
1526
1527
1528 DeepseekV2_INPUTS_DOCSTRING = r"""
1529 Args:
1530 input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1531 Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1532 it.
1533
1534 Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1535 [`PreTrainedTokenizer.__call__`] for details.
1536
1537 [What are input IDs?](../glossary#input-ids)
1538 attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1539 Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1540
1541 - 1 for tokens that are **not masked**,
1542 - 0 for tokens that are **masked**.
1543
1544 [What are attention masks?](../glossary#attention-mask)
1545
1546 Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1547 [`PreTrainedTokenizer.__call__`] for details.
1548
1549 If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1550 `past_key_values`).
1551
1552 If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1553 and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1554 information on the default strategy.
1555
1556 - 1 indicates the head is **not masked**,
1557 - 0 indicates the head is **masked**.
1558 position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1559 Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1560 config.n_positions - 1]`.
1561
1562 [What are position IDs?](../glossary#position-ids)
1563 past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1564 Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1565 blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1566 returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1567
1568 Two formats are allowed:
1569 - a [`~cache_utils.Cache`] instance;
1570 - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1571 shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1572 cache format.
1573
1574 The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1575 legacy cache format will be returned.
1576
1577 If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1578 have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1579 of shape `(batch_size, sequence_length)`.
1580 inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1581 Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1582 is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1583 model's internal embedding lookup matrix.
1584 use_cache (`bool`, *optional*):
1585 If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1586 `past_key_values`).
1587 output_attentions (`bool`, *optional*):
1588 Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1589 tensors for more detail.
1590 output_hidden_states (`bool`, *optional*):
1591 Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1592 more detail.
1593 return_dict (`bool`, *optional*):
1594 Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1595 """
1596
1597
1598 @add_start_docstrings(
1599 "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1600 DeepseekV2_START_DOCSTRING,
1601 )
1602 class DeepseekV2Model(DeepseekV2PreTrainedModel):
1603 """
1604 Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1605
1606 Args:
1607 config: DeepseekV2Config
1608 """
1609
1610 def __init__(self, config: DeepseekV2Config):
1611 super().__init__(config)
1612 self.padding_idx = config.pad_token_id
1613 self.vocab_size = config.vocab_size
1614
1615 self.embed_tokens = nn.Embedding(
1616 config.vocab_size, config.hidden_size, self.padding_idx
1617 )
1618 self.layers = nn.ModuleList(
1619 [
1620 DeepseekV2DecoderLayer(config, layer_idx)
1621 for layer_idx in range(config.num_hidden_layers)
1622 ]
1623 )
1624 # print(config._attn_implementation)
1625 self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1626 self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1627
1628 self.gradient_checkpointing = False
1629 # Initialize weights and apply final processing
1630 self.post_init()
1631
1632 def get_input_embeddings(self):
1633 return self.embed_tokens
1634
1635 def set_input_embeddings(self, value):
1636 self.embed_tokens = value
1637
1638 @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1639 def forward(
1640 self,
1641 input_ids: torch.LongTensor = None,
1642 attention_mask: Optional[torch.Tensor] = None,
1643 position_ids: Optional[torch.LongTensor] = None,
1644 past_key_values: Optional[List[torch.FloatTensor]] = None,
1645 inputs_embeds: Optional[torch.FloatTensor] = None,
1646 use_cache: Optional[bool] = None,
1647 output_attentions: Optional[bool] = None,
1648 output_hidden_states: Optional[bool] = None,
1649 return_dict: Optional[bool] = None,
1650 cache_position: Optional[torch.LongTensor] = None
1651 ) -> Union[Tuple, BaseModelOutputWithPast]:
1652 output_attentions = (
1653 output_attentions
1654 if output_attentions is not None
1655 else self.config.output_attentions
1656 )
1657 output_hidden_states = (
1658 output_hidden_states
1659 if output_hidden_states is not None
1660 else self.config.output_hidden_states
1661 )
1662 use_cache = use_cache if use_cache is not None else self.config.use_cache
1663
1664 return_dict = (
1665 return_dict if return_dict is not None else self.config.use_return_dict
1666 )
1667
1668 # retrieve input_ids and inputs_embeds
1669 if input_ids is not None and inputs_embeds is not None:
1670 raise ValueError(
1671 "You cannot specify both input_ids and inputs_embeds at the same time"
1672 )
1673 elif input_ids is not None:
1674 batch_size, seq_length = input_ids.shape[:2]
1675 elif inputs_embeds is not None:
1676 batch_size, seq_length = inputs_embeds.shape[:2]
1677 else:
1678 raise ValueError("You have to specify either input_ids or inputs_embeds")
1679
1680 if self.gradient_checkpointing and self.training:
1681 if use_cache:
1682 logger.warning_once(
1683 "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1684 )
1685 use_cache = False
1686
1687 past_key_values_length = 0
1688 if use_cache:
1689 use_legacy_cache = not isinstance(past_key_values, Cache)
1690 if use_legacy_cache:
1691 past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1692 past_key_values_length = past_key_values.get_seq_length()
1693
1694 if position_ids is None:
1695 device = input_ids.device if input_ids is not None else inputs_embeds.device
1696 position_ids = torch.arange(
1697 past_key_values_length,
1698 seq_length + past_key_values_length,
1699 dtype=torch.long,
1700 device=device,
1701 )
1702 position_ids = position_ids.unsqueeze(0)
1703
1704 if inputs_embeds is None:
1705 inputs_embeds = self.embed_tokens(input_ids)
1706
1707 # Skip 4D causal mask for decode (q_len=1 with KV cache doesn't need it)
1708 if seq_length == 1 and past_key_values_length > 0:
1709 attention_mask = None
1710 elif self._use_flash_attention_2:
1711 # 2d mask is passed through the layers
1712 attention_mask = (
1713 attention_mask
1714 if (attention_mask is not None and 0 in attention_mask)
1715 else None
1716 )
1717 else:
1718 # 4d mask is passed through the layers
1719 attention_mask = _prepare_4d_causal_attention_mask(
1720 attention_mask,
1721 (batch_size, seq_length),
1722 inputs_embeds,
1723 past_key_values_length,
1724 )
1725
1726 # embed positions
1727 hidden_states = inputs_embeds
1728
1729 # decoder layers
1730 all_hidden_states = () if output_hidden_states else None
1731 all_self_attns = () if output_attentions else None
1732 next_decoder_cache = None
1733
1734 for decoder_layer in self.layers:
1735 if output_hidden_states:
1736 all_hidden_states += (hidden_states,)
1737
1738 if self.gradient_checkpointing and self.training:
1739 layer_outputs = self._gradient_checkpointing_func(
1740 decoder_layer.__call__,
1741 hidden_states,
1742 attention_mask,
1743 position_ids,
1744 past_key_values,
1745 output_attentions,
1746 use_cache,
1747 )
1748 else:
1749 layer_outputs = decoder_layer(
1750 hidden_states,
1751 attention_mask=attention_mask,
1752 position_ids=position_ids,
1753 past_key_value=past_key_values,
1754 output_attentions=output_attentions,
1755 use_cache=use_cache,
1756 )
1757
1758 hidden_states = layer_outputs[0]
1759
1760 if use_cache:
1761 next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1762
1763 if output_attentions:
1764 all_self_attns += (layer_outputs[1],)
1765
1766 hidden_states = self.norm(hidden_states)
1767
1768 # add hidden states from the last decoder layer
1769 if output_hidden_states:
1770 all_hidden_states += (hidden_states,)
1771
1772 next_cache = None
1773 if use_cache:
1774 next_cache = next_decoder_cache # Always return DynamicCache to preserve custom attributes
1775 if not return_dict:
1776 return tuple(
1777 v
1778 for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1779 if v is not None
1780 )
1781 return BaseModelOutputWithPast(
1782 last_hidden_state=hidden_states,
1783 past_key_values=next_cache,
1784 hidden_states=all_hidden_states,
1785 attentions=all_self_attns,
1786 )
1787
1788
1789 class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1790 _tied_weights_keys = ["lm_head.weight"]
1791
1792 def __init__(self, config):
1793 super().__init__(config)
1794 self.model = DeepseekV2Model(config)
1795 self.vocab_size = config.vocab_size
1796 self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1797
1798 # Initialize weights and apply final processing
1799 self.post_init()
1800
1801 def get_input_embeddings(self):
1802 return self.model.embed_tokens
1803
1804 def set_input_embeddings(self, value):
1805 self.model.embed_tokens = value
1806
1807 def get_output_embeddings(self):
1808 return self.lm_head
1809
1810 def set_output_embeddings(self, new_embeddings):
1811 self.lm_head = new_embeddings
1812
1813 def set_decoder(self, decoder):
1814 self.model = decoder
1815
1816 def get_decoder(self):
1817 return self.model
1818
1819 @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1820 @replace_return_docstrings(
1821 output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1822 )
1823 def forward(
1824 self,
1825 input_ids: torch.LongTensor = None,
1826 attention_mask: Optional[torch.Tensor] = None,
1827 position_ids: Optional[torch.LongTensor] = None,
1828 past_key_values: Optional[List[torch.FloatTensor]] = None,
1829 inputs_embeds: Optional[torch.FloatTensor] = None,
1830 labels: Optional[torch.LongTensor] = None,
1831 use_cache: Optional[bool] = None,
1832 output_attentions: Optional[bool] = None,
1833 output_hidden_states: Optional[bool] = None,
1834 return_dict: Optional[bool] = None,
1835 cache_position: Optional[torch.LongTensor] = None
1836 ) -> Union[Tuple, CausalLMOutputWithPast]:
1837 r"""
1838 Args:
1839 labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1840 Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1841 config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1842 (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1843
1844 Returns:
1845
1846 Example:
1847
1848 ```python
1849 >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1850
1851 >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1852 >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1853
1854 >>> prompt = "Hey, are you conscious? Can you talk to me?"
1855 >>> inputs = tokenizer(prompt, return_tensors="pt")
1856
1857 >>> # Generate
1858 >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1859 >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1860 "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1861 ```"""
1862 output_attentions = (
1863 output_attentions
1864 if output_attentions is not None
1865 else self.config.output_attentions
1866 )
1867 output_hidden_states = (
1868 output_hidden_states
1869 if output_hidden_states is not None
1870 else self.config.output_hidden_states
1871 )
1872 return_dict = (
1873 return_dict if return_dict is not None else self.config.use_return_dict
1874 )
1875
1876 # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1877 outputs = self.model(
1878 input_ids=input_ids,
1879 attention_mask=attention_mask,
1880 position_ids=position_ids,
1881 past_key_values=past_key_values,
1882 inputs_embeds=inputs_embeds,
1883 use_cache=use_cache,
1884 output_attentions=output_attentions,
1885 output_hidden_states=output_hidden_states,
1886 return_dict=return_dict,
1887 cache_position=cache_position
1888 )
1889
1890 hidden_states = outputs[0]
1891 logits = self.lm_head(hidden_states)
1892 logits = logits.float()
1893
1894 loss = None
1895 if labels is not None:
1896 # Shift so that tokens < n predict n
1897 shift_logits = logits[..., :-1, :].contiguous()
1898 shift_labels = labels[..., 1:].contiguous()
1899 # Flatten the tokens
1900 loss_fct = CrossEntropyLoss()
1901 shift_logits = shift_logits.view(-1, self.config.vocab_size)
1902 shift_labels = shift_labels.view(-1)
1903 # Enable model parallelism
1904 shift_labels = shift_labels.to(shift_logits.device)
1905 loss = loss_fct(shift_logits, shift_labels)
1906
1907 if not return_dict:
1908 output = (logits,) + outputs[1:]
1909 return (loss,) + output if loss is not None else output
1910
1911 return CausalLMOutputWithPast(
1912 loss=loss,
1913 logits=logits,
1914 past_key_values=outputs.past_key_values,
1915 hidden_states=outputs.hidden_states,
1916 attentions=outputs.attentions,
1917 )
1918
1919 def prepare_inputs_for_generation(
1920 self,
1921 input_ids,
1922 past_key_values=None,
1923 attention_mask=None,
1924 inputs_embeds=None,
1925 **kwargs,
1926 ):
1927 past_length = 0
1928 if past_key_values is not None:
1929 if isinstance(past_key_values, Cache):
1930 cache_length = past_key_values.get_seq_length()
1931 past_length = past_key_values.get_seq_length()
1932 max_cache_length = getattr(past_key_values, 'get_max_length', lambda: None)()
1933 else:
1934 cache_length = past_length = past_key_values[0][0].shape[2]
1935 max_cache_length = None
1936
1937 # Keep only the unprocessed tokens:
1938 # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1939 # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1940 # input)
1941 if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1942 input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1943 # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1944 # input_ids based on the past_length.
1945 elif past_length < input_ids.shape[1]:
1946 input_ids = input_ids[:, past_length:]
1947 # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1948
1949 # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1950 if (
1951 max_cache_length is not None
1952 and attention_mask is not None
1953 and cache_length + input_ids.shape[1] > max_cache_length
1954 ):
1955 attention_mask = attention_mask[:, -max_cache_length:]
1956
1957 position_ids = kwargs.get("position_ids", None)
1958 if attention_mask is not None and position_ids is None:
1959 # create position_ids on the fly for batch generation
1960 position_ids = attention_mask.long().cumsum(-1) - 1
1961 position_ids.masked_fill_(attention_mask == 0, 1)
1962 if past_key_values:
1963 position_ids = position_ids[:, -input_ids.shape[1]:]
1964
1965 if self.generation_config.cache_implementation == "static":
1966 # generation with static cache
1967 cache_position = kwargs.get("cache_position", None)
1968 if cache_position is None:
1969 past_length = 0
1970 else:
1971 past_length = cache_position[-1] + 1
1972 input_ids = input_ids[:, past_length:]
1973 position_ids = position_ids[:, past_length:]
1974
1975 # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
1976 # same goes for position ids. Could also help with continued generation.
1977 cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
1978
1979 # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1980 if inputs_embeds is not None and past_key_values is None:
1981 model_inputs = {"inputs_embeds": inputs_embeds}
1982 else:
1983 # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1984 # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1985 # TODO: use `next_tokens` directly instead.
1986 model_inputs = {"input_ids": input_ids.contiguous()}
1987
1988 model_inputs.update(
1989 {
1990 "position_ids": position_ids.contiguous(),
1991 "cache_position": cache_position,
1992 "past_key_values": past_key_values,
1993 "use_cache": kwargs.get("use_cache"),
1994 "attention_mask": attention_mask,
1995 }
1996 )
1997 return model_inputs
1998
1999 @staticmethod
2000 def _reorder_cache(past_key_values, beam_idx):
2001 reordered_past = ()
2002 for layer_past in past_key_values:
2003 reordered_past += (
2004 tuple(
2005 past_state.index_select(0, beam_idx.to(past_state.device))
2006 for past_state in layer_past
2007 ),
2008 )
2009 return reordered_past
2010
2011
2012 @add_start_docstrings(
2013 """
2014 The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
2015
2016 [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2017 (e.g. GPT-2) do.
2018
2019 Since it does classification on the last token, it requires to know the position of the last token. If a
2020 `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2021 no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2022 padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2023 each row of the batch).
2024 """,
2025 DeepseekV2_START_DOCSTRING,
2026 )
2027 class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
2028 def __init__(self, config):
2029 super().__init__(config)
2030 self.num_labels = config.num_labels
2031 self.model = DeepseekV2Model(config)
2032 self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2033
2034 # Initialize weights and apply final processing
2035 self.post_init()
2036
2037 def get_input_embeddings(self):
2038 return self.model.embed_tokens
2039
2040 def set_input_embeddings(self, value):
2041 self.model.embed_tokens = value
2042
2043 @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
2044 def forward(
2045 self,
2046 input_ids: torch.LongTensor = None,
2047 attention_mask: Optional[torch.Tensor] = None,
2048 position_ids: Optional[torch.LongTensor] = None,
2049 past_key_values: Optional[List[torch.FloatTensor]] = None,
2050 inputs_embeds: Optional[torch.FloatTensor] = None,
2051 labels: Optional[torch.LongTensor] = None,
2052 use_cache: Optional[bool] = None,
2053 output_attentions: Optional[bool] = None,
2054 output_hidden_states: Optional[bool] = None,
2055 return_dict: Optional[bool] = None,
2056 ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2057 r"""
2058 labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2059 Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2060 config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2061 `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2062 """
2063 return_dict = (
2064 return_dict if return_dict is not None else self.config.use_return_dict
2065 )
2066
2067 transformer_outputs = self.model(
2068 input_ids,
2069 attention_mask=attention_mask,
2070 position_ids=position_ids,
2071 past_key_values=past_key_values,
2072 inputs_embeds=inputs_embeds,
2073 use_cache=use_cache,
2074 output_attentions=output_attentions,
2075 output_hidden_states=output_hidden_states,
2076 return_dict=return_dict,
2077 )
2078 hidden_states = transformer_outputs[0]
2079 logits = self.score(hidden_states)
2080
2081 if input_ids is not None:
2082 batch_size = input_ids.shape[0]
2083 else:
2084 batch_size = inputs_embeds.shape[0]
2085
2086 if self.config.pad_token_id is None and batch_size != 1:
2087 raise ValueError(
2088 "Cannot handle batch sizes > 1 if no padding token is defined."
2089 )
2090 if self.config.pad_token_id is None:
2091 sequence_lengths = -1
2092 else:
2093 if input_ids is not None:
2094 sequence_lengths = (
2095 torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2096 ).to(logits.device)
2097 else:
2098 sequence_lengths = -1
2099
2100 pooled_logits = logits[
2101 torch.arange(batch_size, device=logits.device), sequence_lengths
2102 ]
2103
2104 loss = None
2105 if labels is not None:
2106 labels = labels.to(logits.device)
2107 if self.config.problem_type is None:
2108 if self.num_labels == 1:
2109 self.config.problem_type = "regression"
2110 elif self.num_labels > 1 and (
2111 labels.dtype == torch.long or labels.dtype == torch.int
2112 ):
2113 self.config.problem_type = "single_label_classification"
2114 else:
2115 self.config.problem_type = "multi_label_classification"
2116
2117 if self.config.problem_type == "regression":
2118 loss_fct = MSELoss()
2119 if self.num_labels == 1:
2120 loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2121 else:
2122 loss = loss_fct(pooled_logits, labels)
2123 elif self.config.problem_type == "single_label_classification":
2124 loss_fct = CrossEntropyLoss()
2125 loss = loss_fct(
2126 pooled_logits.view(-1, self.num_labels), labels.view(-1)
2127 )
2128 elif self.config.problem_type == "multi_label_classification":
2129 loss_fct = BCEWithLogitsLoss()
2130 loss = loss_fct(pooled_logits, labels)
2131 if not return_dict:
2132 output = (pooled_logits,) + transformer_outputs[1:]
2133 return ((loss,) + output) if loss is not None else output
2134
2135 return SequenceClassifierOutputWithPast(
2136 loss=loss,
2137 logits=pooled_logits,
2138 past_key_values=transformer_outputs.past_key_values,
2139 hidden_states=transformer_outputs.hidden_states,
2140 attentions=transformer_outputs.attentions,
2141 )
2142