v2ray commited on
Commit
5c89bcb
·
verified ·
1 Parent(s): 4f35c39

Upload folder using huggingface_hub

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