xinference 1.4.0__py3-none-any.whl → 1.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xinference might be problematic. Click here for more details.

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