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