JuhaoLiang commited on
Commit
c463ff7
·
1 Parent(s): 3c4c912

checkpoints

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. checkpoint-1000/config.json +66 -0
  2. checkpoint-1000/configuration_tinydeepseek.py +222 -0
  3. checkpoint-1000/generation_config.json +7 -0
  4. checkpoint-1000/model-00001-of-00002.safetensors +3 -0
  5. checkpoint-1000/model-00002-of-00002.safetensors +3 -0
  6. checkpoint-1000/model.safetensors.index.json +0 -0
  7. checkpoint-1000/modeling_tinydeepseek.py +2150 -0
  8. checkpoint-1000/tokenizer.json +0 -0
  9. checkpoint-1000/tokenizer_config.json +35 -0
  10. checkpoint-10000/config.json +66 -0
  11. checkpoint-10000/configuration_tinydeepseek.py +222 -0
  12. checkpoint-10000/generation_config.json +7 -0
  13. checkpoint-10000/model-00001-of-00002.safetensors +3 -0
  14. checkpoint-10000/model-00002-of-00002.safetensors +3 -0
  15. checkpoint-10000/model.safetensors.index.json +0 -0
  16. checkpoint-10000/modeling_tinydeepseek.py +2150 -0
  17. checkpoint-10000/tokenizer.json +0 -0
  18. checkpoint-10000/tokenizer_config.json +35 -0
  19. checkpoint-11000/config.json +66 -0
  20. checkpoint-11000/configuration_tinydeepseek.py +222 -0
  21. checkpoint-11000/generation_config.json +7 -0
  22. checkpoint-11000/model-00001-of-00002.safetensors +3 -0
  23. checkpoint-11000/model-00002-of-00002.safetensors +3 -0
  24. checkpoint-11000/model.safetensors.index.json +0 -0
  25. checkpoint-11000/modeling_tinydeepseek.py +2150 -0
  26. checkpoint-11000/tokenizer.json +0 -0
  27. checkpoint-11000/tokenizer_config.json +35 -0
  28. checkpoint-12000/config.json +66 -0
  29. checkpoint-12000/configuration_tinydeepseek.py +222 -0
  30. checkpoint-12000/generation_config.json +7 -0
  31. checkpoint-12000/model-00001-of-00002.safetensors +3 -0
  32. checkpoint-12000/model-00002-of-00002.safetensors +3 -0
  33. checkpoint-12000/model.safetensors.index.json +0 -0
  34. checkpoint-12000/modeling_tinydeepseek.py +2150 -0
  35. checkpoint-12000/tokenizer.json +0 -0
  36. checkpoint-12000/tokenizer_config.json +35 -0
  37. checkpoint-13000/config.json +66 -0
  38. checkpoint-13000/configuration_tinydeepseek.py +222 -0
  39. checkpoint-13000/generation_config.json +7 -0
  40. checkpoint-13000/model-00001-of-00002.safetensors +3 -0
  41. checkpoint-13000/model-00002-of-00002.safetensors +3 -0
  42. checkpoint-13000/model.safetensors.index.json +0 -0
  43. checkpoint-13000/modeling_tinydeepseek.py +2150 -0
  44. checkpoint-13000/tokenizer.json +0 -0
  45. checkpoint-13000/tokenizer_config.json +35 -0
  46. checkpoint-14000/config.json +66 -0
  47. checkpoint-14000/configuration_tinydeepseek.py +222 -0
  48. checkpoint-14000/generation_config.json +7 -0
  49. checkpoint-14000/model-00001-of-00002.safetensors +3 -0
  50. checkpoint-14000/model-00002-of-00002.safetensors +3 -0
checkpoint-1000/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyDeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tinydeepseek.TinyDeepseekV3Config",
9
+ "AutoModel": "modeling_tinydeepseek.TinyDeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_tinydeepseek.TinyDeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.0001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4864,
21
+ "kv_lora_rank": 128,
22
+ "lossfreebalance_update_rate": 0.001,
23
+ "max_position_embeddings": 163840,
24
+ "model_type": "tinydeepseek_v3",
25
+ "moe_intermediate_size": 608,
26
+ "moe_layer_freq": 1,
27
+ "mtp_loss_lambda": 0.1,
28
+ "n_future_tokens": 2,
29
+ "n_group": 8,
30
+ "n_routed_experts": 64,
31
+ "n_shared_experts": 2,
32
+ "norm_topk_prob": true,
33
+ "num_attention_heads": 8,
34
+ "num_experts_per_tok": 6,
35
+ "num_hidden_layers": 27,
36
+ "num_key_value_heads": 8,
37
+ "num_nextn_predict_layers": 1,
38
+ "output_router_logits": false,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": null,
41
+ "qk_nope_head_dim": 32,
42
+ "qk_rope_head_dim": 16,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 0.707,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 1.0,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": false,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.48.3",
62
+ "use_cache": true,
63
+ "use_lossfreebalance": false,
64
+ "v_head_dim": 32,
65
+ "vocab_size": 129280
66
+ }
checkpoint-1000/configuration_tinydeepseek.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TinyDeepseekV3Config(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
+ n_future_tokens (int):
104
+ Number of prediction heads in the model (= 1 + `len(extra_heads)`).
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "tinydeepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'aux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.0001,
147
+ seq_aux=True,
148
+ output_router_logits=False,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ n_future_tokens=1,
164
+ mtp_loss_lambda=0.1,
165
+ use_lossfreebalance=True,
166
+ lossfreebalance_update_rate=0.001,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.moe_intermediate_size = moe_intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_nextn_predict_layers = num_nextn_predict_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.n_shared_experts = n_shared_experts
178
+ self.n_routed_experts = n_routed_experts
179
+ self.ep_size = ep_size
180
+ self.routed_scaling_factor = routed_scaling_factor
181
+ self.kv_lora_rank = kv_lora_rank
182
+ self.q_lora_rank = q_lora_rank if q_lora_rank else None
183
+ self.qk_rope_head_dim = qk_rope_head_dim
184
+ self.v_head_dim = v_head_dim
185
+ self.qk_nope_head_dim = qk_nope_head_dim
186
+ self.topk_method = topk_method
187
+ self.n_group = n_group
188
+ self.topk_group = topk_group
189
+ self.num_experts_per_tok = num_experts_per_tok
190
+ self.moe_layer_freq = moe_layer_freq
191
+ self.first_k_dense_replace = first_k_dense_replace
192
+ self.norm_topk_prob = norm_topk_prob
193
+ self.scoring_func = scoring_func
194
+ self.aux_loss_alpha = aux_loss_alpha
195
+ self.seq_aux = seq_aux
196
+ self.output_router_logits = output_router_logits
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.rms_norm_eps = rms_norm_eps
205
+ self.pretraining_tp = pretraining_tp
206
+ self.use_cache = use_cache
207
+ self.rope_theta = rope_theta
208
+ self.rope_scaling = rope_scaling
209
+ self.attention_bias = attention_bias
210
+ self.attention_dropout = attention_dropout
211
+ self.n_future_tokens = n_future_tokens
212
+ self.mtp_loss_lambda = mtp_loss_lambda
213
+ self.use_lossfreebalance = use_lossfreebalance
214
+ self.lossfreebalance_update_rate = lossfreebalance_update_rate
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
checkpoint-1000/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.48.3",
6
+ "use_cache": false
7
+ }
checkpoint-1000/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61ee0209e324bc3e0b1230038c7a873a130e402be4b246028705c280f38a8692
3
+ size 5000243440
checkpoint-1000/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43ab3809fde27fc853f500ef5ceba279a8801f60a7873d82e3bf825ac33b5d5a
3
+ size 1591021104
checkpoint-1000/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-1000/modeling_tinydeepseek.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MoeModelOutputWithPast,
40
+ MoeCausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ # is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_tinydeepseek import TinyDeepseekV3Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ # if not is_torch_greater_or_equal_than_1_13:
70
+ # import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "TinyDeepseekV3Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
94
+ def load_balancing_loss_func(
95
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
96
+ num_experts: Optional[int] = None,
97
+ top_k=2,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ ) -> Union[torch.Tensor, int]:
100
+ r"""
101
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
102
+
103
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
104
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
105
+ experts is too unbalanced.
106
+
107
+ Args:
108
+ gate_logits:
109
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
110
+ shape [batch_size X sequence_length, num_experts].
111
+ num_experts:
112
+ Number of experts
113
+ top_k:
114
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
115
+ parameter.
116
+ attention_mask (`torch.Tensor`, *optional*):
117
+ The attention_mask used in forward function
118
+ shape [batch_size X sequence_length] if not None.
119
+
120
+ Returns:
121
+ The auxiliary loss.
122
+ """
123
+ if gate_logits is None or not isinstance(gate_logits, tuple):
124
+ return 0
125
+
126
+ if isinstance(gate_logits, tuple):
127
+ compute_device = gate_logits[0].device
128
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
129
+
130
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
131
+
132
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
133
+
134
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
135
+
136
+ if attention_mask is None:
137
+ # Compute the percentage of tokens routed to each experts
138
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
139
+
140
+ # Compute the average probability of routing to these experts
141
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
142
+ else:
143
+ batch_size, sequence_length = attention_mask.shape
144
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
145
+
146
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
147
+ expert_attention_mask = (
148
+ attention_mask[None, :, :, None, None]
149
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
150
+ .reshape(-1, top_k, num_experts)
151
+ .to(compute_device)
152
+ )
153
+
154
+ # Compute the percentage of tokens routed to each experts
155
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
156
+ expert_attention_mask, dim=0
157
+ )
158
+
159
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
160
+ router_per_expert_attention_mask = (
161
+ attention_mask[None, :, :, None]
162
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
163
+ .reshape(-1, num_experts)
164
+ .to(compute_device)
165
+ )
166
+
167
+ # Compute the average probability of routing to these experts
168
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
169
+ router_per_expert_attention_mask, dim=0
170
+ )
171
+
172
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
173
+ return overall_loss * num_experts
174
+
175
+
176
+ class DeepseekV3RMSNorm(nn.Module):
177
+ def __init__(self, hidden_size, eps=1e-6):
178
+ """
179
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
180
+ """
181
+ super().__init__()
182
+ self.weight = nn.Parameter(torch.ones(hidden_size))
183
+ self.variance_epsilon = eps
184
+
185
+ def forward(self, hidden_states):
186
+ input_dtype = hidden_states.dtype
187
+ hidden_states = hidden_states.to(torch.float32)
188
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
189
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
190
+ return self.weight * hidden_states.to(input_dtype)
191
+
192
+
193
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
194
+
195
+
196
+ class DeepseekV3RotaryEmbedding(nn.Module):
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
198
+ super().__init__()
199
+
200
+ self.dim = dim
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.base = base
203
+ inv_freq = 1.0 / (
204
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
205
+ )
206
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
207
+
208
+ # Build here to make `torch.jit.trace` work.
209
+ self._set_cos_sin_cache(
210
+ seq_len=max_position_embeddings,
211
+ device=self.inv_freq.device,
212
+ dtype=torch.get_default_dtype(),
213
+ )
214
+ self.max_seq_len_cached = None
215
+
216
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
217
+ self.max_seq_len_cached = seq_len
218
+ t = torch.arange(
219
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
220
+ )
221
+
222
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
223
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
224
+ emb = torch.cat((freqs, freqs), dim=-1)
225
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
226
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
227
+
228
+ def forward(self, x, seq_len=None):
229
+ # x: [bs, num_attention_heads, seq_len, head_size]
230
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
231
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
232
+
233
+ return (
234
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
235
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
236
+ )
237
+
238
+
239
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
240
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
241
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ max_position_embeddings=2048,
247
+ base=10000,
248
+ device=None,
249
+ scaling_factor=1.0,
250
+ ):
251
+ self.scaling_factor = scaling_factor
252
+ super().__init__(dim, max_position_embeddings, base, device)
253
+
254
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
255
+ self.max_seq_len_cached = seq_len
256
+ t = torch.arange(
257
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
258
+ )
259
+ t = t / self.scaling_factor
260
+
261
+ freqs = torch.outer(t, self.inv_freq)
262
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
263
+ emb = torch.cat((freqs, freqs), dim=-1)
264
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
265
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
266
+
267
+
268
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
269
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
270
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
271
+
272
+ def __init__(
273
+ self,
274
+ dim,
275
+ max_position_embeddings=2048,
276
+ base=10000,
277
+ device=None,
278
+ scaling_factor=1.0,
279
+ ):
280
+ self.scaling_factor = scaling_factor
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
+
286
+ if seq_len > self.max_position_embeddings:
287
+ base = self.base * (
288
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
289
+ - (self.scaling_factor - 1)
290
+ ) ** (self.dim / (self.dim - 2))
291
+ inv_freq = 1.0 / (
292
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
293
+ )
294
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
295
+
296
+ t = torch.arange(
297
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
298
+ )
299
+
300
+ freqs = torch.outer(t, self.inv_freq)
301
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
302
+ emb = torch.cat((freqs, freqs), dim=-1)
303
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
304
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
305
+
306
+
307
+ # Inverse dim formula to find dim based on number of rotations
308
+ def yarn_find_correction_dim(
309
+ num_rotations, dim, base=10000, max_position_embeddings=2048
310
+ ):
311
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
312
+ 2 * math.log(base)
313
+ )
314
+
315
+
316
+ # Find dim range bounds based on rotations
317
+ def yarn_find_correction_range(
318
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
319
+ ):
320
+ low = math.floor(
321
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
322
+ )
323
+ high = math.ceil(
324
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
325
+ )
326
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
327
+
328
+
329
+ def yarn_get_mscale(scale=1, mscale=1):
330
+ if scale <= 1:
331
+ return 1.0
332
+ return 0.1 * mscale * math.log(scale) + 1.0
333
+
334
+
335
+ def yarn_linear_ramp_mask(min, max, dim):
336
+ if min == max:
337
+ max += 0.001 # Prevent singularity
338
+
339
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
340
+ ramp_func = torch.clamp(linear_func, 0, 1)
341
+ return ramp_func
342
+
343
+
344
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
345
+
346
+ def __init__(
347
+ self,
348
+ dim,
349
+ max_position_embeddings=2048,
350
+ base=10000,
351
+ device=None,
352
+ scaling_factor=1.0,
353
+ original_max_position_embeddings=4096,
354
+ beta_fast=32,
355
+ beta_slow=1,
356
+ mscale=1,
357
+ mscale_all_dim=0,
358
+ ):
359
+ self.scaling_factor = scaling_factor
360
+ self.original_max_position_embeddings = original_max_position_embeddings
361
+ self.beta_fast = beta_fast
362
+ self.beta_slow = beta_slow
363
+ self.mscale = mscale
364
+ self.mscale_all_dim = mscale_all_dim
365
+ super().__init__(dim, max_position_embeddings, base, device)
366
+
367
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
368
+ self.max_seq_len_cached = seq_len
369
+ dim = self.dim
370
+
371
+ freq_extra = 1.0 / (
372
+ self.base
373
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
374
+ )
375
+ freq_inter = 1.0 / (
376
+ self.scaling_factor
377
+ * self.base
378
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
379
+ )
380
+
381
+ low, high = yarn_find_correction_range(
382
+ self.beta_fast,
383
+ self.beta_slow,
384
+ dim,
385
+ self.base,
386
+ self.original_max_position_embeddings,
387
+ )
388
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
389
+ device=device, dtype=torch.float32
390
+ )
391
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
392
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
393
+
394
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
395
+
396
+ freqs = torch.outer(t, inv_freq)
397
+
398
+ _mscale = float(
399
+ yarn_get_mscale(self.scaling_factor, self.mscale)
400
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
401
+ )
402
+
403
+ emb = torch.cat((freqs, freqs), dim=-1)
404
+ self.register_buffer(
405
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
406
+ )
407
+ self.register_buffer(
408
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
409
+ )
410
+
411
+
412
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
413
+ def rotate_half(x):
414
+ """Rotates half the hidden dims of the input."""
415
+ x1 = x[..., : x.shape[-1] // 2]
416
+ x2 = x[..., x.shape[-1] // 2 :]
417
+ return torch.cat((-x2, x1), dim=-1)
418
+
419
+
420
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
421
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
422
+ """Applies Rotary Position Embedding to the query and key tensors.
423
+
424
+ Args:
425
+ q (`torch.Tensor`): The query tensor.
426
+ k (`torch.Tensor`): The key tensor.
427
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
428
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
429
+ position_ids (`torch.Tensor`):
430
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
431
+ used to pass offsetted position ids when working with a KV-cache.
432
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
433
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
434
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
435
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
436
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
437
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
438
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
439
+ Returns:
440
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
441
+ """
442
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
443
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
444
+
445
+ b, h, s, d = q.shape
446
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
447
+
448
+ b, h, s, d = k.shape
449
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
450
+
451
+ q_embed = (q * cos) + (rotate_half(q) * sin)
452
+ k_embed = (k * cos) + (rotate_half(k) * sin)
453
+ return q_embed, k_embed
454
+
455
+
456
+ class DeepseekV3MLP(nn.Module):
457
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
458
+ super().__init__()
459
+ self.config = config
460
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
461
+ self.intermediate_size = (
462
+ config.intermediate_size if intermediate_size is None else intermediate_size
463
+ )
464
+
465
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
466
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
467
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
468
+ self.act_fn = ACT2FN[config.hidden_act]
469
+
470
+ def forward(self, x):
471
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
472
+ return down_proj
473
+
474
+
475
+ class MoEGate(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.config = config
479
+ self.top_k = config.num_experts_per_tok
480
+ self.n_routed_experts = config.n_routed_experts
481
+ self.routed_scaling_factor = config.routed_scaling_factor
482
+ self.scoring_func = config.scoring_func
483
+ self.seq_aux = config.seq_aux
484
+ self.topk_method = config.topk_method
485
+ self.n_group = config.n_group
486
+ self.topk_group = config.topk_group
487
+
488
+ # topk selection algorithm
489
+ self.norm_topk_prob = config.norm_topk_prob
490
+ self.gating_dim = config.hidden_size
491
+ self.weight = nn.Parameter(
492
+ torch.empty((self.n_routed_experts, self.gating_dim))
493
+ )
494
+ if self.topk_method == "noaux_tc":
495
+ self.e_score_correction_bias = nn.Parameter(
496
+ torch.empty((self.n_routed_experts))
497
+ )
498
+ elif self.topk_method == "aux_tc":
499
+ self.update_rate = config.lossfreebalance_update_rate
500
+ self.e_score_correction_bias = nn.Parameter(
501
+ torch.zeros((self.n_routed_experts))
502
+ )
503
+
504
+ self.reset_parameters()
505
+
506
+ def reset_parameters(self) -> None:
507
+ import torch.nn.init as init
508
+
509
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
510
+
511
+ def forward(self, hidden_states):
512
+ bsz, seq_len, h = hidden_states.shape
513
+ ### compute gating score
514
+ hidden_states = hidden_states.view(-1, h)
515
+ logits = F.linear(
516
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
517
+ )
518
+ if self.scoring_func == "sigmoid":
519
+ scores = logits.sigmoid()
520
+ else:
521
+ raise NotImplementedError(
522
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
523
+ )
524
+
525
+ ### select top-k experts
526
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
527
+ group_scores = (
528
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
529
+ ) # [n, n_group]
530
+ group_idx = torch.topk(
531
+ group_scores, k=self.topk_group, dim=-1, sorted=False
532
+ )[
533
+ 1
534
+ ] # [n, top_k_group]
535
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
536
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
537
+ score_mask = (
538
+ group_mask.unsqueeze(-1)
539
+ .expand(
540
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
541
+ )
542
+ .reshape(bsz * seq_len, -1)
543
+ ) # [n, e]
544
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
545
+ _, topk_idx = torch.topk(
546
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
547
+ )
548
+ topk_weight = scores.gather(1, topk_idx)
549
+
550
+ if self.topk_method == "aux_tc":
551
+ expert_counts = torch.bincount(
552
+ topk_idx.flatten(),
553
+ minlength=self.n_routed_experts
554
+ )
555
+
556
+ avg_count = expert_counts.float().mean()
557
+ #max_violation = torch.max(torch.abs(expert_counts.float() - avg_count) / avg_count)
558
+
559
+ # for monitoring the expert-balancing globallu
560
+ # min_violation = torch.min(expert_counts.float()) / avg_count
561
+ # max_violation = torch.max(expert_counts.float()) / avg_count
562
+ # return [min_violation.item(), max_violation.item()]
563
+
564
+ for expert_idx, expert_count in enumerate(expert_counts):
565
+ # b_i = b_i + u + sign(e_i)
566
+ # note: this is \bar{c_i} - c_i, NOT c_i - \bar{c_i}, which will push the network to
567
+ # be maximally unbalanced. Really important to get this part right!!!
568
+ count_error = avg_count - expert_count.float()
569
+ self.e_score_correction_bias.data[expert_idx] += (self.update_rate * torch.sign(count_error))
570
+
571
+ ### norm gate to sum 1
572
+ if self.top_k > 1 and self.norm_topk_prob:
573
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
574
+ topk_weight = topk_weight / denominator
575
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
576
+
577
+ return topk_idx, topk_weight, scores
578
+
579
+ class TinyDeepseekV3MoE(nn.Module):
580
+ """
581
+ A mixed expert module containing shared experts.
582
+ """
583
+
584
+ def __init__(self, config):
585
+ super().__init__()
586
+ self.config = config
587
+ self.num_experts_per_tok = config.num_experts_per_tok
588
+
589
+ if hasattr(config, "ep_size") and config.ep_size > 1:
590
+ assert config.ep_size == dist.get_world_size()
591
+ self.ep_size = config.ep_size
592
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
593
+ self.ep_rank = dist.get_rank()
594
+ self.experts = nn.ModuleList(
595
+ [
596
+ (
597
+ DeepseekV3MLP(
598
+ config, intermediate_size=config.moe_intermediate_size
599
+ )
600
+ if i >= self.ep_rank * self.experts_per_rank
601
+ and i < (self.ep_rank + 1) * self.experts_per_rank
602
+ else None
603
+ )
604
+ for i in range(config.n_routed_experts)
605
+ ]
606
+ )
607
+ else:
608
+ self.ep_size = 1
609
+ self.experts_per_rank = config.n_routed_experts
610
+ self.ep_rank = 0
611
+ self.experts = nn.ModuleList(
612
+ [
613
+ DeepseekV3MLP(
614
+ config, intermediate_size=config.moe_intermediate_size
615
+ )
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV3MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, router_scores = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if not self.training:
633
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
634
+ else:
635
+ # tinydeepseek: moe forward for training
636
+ y = self.moe_train(hidden_states, topk_idx, topk_weight).view(*orig_shape)
637
+ if self.config.n_shared_experts is not None:
638
+ y = y + self.shared_experts(identity)
639
+ return y, router_scores
640
+
641
+ @torch.no_grad()
642
+ def moe_infer(self, x, topk_ids, topk_weight):
643
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
644
+ cnts.scatter_(1, topk_ids, 1)
645
+ tokens_per_expert = cnts.sum(dim=0)
646
+ idxs = topk_ids.view(-1).argsort()
647
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
648
+ sorted_tokens_shape = sorted_tokens.shape
649
+ if self.ep_size > 1:
650
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
651
+ tokens_per_expert_group = tokens_per_expert.new_empty(
652
+ tokens_per_expert.shape[0]
653
+ )
654
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
655
+ output_splits = (
656
+ tokens_per_expert_group.view(self.ep_size, -1)
657
+ .sum(1)
658
+ .cpu()
659
+ .numpy()
660
+ .tolist()
661
+ )
662
+ gathered_tokens = sorted_tokens.new_empty(
663
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
664
+ )
665
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
666
+ dist.all_to_all(
667
+ list(gathered_tokens.split(output_splits)),
668
+ list(sorted_tokens.split(input_split_sizes)),
669
+ )
670
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
671
+ self.ep_size, self.experts_per_rank
672
+ ).sum(dim=0)
673
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
674
+ s = 0
675
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
676
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
677
+ s += k
678
+ gatherd_idxs = gatherd_idxs.argsort()
679
+ sorted_tokens = gathered_tokens[gatherd_idxs]
680
+ tokens_per_expert = tokens_per_expert_post_gather
681
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
682
+
683
+ outputs = []
684
+ start_idx = 0
685
+ for i, num_tokens in enumerate(tokens_per_expert):
686
+ end_idx = start_idx + num_tokens
687
+ if num_tokens == 0:
688
+ continue
689
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
690
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
691
+ expert_out = expert(tokens_for_this_expert)
692
+ outputs.append(expert_out)
693
+ start_idx = end_idx
694
+
695
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
696
+ if self.ep_size > 1:
697
+ new_x = torch.empty_like(outs)
698
+ new_x[gatherd_idxs] = outs
699
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
700
+ dist.all_to_all(
701
+ list(gathered_tokens.split(input_split_sizes)),
702
+ list(new_x.split(output_splits)),
703
+ )
704
+ outs = gathered_tokens
705
+
706
+ new_x = torch.empty_like(outs)
707
+ new_x[idxs] = outs
708
+ final_out = (
709
+ new_x.view(*topk_ids.shape, -1)
710
+ .type(topk_weight.dtype)
711
+ .mul_(topk_weight.unsqueeze(dim=-1))
712
+ .sum(dim=1)
713
+ .type(new_x.dtype)
714
+ )
715
+ return final_out
716
+
717
+
718
+ def moe_train(self, x, topk_ids, topk_weight):
719
+ token_size, hidden_dim = x.shape # token_size = bsz_size * seq_len
720
+ final_hidden_states = torch.zeros(
721
+ (token_size, hidden_dim), dtype=x.dtype, device=x.device
722
+ )
723
+
724
+ # One hot encode the selected experts to create an expert mask
725
+ # this will be used to easily index which expert is going to be sollicitated
726
+ expert_mask = torch.nn.functional.one_hot(topk_ids, num_classes=self.config.n_routed_experts).permute(2, 1, 0)
727
+
728
+ # Loop over all available experts in the model and perform the computation on each expert
729
+ for expert_idx in range(self.config.n_routed_experts):
730
+ expert_layer = self.experts[expert_idx]
731
+ idx, top_x = torch.where(expert_mask[expert_idx])
732
+
733
+ # Index the correct hidden states and compute the expert hidden state for
734
+ # the current expert. We need to make sure to multiply the output hidden
735
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
736
+ current_state = x[None, top_x].reshape(-1, hidden_dim)
737
+ current_hidden_states = expert_layer(current_state) * topk_weight[top_x, idx, None]
738
+
739
+ # However `index_add_` only support torch tensors for indexing so we'll use
740
+ # the `top_x` tensor here.
741
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(x.dtype))
742
+
743
+ return final_hidden_states.view(-1, hidden_dim)
744
+
745
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
746
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
747
+ """
748
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
749
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
750
+ """
751
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
752
+ if n_rep == 1:
753
+ return hidden_states
754
+ hidden_states = hidden_states[:, :, None, :, :].expand(
755
+ batch, num_key_value_heads, n_rep, slen, head_dim
756
+ )
757
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
758
+
759
+
760
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
761
+ class DeepseekV3Attention(nn.Module):
762
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
763
+
764
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: Optional[int] = None):
765
+ super().__init__()
766
+ self.config = config
767
+ self.layer_idx = layer_idx
768
+ if layer_idx is None:
769
+ logger.warning_once(
770
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
771
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
772
+ "when creating this class."
773
+ )
774
+
775
+ self.attention_dropout = config.attention_dropout
776
+ self.hidden_size = config.hidden_size
777
+ self.num_heads = config.num_attention_heads
778
+
779
+ self.max_position_embeddings = config.max_position_embeddings
780
+ self.rope_theta = config.rope_theta
781
+ self.q_lora_rank = config.q_lora_rank
782
+ self.qk_rope_head_dim = config.qk_rope_head_dim
783
+ self.kv_lora_rank = config.kv_lora_rank
784
+ self.v_head_dim = config.v_head_dim
785
+ self.qk_nope_head_dim = config.qk_nope_head_dim
786
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
787
+
788
+ self.is_causal = True
789
+
790
+ if self.q_lora_rank is None:
791
+ self.q_proj = nn.Linear(
792
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
793
+ )
794
+ else:
795
+ self.q_a_proj = nn.Linear(
796
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
797
+ )
798
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
799
+ self.q_b_proj = nn.Linear(
800
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
801
+ )
802
+
803
+ self.kv_a_proj_with_mqa = nn.Linear(
804
+ self.hidden_size,
805
+ config.kv_lora_rank + config.qk_rope_head_dim,
806
+ bias=config.attention_bias,
807
+ )
808
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
809
+ self.kv_b_proj = nn.Linear(
810
+ config.kv_lora_rank,
811
+ self.num_heads
812
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
813
+ bias=False,
814
+ )
815
+
816
+ self.o_proj = nn.Linear(
817
+ self.num_heads * self.v_head_dim,
818
+ self.hidden_size,
819
+ bias=config.attention_bias,
820
+ )
821
+ self._init_rope()
822
+
823
+ self.softmax_scale = self.q_head_dim ** (-0.5)
824
+ if self.config.rope_scaling is not None:
825
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
826
+ scaling_factor = self.config.rope_scaling["factor"]
827
+ if mscale_all_dim:
828
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
829
+ self.softmax_scale = self.softmax_scale * mscale * mscale
830
+
831
+ def _init_rope(self):
832
+ if self.config.rope_scaling is None:
833
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
834
+ self.qk_rope_head_dim,
835
+ max_position_embeddings=self.max_position_embeddings,
836
+ base=self.rope_theta,
837
+ )
838
+ else:
839
+ scaling_type = self.config.rope_scaling["type"]
840
+ scaling_factor = self.config.rope_scaling["factor"]
841
+ if scaling_type == "linear":
842
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
843
+ self.qk_rope_head_dim,
844
+ max_position_embeddings=self.max_position_embeddings,
845
+ scaling_factor=scaling_factor,
846
+ base=self.rope_theta,
847
+ )
848
+ elif scaling_type == "dynamic":
849
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
850
+ self.qk_rope_head_dim,
851
+ max_position_embeddings=self.max_position_embeddings,
852
+ scaling_factor=scaling_factor,
853
+ base=self.rope_theta,
854
+ )
855
+ elif scaling_type == "yarn":
856
+ kwargs = {
857
+ key: self.config.rope_scaling[key]
858
+ for key in [
859
+ "original_max_position_embeddings",
860
+ "beta_fast",
861
+ "beta_slow",
862
+ "mscale",
863
+ "mscale_all_dim",
864
+ ]
865
+ if key in self.config.rope_scaling
866
+ }
867
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
868
+ self.qk_rope_head_dim,
869
+ max_position_embeddings=self.max_position_embeddings,
870
+ scaling_factor=scaling_factor,
871
+ base=self.rope_theta,
872
+ **kwargs,
873
+ )
874
+ else:
875
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
876
+
877
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
878
+ return (
879
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
880
+ .transpose(1, 2)
881
+ .contiguous()
882
+ )
883
+
884
+ def forward(
885
+ self,
886
+ hidden_states: torch.Tensor,
887
+ attention_mask: Optional[torch.Tensor] = None,
888
+ position_ids: Optional[torch.LongTensor] = None,
889
+ past_key_value: Optional[Cache] = None,
890
+ output_attentions: bool = False,
891
+ use_cache: bool = False,
892
+ **kwargs,
893
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
894
+ if "padding_mask" in kwargs:
895
+ warnings.warn(
896
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
897
+ )
898
+ bsz, q_len, _ = hidden_states.size()
899
+
900
+ if self.q_lora_rank is None:
901
+ q = self.q_proj(hidden_states)
902
+ else:
903
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
904
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
905
+ q_nope, q_pe = torch.split(
906
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
907
+ )
908
+
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
+ if past_key_value is not None:
925
+ if self.layer_idx is None:
926
+ raise ValueError(
927
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
928
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
929
+ "with a layer index."
930
+ )
931
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
932
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
933
+
934
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
935
+
936
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
937
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
938
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
939
+
940
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
941
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
942
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
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
+ attn_weights = (
950
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
951
+ )
952
+
953
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
954
+ raise ValueError(
955
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
956
+ f" {attn_weights.size()}"
957
+ )
958
+ assert attention_mask is not None
959
+ if attention_mask is not None:
960
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
961
+ raise ValueError(
962
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
963
+ )
964
+ attn_weights = attn_weights + attention_mask
965
+
966
+ # upcast attention to fp32
967
+ attn_weights = nn.functional.softmax(
968
+ attn_weights, dim=-1, dtype=torch.float32
969
+ ).to(query_states.dtype)
970
+ attn_weights = nn.functional.dropout(
971
+ attn_weights, p=self.attention_dropout, training=self.training
972
+ )
973
+ attn_output = torch.matmul(attn_weights, value_states)
974
+
975
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
976
+ raise ValueError(
977
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
978
+ f" {attn_output.size()}"
979
+ )
980
+
981
+ attn_output = attn_output.transpose(1, 2).contiguous()
982
+
983
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
984
+
985
+ attn_output = self.o_proj(attn_output)
986
+
987
+ if not output_attentions:
988
+ attn_weights = None
989
+
990
+ return attn_output, attn_weights, past_key_value
991
+
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
994
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
995
+ """
996
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
997
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
998
+ flash attention and deal with padding tokens in case the input contains any of them.
999
+ """
1000
+
1001
+ def __init__(self, *args, **kwargs):
1002
+ super().__init__(*args, **kwargs)
1003
+
1004
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1005
+ # 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.
1006
+ # 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).
1007
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1008
+
1009
+ def forward(
1010
+ self,
1011
+ hidden_states: torch.Tensor,
1012
+ attention_mask: Optional[torch.LongTensor] = None,
1013
+ position_ids: Optional[torch.LongTensor] = None,
1014
+ past_key_value: Optional[Cache] = None,
1015
+ output_attentions: bool = False,
1016
+ use_cache: bool = False,
1017
+ **kwargs,
1018
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1019
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1020
+ if "padding_mask" in kwargs:
1021
+ warnings.warn(
1022
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1023
+ )
1024
+
1025
+ # overwrite attention_mask with padding_mask
1026
+ attention_mask = kwargs.pop("padding_mask")
1027
+
1028
+ output_attentions = False
1029
+
1030
+ bsz, q_len, _ = hidden_states.size()
1031
+
1032
+ if self.q_lora_rank is None:
1033
+ q = self.q_proj(hidden_states)
1034
+ else:
1035
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1036
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1037
+ q_nope, q_pe = torch.split(
1038
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1039
+ )
1040
+
1041
+ # Flash attention requires the input to have the shape
1042
+ # batch_size x seq_length x head_dim x hidden_dim
1043
+ # therefore we just need to keep the original shape
1044
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1045
+ compressed_kv, k_pe = torch.split(
1046
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1047
+ )
1048
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1049
+ kv = (
1050
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1051
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1052
+ .transpose(1, 2)
1053
+ )
1054
+
1055
+ k_nope, value_states = torch.split(
1056
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1057
+ )
1058
+ kv_seq_len = value_states.shape[-2]
1059
+
1060
+ kv_seq_len = value_states.shape[-2]
1061
+ if past_key_value is not None:
1062
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1063
+
1064
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1065
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1066
+
1067
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1068
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1069
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1070
+
1071
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1072
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1073
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1074
+
1075
+ if self.q_head_dim != self.v_head_dim:
1076
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1077
+
1078
+ if past_key_value is not None:
1079
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1080
+ key_states, value_states = past_key_value.update(
1081
+ key_states, value_states, self.layer_idx, cache_kwargs
1082
+ )
1083
+
1084
+ # 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
1085
+ # to be able to avoid many of these transpose/reshape/view.
1086
+ query_states = query_states.transpose(1, 2)
1087
+ key_states = key_states.transpose(1, 2)
1088
+ value_states = value_states.transpose(1, 2)
1089
+
1090
+ dropout_rate = self.attention_dropout if self.training else 0.0
1091
+
1092
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1093
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1094
+ # cast them back in the correct dtype just to be sure everything works as expected.
1095
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1096
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1097
+
1098
+ input_dtype = query_states.dtype
1099
+ if input_dtype == torch.float32:
1100
+ # Handle the case where the model is quantized
1101
+ if hasattr(self.config, "_pre_quantization_dtype"):
1102
+ target_dtype = self.config._pre_quantization_dtype
1103
+ elif torch.is_autocast_enabled():
1104
+ target_dtype = torch.get_autocast_gpu_dtype()
1105
+ else:
1106
+ target_dtype = (
1107
+ self.q_proj.weight.dtype
1108
+ if self.q_lora_rank is None
1109
+ else self.q_a_proj.weight.dtype
1110
+ )
1111
+
1112
+ logger.warning_once(
1113
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1114
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1115
+ f" {target_dtype}."
1116
+ )
1117
+
1118
+ query_states = query_states.to(target_dtype)
1119
+ key_states = key_states.to(target_dtype)
1120
+ value_states = value_states.to(target_dtype)
1121
+
1122
+ attn_output = self._flash_attention_forward(
1123
+ query_states,
1124
+ key_states,
1125
+ value_states,
1126
+ attention_mask,
1127
+ q_len,
1128
+ dropout=dropout_rate,
1129
+ softmax_scale=self.softmax_scale,
1130
+ )
1131
+ if self.q_head_dim != self.v_head_dim:
1132
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1133
+
1134
+ attn_output = attn_output.reshape(
1135
+ bsz, q_len, self.num_heads * self.v_head_dim
1136
+ ).contiguous()
1137
+ attn_output = self.o_proj(attn_output)
1138
+
1139
+ if not output_attentions:
1140
+ attn_weights = None
1141
+
1142
+ return attn_output, attn_weights, past_key_value
1143
+
1144
+ def _flash_attention_forward(
1145
+ self,
1146
+ query_states,
1147
+ key_states,
1148
+ value_states,
1149
+ attention_mask,
1150
+ query_length,
1151
+ dropout=0.0,
1152
+ softmax_scale=None,
1153
+ ):
1154
+ """
1155
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1156
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1157
+
1158
+ Args:
1159
+ query_states (`torch.Tensor`):
1160
+ Input query states to be passed to Flash Attention API
1161
+ key_states (`torch.Tensor`):
1162
+ Input key states to be passed to Flash Attention API
1163
+ value_states (`torch.Tensor`):
1164
+ Input value states to be passed to Flash Attention API
1165
+ attention_mask (`torch.Tensor`):
1166
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1167
+ position of padding tokens and 1 for the position of non-padding tokens.
1168
+ dropout (`int`, *optional*):
1169
+ Attention dropout
1170
+ softmax_scale (`float`, *optional*):
1171
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1172
+ """
1173
+ if not self._flash_attn_uses_top_left_mask:
1174
+ causal = self.is_causal
1175
+ else:
1176
+ # 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__.
1177
+ causal = self.is_causal and query_length != 1
1178
+
1179
+ # Contains at least one padding token in the sequence
1180
+ if attention_mask is not None:
1181
+ batch_size = query_states.shape[0]
1182
+ (
1183
+ query_states,
1184
+ key_states,
1185
+ value_states,
1186
+ indices_q,
1187
+ cu_seq_lens,
1188
+ max_seq_lens,
1189
+ ) = self._upad_input(
1190
+ query_states, key_states, value_states, attention_mask, query_length
1191
+ )
1192
+
1193
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1194
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1195
+
1196
+ attn_output_unpad = flash_attn_varlen_func(
1197
+ query_states,
1198
+ key_states,
1199
+ value_states,
1200
+ cu_seqlens_q=cu_seqlens_q,
1201
+ cu_seqlens_k=cu_seqlens_k,
1202
+ max_seqlen_q=max_seqlen_in_batch_q,
1203
+ max_seqlen_k=max_seqlen_in_batch_k,
1204
+ dropout_p=dropout,
1205
+ softmax_scale=softmax_scale,
1206
+ causal=causal,
1207
+ )
1208
+
1209
+ attn_output = pad_input(
1210
+ attn_output_unpad, indices_q, batch_size, query_length
1211
+ )
1212
+ else:
1213
+ attn_output = flash_attn_func(
1214
+ query_states,
1215
+ key_states,
1216
+ value_states,
1217
+ dropout,
1218
+ softmax_scale=softmax_scale,
1219
+ causal=causal,
1220
+ )
1221
+
1222
+ return attn_output
1223
+
1224
+ def _upad_input(
1225
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1226
+ ):
1227
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1228
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1229
+
1230
+ key_layer = index_first_axis(
1231
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1232
+ indices_k,
1233
+ )
1234
+ value_layer = index_first_axis(
1235
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1236
+ indices_k,
1237
+ )
1238
+ if query_length == kv_seq_len:
1239
+ query_layer = index_first_axis(
1240
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1241
+ indices_k,
1242
+ )
1243
+ cu_seqlens_q = cu_seqlens_k
1244
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1245
+ indices_q = indices_k
1246
+ elif query_length == 1:
1247
+ max_seqlen_in_batch_q = 1
1248
+ cu_seqlens_q = torch.arange(
1249
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1250
+ ) # There is a memcpy here, that is very bad.
1251
+ indices_q = cu_seqlens_q[:-1]
1252
+ query_layer = query_layer.squeeze(1)
1253
+ else:
1254
+ # The -q_len: slice assumes left padding.
1255
+ attention_mask = attention_mask[:, -query_length:]
1256
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1257
+ query_layer, attention_mask
1258
+ )
1259
+
1260
+ return (
1261
+ query_layer,
1262
+ key_layer,
1263
+ value_layer,
1264
+ indices_q,
1265
+ (cu_seqlens_q, cu_seqlens_k),
1266
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1267
+ )
1268
+
1269
+
1270
+ ATTENTION_CLASSES = {
1271
+ "eager": DeepseekV3Attention,
1272
+ "flash_attention_2": DeepseekV3FlashAttention2,
1273
+ }
1274
+
1275
+
1276
+ class DeepseekV3DecoderLayer(nn.Module):
1277
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: int):
1278
+ super().__init__()
1279
+ self.hidden_size = config.hidden_size
1280
+
1281
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1282
+ config=config, layer_idx=layer_idx
1283
+ )
1284
+
1285
+ self.mlp = (
1286
+ TinyDeepseekV3MoE(config)
1287
+ if (
1288
+ config.n_routed_experts is not None
1289
+ and layer_idx >= config.first_k_dense_replace
1290
+ and layer_idx % config.moe_layer_freq == 0
1291
+ )
1292
+ else DeepseekV3MLP(config)
1293
+ )
1294
+ self.input_layernorm = DeepseekV3RMSNorm(
1295
+ config.hidden_size, eps=config.rms_norm_eps
1296
+ )
1297
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1298
+ config.hidden_size, eps=config.rms_norm_eps
1299
+ )
1300
+
1301
+ def forward(
1302
+ self,
1303
+ hidden_states: torch.Tensor,
1304
+ attention_mask: Optional[torch.Tensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1307
+ output_attentions: Optional[bool] = False,
1308
+ output_router_logits: Optional[bool] = False,
1309
+ use_cache: Optional[bool] = False,
1310
+ **kwargs,
1311
+ ) -> Tuple[
1312
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1313
+ ]:
1314
+ """
1315
+ Args:
1316
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1317
+ attention_mask (`torch.FloatTensor`, *optional*):
1318
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1319
+ query_sequence_length, key_sequence_length)` if default attention is used.
1320
+ output_attentions (`bool`, *optional*):
1321
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1322
+ returned tensors for more detail.
1323
+ use_cache (`bool`, *optional*):
1324
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1325
+ (see `past_key_values`).
1326
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1327
+ """
1328
+ if "padding_mask" in kwargs:
1329
+ warnings.warn(
1330
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1331
+ )
1332
+ residual = hidden_states
1333
+
1334
+ hidden_states = self.input_layernorm(hidden_states)
1335
+
1336
+ # Self Attention
1337
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1338
+ hidden_states=hidden_states,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_value=past_key_value,
1342
+ output_attentions=output_attentions,
1343
+ use_cache=use_cache,
1344
+ **kwargs,
1345
+ )
1346
+ hidden_states = residual + hidden_states
1347
+
1348
+ # Fully Connected
1349
+ residual = hidden_states
1350
+ hidden_states = self.post_attention_layernorm(hidden_states)
1351
+ hidden_states = self.mlp(hidden_states)
1352
+ if isinstance(hidden_states, tuple):
1353
+ hidden_states, router_scores = hidden_states
1354
+ else:
1355
+ router_scores = None
1356
+ hidden_states = residual + hidden_states
1357
+
1358
+ outputs = (hidden_states,)
1359
+
1360
+ if output_attentions:
1361
+ outputs += (self_attn_weights,)
1362
+
1363
+ if use_cache:
1364
+ outputs += (present_key_value,)
1365
+
1366
+ if output_router_logits:
1367
+ outputs += (router_scores, )
1368
+
1369
+ return outputs
1370
+
1371
+
1372
+ DeepseekV3_START_DOCSTRING = r"""
1373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1375
+ etc.)
1376
+
1377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1379
+ and behavior.
1380
+
1381
+ Parameters:
1382
+ config ([`TinyDeepseekV3Config`]):
1383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1384
+ load the weights associated with the model, only the configuration. Check out the
1385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1386
+ """
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1391
+ DeepseekV3_START_DOCSTRING,
1392
+ )
1393
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1394
+ config_class = TinyDeepseekV3Config
1395
+ base_model_prefix = "model"
1396
+ supports_gradient_checkpointing = True
1397
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1398
+ _skip_keys_device_placement = "past_key_values"
1399
+ _supports_flash_attn_2 = True
1400
+ _supports_cache_class = True
1401
+
1402
+ def _init_weights(self, module):
1403
+ std = self.config.initializer_range
1404
+ if isinstance(module, nn.Linear):
1405
+ module.weight.data.normal_(mean=0.0, std=std)
1406
+ if module.bias is not None:
1407
+ module.bias.data.zero_()
1408
+ elif isinstance(module, nn.Embedding):
1409
+ module.weight.data.normal_(mean=0.0, std=std)
1410
+ if module.padding_idx is not None:
1411
+ module.weight.data[module.padding_idx].zero_()
1412
+
1413
+
1414
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1415
+ Args:
1416
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1417
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1418
+ it.
1419
+
1420
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1421
+ [`PreTrainedTokenizer.__call__`] for details.
1422
+
1423
+ [What are input IDs?](../glossary#input-ids)
1424
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1425
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1426
+
1427
+ - 1 for tokens that are **not masked**,
1428
+ - 0 for tokens that are **masked**.
1429
+
1430
+ [What are attention masks?](../glossary#attention-mask)
1431
+
1432
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1433
+ [`PreTrainedTokenizer.__call__`] for details.
1434
+
1435
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1436
+ `past_key_values`).
1437
+
1438
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1439
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1440
+ information on the default strategy.
1441
+
1442
+ - 1 indicates the head is **not masked**,
1443
+ - 0 indicates the head is **masked**.
1444
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1446
+ config.n_positions - 1]`.
1447
+
1448
+ [What are position IDs?](../glossary#position-ids)
1449
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1450
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1451
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1452
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1453
+
1454
+ Two formats are allowed:
1455
+ - a [`~cache_utils.Cache`] instance;
1456
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1457
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1458
+ cache format.
1459
+
1460
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1461
+ legacy cache format will be returned.
1462
+
1463
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1464
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1465
+ of shape `(batch_size, sequence_length)`.
1466
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1467
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1468
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1469
+ model's internal embedding lookup matrix.
1470
+ use_cache (`bool`, *optional*):
1471
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1472
+ `past_key_values`).
1473
+ output_attentions (`bool`, *optional*):
1474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1475
+ tensors for more detail.
1476
+ output_hidden_states (`bool`, *optional*):
1477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1478
+ more detail.
1479
+ return_dict (`bool`, *optional*):
1480
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1481
+ """
1482
+
1483
+
1484
+ @add_start_docstrings(
1485
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1486
+ DeepseekV3_START_DOCSTRING,
1487
+ )
1488
+ class TinyDeepseekV3Model(DeepseekV3PreTrainedModel):
1489
+ """
1490
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1491
+
1492
+ Args:
1493
+ config: TinyDeepseekV3Config
1494
+ """
1495
+
1496
+ def __init__(self, config: TinyDeepseekV3Config):
1497
+ super().__init__(config)
1498
+ self.padding_idx = config.pad_token_id
1499
+ self.vocab_size = config.vocab_size
1500
+
1501
+ self.n_future_tokens = config.n_future_tokens
1502
+ assert self.n_future_tokens > 0, "At least one future token prediction needed, i.e., n_future_tokens>0"
1503
+ assert config.num_hidden_layers > self.n_future_tokens, "The number of layer should larger than the n_future_tokens, i.e., config.num_hidden_layers > config.n_future_tokens"
1504
+
1505
+ self.embed_tokens = nn.Embedding(
1506
+ config.vocab_size, config.hidden_size, self.padding_idx
1507
+ )
1508
+ self.layers = nn.ModuleList(
1509
+ [
1510
+ DeepseekV3DecoderLayer(config, layer_idx)
1511
+ for layer_idx in range(config.num_hidden_layers - self.n_future_tokens + 1)
1512
+ ]
1513
+ )
1514
+
1515
+ # Additional prediction heads for multi-token prediction.
1516
+ # `layer_id` counts contiguously from the first Transformer block.
1517
+ self.extra_heads = nn.ModuleList(
1518
+ [
1519
+ DeepseekV3DecoderLayer(config, len(self.layers) + layer_idx)
1520
+ for layer_idx in range(self.n_future_tokens - 1)
1521
+ ]
1522
+ )
1523
+ self.extra_heads_input_norms = nn.ModuleList(
1524
+ [
1525
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1526
+ for _ in range(self.n_future_tokens - 1)
1527
+ ]
1528
+ )
1529
+ self.extra_heads_hidden_norms = nn.ModuleList(
1530
+ [
1531
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1532
+ for _ in range(self.n_future_tokens - 1)
1533
+ ]
1534
+ )
1535
+ self.extra_heads_projections = nn.ModuleList(
1536
+ [
1537
+ nn.Linear(config.hidden_size*2, config.hidden_size, bias=False)
1538
+ for _ in range(self.n_future_tokens - 1)
1539
+ ]
1540
+ )
1541
+
1542
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1543
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1544
+
1545
+ self.gradient_checkpointing = False
1546
+ # Initialize weights and apply final processing
1547
+ self.post_init()
1548
+
1549
+ def get_input_embeddings(self):
1550
+ return self.embed_tokens
1551
+
1552
+ def set_input_embeddings(self, value):
1553
+ self.embed_tokens = value
1554
+
1555
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1556
+ def forward(
1557
+ self,
1558
+ input_ids: torch.LongTensor = None,
1559
+ attention_mask: Optional[torch.Tensor] = None,
1560
+ position_ids: Optional[torch.LongTensor] = None,
1561
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1562
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1563
+ use_cache: Optional[bool] = None,
1564
+ output_attentions: Optional[bool] = None,
1565
+ output_hidden_states: Optional[bool] = None,
1566
+ output_router_logits: Optional[bool] = None,
1567
+ return_dict: Optional[bool] = None,
1568
+ return_all_heads: Optional[bool] = False,
1569
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1570
+ output_attentions = (
1571
+ output_attentions
1572
+ if output_attentions is not None
1573
+ else self.config.output_attentions
1574
+ )
1575
+ output_router_logits = (
1576
+ output_router_logits
1577
+ if output_router_logits is not None
1578
+ else self.config.output_router_logits
1579
+ )
1580
+ output_hidden_states = (
1581
+ output_hidden_states
1582
+ if output_hidden_states is not None
1583
+ else self.config.output_hidden_states
1584
+ )
1585
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1586
+
1587
+ return_dict = (
1588
+ return_dict if return_dict is not None else self.config.use_return_dict
1589
+ )
1590
+
1591
+ # retrieve input_ids and inputs_embeds
1592
+ if input_ids is not None and inputs_embeds is not None:
1593
+ raise ValueError(
1594
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1595
+ )
1596
+ elif input_ids is not None:
1597
+ batch_size, seq_length = input_ids.shape[:2]
1598
+ elif inputs_embeds is not None:
1599
+ batch_size, seq_length = inputs_embeds.shape[:2]
1600
+ else:
1601
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1602
+
1603
+ past_key_values_length = 0
1604
+ if use_cache:
1605
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1606
+ if use_legacy_cache:
1607
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1608
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1609
+
1610
+ if position_ids is None:
1611
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1612
+ position_ids = torch.arange(
1613
+ past_key_values_length,
1614
+ seq_length + past_key_values_length,
1615
+ dtype=torch.long,
1616
+ device=device,
1617
+ )
1618
+ position_ids = position_ids.unsqueeze(0)
1619
+
1620
+ if inputs_embeds is None:
1621
+ inputs_embeds = self.embed_tokens(input_ids)
1622
+
1623
+ if self._use_flash_attention_2:
1624
+ # 2d mask is passed through the layers
1625
+ attention_mask = (
1626
+ attention_mask
1627
+ if (attention_mask is not None and 0 in attention_mask)
1628
+ else None
1629
+ )
1630
+ else:
1631
+ # 4d mask is passed through the layers
1632
+ attention_mask = _prepare_4d_causal_attention_mask(
1633
+ attention_mask,
1634
+ (batch_size, seq_length),
1635
+ inputs_embeds,
1636
+ past_key_values_length,
1637
+ )
1638
+
1639
+ # embed positions
1640
+ hidden_states = inputs_embeds
1641
+
1642
+ # decoder layers
1643
+ all_hidden_states = () if output_hidden_states or return_all_heads else None
1644
+ all_self_attns = () if output_attentions else None
1645
+ all_router_logits = () if output_router_logits else None
1646
+ next_decoder_cache = None
1647
+
1648
+ # layers = self.layers if not return_all_heads else self.layers + self.extra_heads
1649
+ for decoder_layer in self.layers:
1650
+ if output_hidden_states:
1651
+ all_hidden_states += (hidden_states,)
1652
+
1653
+ layer_outputs = decoder_layer(
1654
+ hidden_states,
1655
+ attention_mask=attention_mask,
1656
+ position_ids=position_ids,
1657
+ past_key_value=past_key_values,
1658
+ output_attentions=output_attentions,
1659
+ output_router_logits=output_router_logits,
1660
+ use_cache=use_cache,
1661
+ )
1662
+
1663
+ hidden_states = layer_outputs[0]
1664
+
1665
+ if use_cache:
1666
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1667
+
1668
+ if output_attentions:
1669
+ all_self_attns += (layer_outputs[1],)
1670
+
1671
+ if output_router_logits and layer_outputs[-1] is not None:
1672
+ all_router_logits += (layer_outputs[-1],)
1673
+
1674
+ # Multi-token prediction
1675
+ if return_all_heads:
1676
+ first_token_hidden_state = self.norm(hidden_states) # first next token prediction
1677
+
1678
+ all_hidden_states += (first_token_hidden_state,)
1679
+
1680
+ for extra_head_idx in range(len(self.extra_heads)):
1681
+ hidden_states = torch.cat(
1682
+ (self.extra_heads_input_norms[extra_head_idx](inputs_embeds),
1683
+ self.extra_heads_hidden_norms[extra_head_idx](hidden_states)),
1684
+ dim=-1
1685
+ ) # (bsz, seq_len, dim*2)
1686
+
1687
+ hidden_states = self.extra_heads_projections[extra_head_idx](hidden_states)
1688
+ # (bsz, seq_len, dim)
1689
+
1690
+ layer_outputs = self.extra_heads[extra_head_idx](
1691
+ hidden_states,
1692
+ attention_mask=attention_mask,
1693
+ position_ids=position_ids,
1694
+ past_key_value=past_key_values,
1695
+ output_attentions=output_attentions,
1696
+ use_cache=use_cache,
1697
+ )
1698
+
1699
+ hidden_states = layer_outputs[0]
1700
+
1701
+ if use_cache:
1702
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1703
+
1704
+ if output_attentions:
1705
+ all_self_attns += (layer_outputs[1],)
1706
+
1707
+ # always return extra_head hidden_states with norm
1708
+ all_hidden_states += (self.norm(hidden_states),)
1709
+
1710
+ hidden_states = first_token_hidden_state
1711
+
1712
+ else:
1713
+ hidden_states = self.norm(hidden_states)
1714
+
1715
+ # add hidden states from the last decoder layer
1716
+ if output_hidden_states:
1717
+ all_hidden_states += (hidden_states,)
1718
+
1719
+ next_cache = None
1720
+ if use_cache:
1721
+ next_cache = (
1722
+ next_decoder_cache.to_legacy_cache()
1723
+ if use_legacy_cache
1724
+ else next_decoder_cache
1725
+ )
1726
+ if not return_dict:
1727
+ return tuple(
1728
+ v
1729
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1730
+ if v is not None
1731
+ )
1732
+ return MoeModelOutputWithPast(
1733
+ last_hidden_state=hidden_states,
1734
+ past_key_values=next_cache,
1735
+ hidden_states=all_hidden_states,
1736
+ attentions=all_self_attns,
1737
+ router_logits=all_router_logits
1738
+ )
1739
+
1740
+
1741
+ class TinyDeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1742
+ _tied_weights_keys = ["lm_head.weight"]
1743
+
1744
+ def __init__(self, config):
1745
+ super().__init__(config)
1746
+ self.model = TinyDeepseekV3Model(config)
1747
+ self.vocab_size = config.vocab_size
1748
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1749
+ self.n_future_tokens = config.n_future_tokens
1750
+ self.mtp_loss_lambda = config.mtp_loss_lambda
1751
+
1752
+ self.seq_aux = config.seq_aux
1753
+ self.aux_loss_alpha = config.aux_loss_alpha
1754
+ self.n_routed_experts = config.n_routed_experts
1755
+ self.num_experts_per_tok = config.num_experts_per_tok
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ output_router_logits: Optional[bool] = None,
1794
+ return_dict: Optional[bool] = None,
1795
+ return_all_heads: Optional[bool] = False,
1796
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1797
+ r"""
1798
+ Args:
1799
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1800
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1801
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1802
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1803
+
1804
+ Returns:
1805
+
1806
+ Example:
1807
+
1808
+ ```python
1809
+ >>> from transformers import AutoTokenizer, TinyDeepseekV3ForCausalLM
1810
+
1811
+ >>> model = TinyDeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1812
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1813
+
1814
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1815
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1816
+
1817
+ >>> # Generate
1818
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1819
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1820
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1821
+ ```"""
1822
+ output_attentions = (
1823
+ output_attentions
1824
+ if output_attentions is not None
1825
+ else self.config.output_attentions
1826
+ )
1827
+ output_router_logits = (
1828
+ output_router_logits
1829
+ if output_router_logits is not None
1830
+ else self.config.output_router_logits
1831
+ )
1832
+ output_hidden_states = (
1833
+ output_hidden_states
1834
+ if output_hidden_states is not None
1835
+ else self.config.output_hidden_states
1836
+ )
1837
+ return_dict = (
1838
+ return_dict if return_dict is not None else self.config.use_return_dict
1839
+ )
1840
+
1841
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1842
+ outputs = self.model(
1843
+ input_ids=input_ids,
1844
+ attention_mask=attention_mask,
1845
+ position_ids=position_ids,
1846
+ past_key_values=past_key_values,
1847
+ inputs_embeds=inputs_embeds,
1848
+ use_cache=use_cache,
1849
+ output_attentions=output_attentions,
1850
+ output_hidden_states=output_hidden_states,
1851
+ output_router_logits=output_router_logits or self.seq_aux,
1852
+ return_dict=return_dict,
1853
+ return_all_heads=return_all_heads,
1854
+ )
1855
+
1856
+ if not return_all_heads:
1857
+ hidden_states = outputs[0]
1858
+ logits = self.lm_head(hidden_states)
1859
+ logits = logits.float()
1860
+
1861
+ loss = None
1862
+ if labels is not None:
1863
+ # Shift so that tokens < n predict n
1864
+ shift_logits = logits[..., :-1, :].contiguous()
1865
+ shift_labels = labels[..., 1:].contiguous()
1866
+ # Flatten the tokens
1867
+ loss_fct = CrossEntropyLoss()
1868
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1869
+ shift_labels = shift_labels.view(-1)
1870
+ # Enable model parallelism
1871
+ shift_labels = shift_labels.to(shift_logits.device)
1872
+ loss = loss_fct(shift_logits, shift_labels)
1873
+ else:
1874
+ # Multi-token prediction
1875
+ mtp_hidden_states = outputs[2][-self.n_future_tokens:]
1876
+ first_token_loss = None
1877
+ mtp_loss = None
1878
+ loss = None
1879
+
1880
+ add_loss = lambda x, y: y if x is None else x+y
1881
+
1882
+ for token_idx in range(self.n_future_tokens):
1883
+ logits = self.lm_head(mtp_hidden_states[token_idx])
1884
+ logits = logits.float()
1885
+
1886
+ if labels is not None:
1887
+ n_shift = token_idx + 1
1888
+ if n_shift > (logits.shape[1]-1):
1889
+ continue
1890
+
1891
+ # Shift so that tokens < n predict n
1892
+ shift_logits = logits[..., :-n_shift, :].contiguous()
1893
+ shift_labels = labels[..., n_shift:].contiguous()
1894
+ # Flatten the tokens
1895
+ loss_fct = CrossEntropyLoss()
1896
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1897
+ shift_labels = shift_labels.view(-1)
1898
+ # Enable model parallelism
1899
+ shift_labels = shift_labels.to(shift_logits.device)
1900
+
1901
+ loss = add_loss(loss, loss_fct(shift_logits, shift_labels))
1902
+
1903
+ if token_idx == 0:
1904
+ first_token_loss = add_loss(first_token_loss, loss)
1905
+ else:
1906
+ mtp_loss = add_loss(mtp_loss, loss)
1907
+
1908
+ if labels is not None:
1909
+ loss = first_token_loss + self.mtp_loss_lambda * mtp_loss / (self.n_future_tokens - 1)
1910
+ # ljh Loss debug
1911
+ # print(f"loss: {loss} first_token_loss: {first_token_loss}, mtp_loss: {mtp_loss} with n_future_tokens {self.n_future_tokens} and mtp_loss_lambda {self.mtp_loss_lambda}")
1912
+
1913
+
1914
+ # balancing loss
1915
+ aux_loss = None
1916
+ if self.seq_aux:
1917
+ aux_loss = load_balancing_loss_func(
1918
+ gate_logits=outputs.router_logits if return_dict else outputs[-1],
1919
+ num_experts=self.n_routed_experts,
1920
+ top_k=self.num_experts_per_tok,
1921
+ attention_mask=attention_mask,
1922
+ )
1923
+ aux_loss = self.aux_loss_alpha * aux_loss
1924
+ # ljh Loss debug
1925
+ # print(f"loss: {loss}, aux_loss: {aux_loss}")
1926
+ if labels is not None:
1927
+ loss += aux_loss.to(loss.device) # make sure to reside in the same device
1928
+
1929
+ if not return_dict:
1930
+ output = (logits,) + outputs[1:]
1931
+ if output_router_logits:
1932
+ output = (aux_loss,) + output
1933
+ return (loss,) + output if loss is not None else output
1934
+
1935
+ return MoeCausalLMOutputWithPast(
1936
+ loss=loss,
1937
+ logits=logits,
1938
+ past_key_values=outputs.past_key_values,
1939
+ hidden_states=outputs.hidden_states,
1940
+ attentions=outputs.attentions,
1941
+ router_logits=outputs.router_logits
1942
+ )
1943
+
1944
+ def prepare_inputs_for_generation(
1945
+ self,
1946
+ input_ids,
1947
+ past_key_values=None,
1948
+ attention_mask=None,
1949
+ inputs_embeds=None,
1950
+ **kwargs,
1951
+ ):
1952
+ if past_key_values is not None:
1953
+ if isinstance(past_key_values, Cache):
1954
+ cache_length = past_key_values.get_seq_length()
1955
+ past_length = past_key_values.seen_tokens
1956
+ max_cache_length = past_key_values.get_max_length()
1957
+ else:
1958
+ cache_length = past_length = past_key_values[0][0].shape[2]
1959
+ max_cache_length = None
1960
+
1961
+ # Keep only the unprocessed tokens:
1962
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1963
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1964
+ # input)
1965
+ if (
1966
+ attention_mask is not None
1967
+ and attention_mask.shape[1] > input_ids.shape[1]
1968
+ ):
1969
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1970
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1971
+ # input_ids based on the past_length.
1972
+ elif past_length < input_ids.shape[1]:
1973
+ input_ids = input_ids[:, past_length:]
1974
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1975
+
1976
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1977
+ if (
1978
+ max_cache_length is not None
1979
+ and attention_mask is not None
1980
+ and cache_length + input_ids.shape[1] > max_cache_length
1981
+ ):
1982
+ attention_mask = attention_mask[:, -max_cache_length:]
1983
+
1984
+ position_ids = kwargs.get("position_ids", None)
1985
+ if attention_mask is not None and position_ids is None:
1986
+ # create position_ids on the fly for batch generation
1987
+ position_ids = attention_mask.long().cumsum(-1) - 1
1988
+ position_ids.masked_fill_(attention_mask == 0, 1)
1989
+ if past_key_values:
1990
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1991
+
1992
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1993
+ if inputs_embeds is not None and past_key_values is None:
1994
+ model_inputs = {"inputs_embeds": inputs_embeds}
1995
+ else:
1996
+ model_inputs = {"input_ids": input_ids}
1997
+
1998
+ model_inputs.update(
1999
+ {
2000
+ "position_ids": position_ids,
2001
+ "past_key_values": past_key_values,
2002
+ "use_cache": kwargs.get("use_cache"),
2003
+ "attention_mask": attention_mask,
2004
+ }
2005
+ )
2006
+ return model_inputs
2007
+
2008
+ @staticmethod
2009
+ def _reorder_cache(past_key_values, beam_idx):
2010
+ reordered_past = ()
2011
+ for layer_past in past_key_values:
2012
+ reordered_past += (
2013
+ tuple(
2014
+ past_state.index_select(0, beam_idx.to(past_state.device))
2015
+ for past_state in layer_past
2016
+ ),
2017
+ )
2018
+ return reordered_past
2019
+
2020
+
2021
+ @add_start_docstrings(
2022
+ """
2023
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
2024
+
2025
+ [`TinyDeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2026
+ (e.g. GPT-2) do.
2027
+
2028
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2029
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2030
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2031
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2032
+ each row of the batch).
2033
+ """,
2034
+ DeepseekV3_START_DOCSTRING,
2035
+ )
2036
+ class TinyDeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
2037
+ def __init__(self, config):
2038
+ super().__init__(config)
2039
+ self.num_labels = config.num_labels
2040
+ self.model = TinyDeepseekV3Model(config)
2041
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2042
+
2043
+ # Initialize weights and apply final processing
2044
+ self.post_init()
2045
+
2046
+ def get_input_embeddings(self):
2047
+ return self.model.embed_tokens
2048
+
2049
+ def set_input_embeddings(self, value):
2050
+ self.model.embed_tokens = value
2051
+
2052
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
2053
+ def forward(
2054
+ self,
2055
+ input_ids: torch.LongTensor = None,
2056
+ attention_mask: Optional[torch.Tensor] = None,
2057
+ position_ids: Optional[torch.LongTensor] = None,
2058
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2059
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2060
+ labels: Optional[torch.LongTensor] = None,
2061
+ use_cache: Optional[bool] = None,
2062
+ output_attentions: Optional[bool] = None,
2063
+ output_hidden_states: Optional[bool] = None,
2064
+ return_dict: Optional[bool] = None,
2065
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2066
+ r"""
2067
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2068
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2069
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2070
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2071
+ """
2072
+ return_dict = (
2073
+ return_dict if return_dict is not None else self.config.use_return_dict
2074
+ )
2075
+
2076
+ transformer_outputs = self.model(
2077
+ input_ids,
2078
+ attention_mask=attention_mask,
2079
+ position_ids=position_ids,
2080
+ past_key_values=past_key_values,
2081
+ inputs_embeds=inputs_embeds,
2082
+ use_cache=use_cache,
2083
+ output_attentions=output_attentions,
2084
+ output_hidden_states=output_hidden_states,
2085
+ return_dict=return_dict,
2086
+ )
2087
+ hidden_states = transformer_outputs[0]
2088
+ logits = self.score(hidden_states)
2089
+
2090
+ if input_ids is not None:
2091
+ batch_size = input_ids.shape[0]
2092
+ else:
2093
+ batch_size = inputs_embeds.shape[0]
2094
+
2095
+ if self.config.pad_token_id is None and batch_size != 1:
2096
+ raise ValueError(
2097
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2098
+ )
2099
+ if self.config.pad_token_id is None:
2100
+ sequence_lengths = -1
2101
+ else:
2102
+ if input_ids is not None:
2103
+ sequence_lengths = (
2104
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2105
+ ).to(logits.device)
2106
+ else:
2107
+ sequence_lengths = -1
2108
+
2109
+ pooled_logits = logits[
2110
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2111
+ ]
2112
+
2113
+ loss = None
2114
+ if labels is not None:
2115
+ labels = labels.to(logits.device)
2116
+ if self.config.problem_type is None:
2117
+ if self.num_labels == 1:
2118
+ self.config.problem_type = "regression"
2119
+ elif self.num_labels > 1 and (
2120
+ labels.dtype == torch.long or labels.dtype == torch.int
2121
+ ):
2122
+ self.config.problem_type = "single_label_classification"
2123
+ else:
2124
+ self.config.problem_type = "multi_label_classification"
2125
+
2126
+ if self.config.problem_type == "regression":
2127
+ loss_fct = MSELoss()
2128
+ if self.num_labels == 1:
2129
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2130
+ else:
2131
+ loss = loss_fct(pooled_logits, labels)
2132
+ elif self.config.problem_type == "single_label_classification":
2133
+ loss_fct = CrossEntropyLoss()
2134
+ loss = loss_fct(
2135
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2136
+ )
2137
+ elif self.config.problem_type == "multi_label_classification":
2138
+ loss_fct = BCEWithLogitsLoss()
2139
+ loss = loss_fct(pooled_logits, labels)
2140
+ if not return_dict:
2141
+ output = (pooled_logits,) + transformer_outputs[1:]
2142
+ return ((loss,) + output) if loss is not None else output
2143
+
2144
+ return SequenceClassifierOutputWithPast(
2145
+ loss=loss,
2146
+ logits=pooled_logits,
2147
+ past_key_values=transformer_outputs.past_key_values,
2148
+ hidden_states=transformer_outputs.hidden_states,
2149
+ attentions=transformer_outputs.attentions,
2150
+ )
checkpoint-1000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-1000/tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 131072,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{{'<|Assistant|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}"
35
+ }
checkpoint-10000/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyDeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tinydeepseek.TinyDeepseekV3Config",
9
+ "AutoModel": "modeling_tinydeepseek.TinyDeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_tinydeepseek.TinyDeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.0001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4864,
21
+ "kv_lora_rank": 128,
22
+ "lossfreebalance_update_rate": 0.001,
23
+ "max_position_embeddings": 163840,
24
+ "model_type": "tinydeepseek_v3",
25
+ "moe_intermediate_size": 608,
26
+ "moe_layer_freq": 1,
27
+ "mtp_loss_lambda": 0.1,
28
+ "n_future_tokens": 2,
29
+ "n_group": 8,
30
+ "n_routed_experts": 64,
31
+ "n_shared_experts": 2,
32
+ "norm_topk_prob": true,
33
+ "num_attention_heads": 8,
34
+ "num_experts_per_tok": 6,
35
+ "num_hidden_layers": 27,
36
+ "num_key_value_heads": 8,
37
+ "num_nextn_predict_layers": 1,
38
+ "output_router_logits": false,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": null,
41
+ "qk_nope_head_dim": 32,
42
+ "qk_rope_head_dim": 16,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 0.707,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 1.0,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": false,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.48.3",
62
+ "use_cache": true,
63
+ "use_lossfreebalance": false,
64
+ "v_head_dim": 32,
65
+ "vocab_size": 129280
66
+ }
checkpoint-10000/configuration_tinydeepseek.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TinyDeepseekV3Config(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
+ n_future_tokens (int):
104
+ Number of prediction heads in the model (= 1 + `len(extra_heads)`).
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "tinydeepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'aux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.0001,
147
+ seq_aux=True,
148
+ output_router_logits=False,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ n_future_tokens=1,
164
+ mtp_loss_lambda=0.1,
165
+ use_lossfreebalance=True,
166
+ lossfreebalance_update_rate=0.001,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.moe_intermediate_size = moe_intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_nextn_predict_layers = num_nextn_predict_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.n_shared_experts = n_shared_experts
178
+ self.n_routed_experts = n_routed_experts
179
+ self.ep_size = ep_size
180
+ self.routed_scaling_factor = routed_scaling_factor
181
+ self.kv_lora_rank = kv_lora_rank
182
+ self.q_lora_rank = q_lora_rank if q_lora_rank else None
183
+ self.qk_rope_head_dim = qk_rope_head_dim
184
+ self.v_head_dim = v_head_dim
185
+ self.qk_nope_head_dim = qk_nope_head_dim
186
+ self.topk_method = topk_method
187
+ self.n_group = n_group
188
+ self.topk_group = topk_group
189
+ self.num_experts_per_tok = num_experts_per_tok
190
+ self.moe_layer_freq = moe_layer_freq
191
+ self.first_k_dense_replace = first_k_dense_replace
192
+ self.norm_topk_prob = norm_topk_prob
193
+ self.scoring_func = scoring_func
194
+ self.aux_loss_alpha = aux_loss_alpha
195
+ self.seq_aux = seq_aux
196
+ self.output_router_logits = output_router_logits
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.rms_norm_eps = rms_norm_eps
205
+ self.pretraining_tp = pretraining_tp
206
+ self.use_cache = use_cache
207
+ self.rope_theta = rope_theta
208
+ self.rope_scaling = rope_scaling
209
+ self.attention_bias = attention_bias
210
+ self.attention_dropout = attention_dropout
211
+ self.n_future_tokens = n_future_tokens
212
+ self.mtp_loss_lambda = mtp_loss_lambda
213
+ self.use_lossfreebalance = use_lossfreebalance
214
+ self.lossfreebalance_update_rate = lossfreebalance_update_rate
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
checkpoint-10000/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.48.3",
6
+ "use_cache": false
7
+ }
checkpoint-10000/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26be8e721f5d9be54bb07fdcba6e1f067a0ba128a610a27ae4bf68e79c1f3555
3
+ size 5000243440
checkpoint-10000/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:175d4e329d8bfc2a905179359e238a0f544e5845acb36e0299eef985381e7626
3
+ size 1591021104
checkpoint-10000/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-10000/modeling_tinydeepseek.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MoeModelOutputWithPast,
40
+ MoeCausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ # is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_tinydeepseek import TinyDeepseekV3Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ # if not is_torch_greater_or_equal_than_1_13:
70
+ # import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "TinyDeepseekV3Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
94
+ def load_balancing_loss_func(
95
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
96
+ num_experts: Optional[int] = None,
97
+ top_k=2,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ ) -> Union[torch.Tensor, int]:
100
+ r"""
101
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
102
+
103
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
104
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
105
+ experts is too unbalanced.
106
+
107
+ Args:
108
+ gate_logits:
109
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
110
+ shape [batch_size X sequence_length, num_experts].
111
+ num_experts:
112
+ Number of experts
113
+ top_k:
114
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
115
+ parameter.
116
+ attention_mask (`torch.Tensor`, *optional*):
117
+ The attention_mask used in forward function
118
+ shape [batch_size X sequence_length] if not None.
119
+
120
+ Returns:
121
+ The auxiliary loss.
122
+ """
123
+ if gate_logits is None or not isinstance(gate_logits, tuple):
124
+ return 0
125
+
126
+ if isinstance(gate_logits, tuple):
127
+ compute_device = gate_logits[0].device
128
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
129
+
130
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
131
+
132
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
133
+
134
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
135
+
136
+ if attention_mask is None:
137
+ # Compute the percentage of tokens routed to each experts
138
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
139
+
140
+ # Compute the average probability of routing to these experts
141
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
142
+ else:
143
+ batch_size, sequence_length = attention_mask.shape
144
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
145
+
146
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
147
+ expert_attention_mask = (
148
+ attention_mask[None, :, :, None, None]
149
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
150
+ .reshape(-1, top_k, num_experts)
151
+ .to(compute_device)
152
+ )
153
+
154
+ # Compute the percentage of tokens routed to each experts
155
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
156
+ expert_attention_mask, dim=0
157
+ )
158
+
159
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
160
+ router_per_expert_attention_mask = (
161
+ attention_mask[None, :, :, None]
162
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
163
+ .reshape(-1, num_experts)
164
+ .to(compute_device)
165
+ )
166
+
167
+ # Compute the average probability of routing to these experts
168
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
169
+ router_per_expert_attention_mask, dim=0
170
+ )
171
+
172
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
173
+ return overall_loss * num_experts
174
+
175
+
176
+ class DeepseekV3RMSNorm(nn.Module):
177
+ def __init__(self, hidden_size, eps=1e-6):
178
+ """
179
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
180
+ """
181
+ super().__init__()
182
+ self.weight = nn.Parameter(torch.ones(hidden_size))
183
+ self.variance_epsilon = eps
184
+
185
+ def forward(self, hidden_states):
186
+ input_dtype = hidden_states.dtype
187
+ hidden_states = hidden_states.to(torch.float32)
188
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
189
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
190
+ return self.weight * hidden_states.to(input_dtype)
191
+
192
+
193
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
194
+
195
+
196
+ class DeepseekV3RotaryEmbedding(nn.Module):
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
198
+ super().__init__()
199
+
200
+ self.dim = dim
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.base = base
203
+ inv_freq = 1.0 / (
204
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
205
+ )
206
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
207
+
208
+ # Build here to make `torch.jit.trace` work.
209
+ self._set_cos_sin_cache(
210
+ seq_len=max_position_embeddings,
211
+ device=self.inv_freq.device,
212
+ dtype=torch.get_default_dtype(),
213
+ )
214
+ self.max_seq_len_cached = None
215
+
216
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
217
+ self.max_seq_len_cached = seq_len
218
+ t = torch.arange(
219
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
220
+ )
221
+
222
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
223
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
224
+ emb = torch.cat((freqs, freqs), dim=-1)
225
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
226
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
227
+
228
+ def forward(self, x, seq_len=None):
229
+ # x: [bs, num_attention_heads, seq_len, head_size]
230
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
231
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
232
+
233
+ return (
234
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
235
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
236
+ )
237
+
238
+
239
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
240
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
241
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ max_position_embeddings=2048,
247
+ base=10000,
248
+ device=None,
249
+ scaling_factor=1.0,
250
+ ):
251
+ self.scaling_factor = scaling_factor
252
+ super().__init__(dim, max_position_embeddings, base, device)
253
+
254
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
255
+ self.max_seq_len_cached = seq_len
256
+ t = torch.arange(
257
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
258
+ )
259
+ t = t / self.scaling_factor
260
+
261
+ freqs = torch.outer(t, self.inv_freq)
262
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
263
+ emb = torch.cat((freqs, freqs), dim=-1)
264
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
265
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
266
+
267
+
268
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
269
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
270
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
271
+
272
+ def __init__(
273
+ self,
274
+ dim,
275
+ max_position_embeddings=2048,
276
+ base=10000,
277
+ device=None,
278
+ scaling_factor=1.0,
279
+ ):
280
+ self.scaling_factor = scaling_factor
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
+
286
+ if seq_len > self.max_position_embeddings:
287
+ base = self.base * (
288
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
289
+ - (self.scaling_factor - 1)
290
+ ) ** (self.dim / (self.dim - 2))
291
+ inv_freq = 1.0 / (
292
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
293
+ )
294
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
295
+
296
+ t = torch.arange(
297
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
298
+ )
299
+
300
+ freqs = torch.outer(t, self.inv_freq)
301
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
302
+ emb = torch.cat((freqs, freqs), dim=-1)
303
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
304
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
305
+
306
+
307
+ # Inverse dim formula to find dim based on number of rotations
308
+ def yarn_find_correction_dim(
309
+ num_rotations, dim, base=10000, max_position_embeddings=2048
310
+ ):
311
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
312
+ 2 * math.log(base)
313
+ )
314
+
315
+
316
+ # Find dim range bounds based on rotations
317
+ def yarn_find_correction_range(
318
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
319
+ ):
320
+ low = math.floor(
321
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
322
+ )
323
+ high = math.ceil(
324
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
325
+ )
326
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
327
+
328
+
329
+ def yarn_get_mscale(scale=1, mscale=1):
330
+ if scale <= 1:
331
+ return 1.0
332
+ return 0.1 * mscale * math.log(scale) + 1.0
333
+
334
+
335
+ def yarn_linear_ramp_mask(min, max, dim):
336
+ if min == max:
337
+ max += 0.001 # Prevent singularity
338
+
339
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
340
+ ramp_func = torch.clamp(linear_func, 0, 1)
341
+ return ramp_func
342
+
343
+
344
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
345
+
346
+ def __init__(
347
+ self,
348
+ dim,
349
+ max_position_embeddings=2048,
350
+ base=10000,
351
+ device=None,
352
+ scaling_factor=1.0,
353
+ original_max_position_embeddings=4096,
354
+ beta_fast=32,
355
+ beta_slow=1,
356
+ mscale=1,
357
+ mscale_all_dim=0,
358
+ ):
359
+ self.scaling_factor = scaling_factor
360
+ self.original_max_position_embeddings = original_max_position_embeddings
361
+ self.beta_fast = beta_fast
362
+ self.beta_slow = beta_slow
363
+ self.mscale = mscale
364
+ self.mscale_all_dim = mscale_all_dim
365
+ super().__init__(dim, max_position_embeddings, base, device)
366
+
367
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
368
+ self.max_seq_len_cached = seq_len
369
+ dim = self.dim
370
+
371
+ freq_extra = 1.0 / (
372
+ self.base
373
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
374
+ )
375
+ freq_inter = 1.0 / (
376
+ self.scaling_factor
377
+ * self.base
378
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
379
+ )
380
+
381
+ low, high = yarn_find_correction_range(
382
+ self.beta_fast,
383
+ self.beta_slow,
384
+ dim,
385
+ self.base,
386
+ self.original_max_position_embeddings,
387
+ )
388
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
389
+ device=device, dtype=torch.float32
390
+ )
391
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
392
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
393
+
394
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
395
+
396
+ freqs = torch.outer(t, inv_freq)
397
+
398
+ _mscale = float(
399
+ yarn_get_mscale(self.scaling_factor, self.mscale)
400
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
401
+ )
402
+
403
+ emb = torch.cat((freqs, freqs), dim=-1)
404
+ self.register_buffer(
405
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
406
+ )
407
+ self.register_buffer(
408
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
409
+ )
410
+
411
+
412
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
413
+ def rotate_half(x):
414
+ """Rotates half the hidden dims of the input."""
415
+ x1 = x[..., : x.shape[-1] // 2]
416
+ x2 = x[..., x.shape[-1] // 2 :]
417
+ return torch.cat((-x2, x1), dim=-1)
418
+
419
+
420
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
421
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
422
+ """Applies Rotary Position Embedding to the query and key tensors.
423
+
424
+ Args:
425
+ q (`torch.Tensor`): The query tensor.
426
+ k (`torch.Tensor`): The key tensor.
427
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
428
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
429
+ position_ids (`torch.Tensor`):
430
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
431
+ used to pass offsetted position ids when working with a KV-cache.
432
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
433
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
434
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
435
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
436
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
437
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
438
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
439
+ Returns:
440
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
441
+ """
442
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
443
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
444
+
445
+ b, h, s, d = q.shape
446
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
447
+
448
+ b, h, s, d = k.shape
449
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
450
+
451
+ q_embed = (q * cos) + (rotate_half(q) * sin)
452
+ k_embed = (k * cos) + (rotate_half(k) * sin)
453
+ return q_embed, k_embed
454
+
455
+
456
+ class DeepseekV3MLP(nn.Module):
457
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
458
+ super().__init__()
459
+ self.config = config
460
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
461
+ self.intermediate_size = (
462
+ config.intermediate_size if intermediate_size is None else intermediate_size
463
+ )
464
+
465
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
466
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
467
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
468
+ self.act_fn = ACT2FN[config.hidden_act]
469
+
470
+ def forward(self, x):
471
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
472
+ return down_proj
473
+
474
+
475
+ class MoEGate(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.config = config
479
+ self.top_k = config.num_experts_per_tok
480
+ self.n_routed_experts = config.n_routed_experts
481
+ self.routed_scaling_factor = config.routed_scaling_factor
482
+ self.scoring_func = config.scoring_func
483
+ self.seq_aux = config.seq_aux
484
+ self.topk_method = config.topk_method
485
+ self.n_group = config.n_group
486
+ self.topk_group = config.topk_group
487
+
488
+ # topk selection algorithm
489
+ self.norm_topk_prob = config.norm_topk_prob
490
+ self.gating_dim = config.hidden_size
491
+ self.weight = nn.Parameter(
492
+ torch.empty((self.n_routed_experts, self.gating_dim))
493
+ )
494
+ if self.topk_method == "noaux_tc":
495
+ self.e_score_correction_bias = nn.Parameter(
496
+ torch.empty((self.n_routed_experts))
497
+ )
498
+ elif self.topk_method == "aux_tc":
499
+ self.update_rate = config.lossfreebalance_update_rate
500
+ self.e_score_correction_bias = nn.Parameter(
501
+ torch.zeros((self.n_routed_experts))
502
+ )
503
+
504
+ self.reset_parameters()
505
+
506
+ def reset_parameters(self) -> None:
507
+ import torch.nn.init as init
508
+
509
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
510
+
511
+ def forward(self, hidden_states):
512
+ bsz, seq_len, h = hidden_states.shape
513
+ ### compute gating score
514
+ hidden_states = hidden_states.view(-1, h)
515
+ logits = F.linear(
516
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
517
+ )
518
+ if self.scoring_func == "sigmoid":
519
+ scores = logits.sigmoid()
520
+ else:
521
+ raise NotImplementedError(
522
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
523
+ )
524
+
525
+ ### select top-k experts
526
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
527
+ group_scores = (
528
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
529
+ ) # [n, n_group]
530
+ group_idx = torch.topk(
531
+ group_scores, k=self.topk_group, dim=-1, sorted=False
532
+ )[
533
+ 1
534
+ ] # [n, top_k_group]
535
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
536
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
537
+ score_mask = (
538
+ group_mask.unsqueeze(-1)
539
+ .expand(
540
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
541
+ )
542
+ .reshape(bsz * seq_len, -1)
543
+ ) # [n, e]
544
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
545
+ _, topk_idx = torch.topk(
546
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
547
+ )
548
+ topk_weight = scores.gather(1, topk_idx)
549
+
550
+ if self.topk_method == "aux_tc":
551
+ expert_counts = torch.bincount(
552
+ topk_idx.flatten(),
553
+ minlength=self.n_routed_experts
554
+ )
555
+
556
+ avg_count = expert_counts.float().mean()
557
+ #max_violation = torch.max(torch.abs(expert_counts.float() - avg_count) / avg_count)
558
+
559
+ # for monitoring the expert-balancing globallu
560
+ # min_violation = torch.min(expert_counts.float()) / avg_count
561
+ # max_violation = torch.max(expert_counts.float()) / avg_count
562
+ # return [min_violation.item(), max_violation.item()]
563
+
564
+ for expert_idx, expert_count in enumerate(expert_counts):
565
+ # b_i = b_i + u + sign(e_i)
566
+ # note: this is \bar{c_i} - c_i, NOT c_i - \bar{c_i}, which will push the network to
567
+ # be maximally unbalanced. Really important to get this part right!!!
568
+ count_error = avg_count - expert_count.float()
569
+ self.e_score_correction_bias.data[expert_idx] += (self.update_rate * torch.sign(count_error))
570
+
571
+ ### norm gate to sum 1
572
+ if self.top_k > 1 and self.norm_topk_prob:
573
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
574
+ topk_weight = topk_weight / denominator
575
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
576
+
577
+ return topk_idx, topk_weight, scores
578
+
579
+ class TinyDeepseekV3MoE(nn.Module):
580
+ """
581
+ A mixed expert module containing shared experts.
582
+ """
583
+
584
+ def __init__(self, config):
585
+ super().__init__()
586
+ self.config = config
587
+ self.num_experts_per_tok = config.num_experts_per_tok
588
+
589
+ if hasattr(config, "ep_size") and config.ep_size > 1:
590
+ assert config.ep_size == dist.get_world_size()
591
+ self.ep_size = config.ep_size
592
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
593
+ self.ep_rank = dist.get_rank()
594
+ self.experts = nn.ModuleList(
595
+ [
596
+ (
597
+ DeepseekV3MLP(
598
+ config, intermediate_size=config.moe_intermediate_size
599
+ )
600
+ if i >= self.ep_rank * self.experts_per_rank
601
+ and i < (self.ep_rank + 1) * self.experts_per_rank
602
+ else None
603
+ )
604
+ for i in range(config.n_routed_experts)
605
+ ]
606
+ )
607
+ else:
608
+ self.ep_size = 1
609
+ self.experts_per_rank = config.n_routed_experts
610
+ self.ep_rank = 0
611
+ self.experts = nn.ModuleList(
612
+ [
613
+ DeepseekV3MLP(
614
+ config, intermediate_size=config.moe_intermediate_size
615
+ )
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV3MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, router_scores = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if not self.training:
633
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
634
+ else:
635
+ # tinydeepseek: moe forward for training
636
+ y = self.moe_train(hidden_states, topk_idx, topk_weight).view(*orig_shape)
637
+ if self.config.n_shared_experts is not None:
638
+ y = y + self.shared_experts(identity)
639
+ return y, router_scores
640
+
641
+ @torch.no_grad()
642
+ def moe_infer(self, x, topk_ids, topk_weight):
643
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
644
+ cnts.scatter_(1, topk_ids, 1)
645
+ tokens_per_expert = cnts.sum(dim=0)
646
+ idxs = topk_ids.view(-1).argsort()
647
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
648
+ sorted_tokens_shape = sorted_tokens.shape
649
+ if self.ep_size > 1:
650
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
651
+ tokens_per_expert_group = tokens_per_expert.new_empty(
652
+ tokens_per_expert.shape[0]
653
+ )
654
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
655
+ output_splits = (
656
+ tokens_per_expert_group.view(self.ep_size, -1)
657
+ .sum(1)
658
+ .cpu()
659
+ .numpy()
660
+ .tolist()
661
+ )
662
+ gathered_tokens = sorted_tokens.new_empty(
663
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
664
+ )
665
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
666
+ dist.all_to_all(
667
+ list(gathered_tokens.split(output_splits)),
668
+ list(sorted_tokens.split(input_split_sizes)),
669
+ )
670
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
671
+ self.ep_size, self.experts_per_rank
672
+ ).sum(dim=0)
673
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
674
+ s = 0
675
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
676
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
677
+ s += k
678
+ gatherd_idxs = gatherd_idxs.argsort()
679
+ sorted_tokens = gathered_tokens[gatherd_idxs]
680
+ tokens_per_expert = tokens_per_expert_post_gather
681
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
682
+
683
+ outputs = []
684
+ start_idx = 0
685
+ for i, num_tokens in enumerate(tokens_per_expert):
686
+ end_idx = start_idx + num_tokens
687
+ if num_tokens == 0:
688
+ continue
689
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
690
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
691
+ expert_out = expert(tokens_for_this_expert)
692
+ outputs.append(expert_out)
693
+ start_idx = end_idx
694
+
695
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
696
+ if self.ep_size > 1:
697
+ new_x = torch.empty_like(outs)
698
+ new_x[gatherd_idxs] = outs
699
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
700
+ dist.all_to_all(
701
+ list(gathered_tokens.split(input_split_sizes)),
702
+ list(new_x.split(output_splits)),
703
+ )
704
+ outs = gathered_tokens
705
+
706
+ new_x = torch.empty_like(outs)
707
+ new_x[idxs] = outs
708
+ final_out = (
709
+ new_x.view(*topk_ids.shape, -1)
710
+ .type(topk_weight.dtype)
711
+ .mul_(topk_weight.unsqueeze(dim=-1))
712
+ .sum(dim=1)
713
+ .type(new_x.dtype)
714
+ )
715
+ return final_out
716
+
717
+
718
+ def moe_train(self, x, topk_ids, topk_weight):
719
+ token_size, hidden_dim = x.shape # token_size = bsz_size * seq_len
720
+ final_hidden_states = torch.zeros(
721
+ (token_size, hidden_dim), dtype=x.dtype, device=x.device
722
+ )
723
+
724
+ # One hot encode the selected experts to create an expert mask
725
+ # this will be used to easily index which expert is going to be sollicitated
726
+ expert_mask = torch.nn.functional.one_hot(topk_ids, num_classes=self.config.n_routed_experts).permute(2, 1, 0)
727
+
728
+ # Loop over all available experts in the model and perform the computation on each expert
729
+ for expert_idx in range(self.config.n_routed_experts):
730
+ expert_layer = self.experts[expert_idx]
731
+ idx, top_x = torch.where(expert_mask[expert_idx])
732
+
733
+ # Index the correct hidden states and compute the expert hidden state for
734
+ # the current expert. We need to make sure to multiply the output hidden
735
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
736
+ current_state = x[None, top_x].reshape(-1, hidden_dim)
737
+ current_hidden_states = expert_layer(current_state) * topk_weight[top_x, idx, None]
738
+
739
+ # However `index_add_` only support torch tensors for indexing so we'll use
740
+ # the `top_x` tensor here.
741
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(x.dtype))
742
+
743
+ return final_hidden_states.view(-1, hidden_dim)
744
+
745
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
746
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
747
+ """
748
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
749
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
750
+ """
751
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
752
+ if n_rep == 1:
753
+ return hidden_states
754
+ hidden_states = hidden_states[:, :, None, :, :].expand(
755
+ batch, num_key_value_heads, n_rep, slen, head_dim
756
+ )
757
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
758
+
759
+
760
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
761
+ class DeepseekV3Attention(nn.Module):
762
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
763
+
764
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: Optional[int] = None):
765
+ super().__init__()
766
+ self.config = config
767
+ self.layer_idx = layer_idx
768
+ if layer_idx is None:
769
+ logger.warning_once(
770
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
771
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
772
+ "when creating this class."
773
+ )
774
+
775
+ self.attention_dropout = config.attention_dropout
776
+ self.hidden_size = config.hidden_size
777
+ self.num_heads = config.num_attention_heads
778
+
779
+ self.max_position_embeddings = config.max_position_embeddings
780
+ self.rope_theta = config.rope_theta
781
+ self.q_lora_rank = config.q_lora_rank
782
+ self.qk_rope_head_dim = config.qk_rope_head_dim
783
+ self.kv_lora_rank = config.kv_lora_rank
784
+ self.v_head_dim = config.v_head_dim
785
+ self.qk_nope_head_dim = config.qk_nope_head_dim
786
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
787
+
788
+ self.is_causal = True
789
+
790
+ if self.q_lora_rank is None:
791
+ self.q_proj = nn.Linear(
792
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
793
+ )
794
+ else:
795
+ self.q_a_proj = nn.Linear(
796
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
797
+ )
798
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
799
+ self.q_b_proj = nn.Linear(
800
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
801
+ )
802
+
803
+ self.kv_a_proj_with_mqa = nn.Linear(
804
+ self.hidden_size,
805
+ config.kv_lora_rank + config.qk_rope_head_dim,
806
+ bias=config.attention_bias,
807
+ )
808
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
809
+ self.kv_b_proj = nn.Linear(
810
+ config.kv_lora_rank,
811
+ self.num_heads
812
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
813
+ bias=False,
814
+ )
815
+
816
+ self.o_proj = nn.Linear(
817
+ self.num_heads * self.v_head_dim,
818
+ self.hidden_size,
819
+ bias=config.attention_bias,
820
+ )
821
+ self._init_rope()
822
+
823
+ self.softmax_scale = self.q_head_dim ** (-0.5)
824
+ if self.config.rope_scaling is not None:
825
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
826
+ scaling_factor = self.config.rope_scaling["factor"]
827
+ if mscale_all_dim:
828
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
829
+ self.softmax_scale = self.softmax_scale * mscale * mscale
830
+
831
+ def _init_rope(self):
832
+ if self.config.rope_scaling is None:
833
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
834
+ self.qk_rope_head_dim,
835
+ max_position_embeddings=self.max_position_embeddings,
836
+ base=self.rope_theta,
837
+ )
838
+ else:
839
+ scaling_type = self.config.rope_scaling["type"]
840
+ scaling_factor = self.config.rope_scaling["factor"]
841
+ if scaling_type == "linear":
842
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
843
+ self.qk_rope_head_dim,
844
+ max_position_embeddings=self.max_position_embeddings,
845
+ scaling_factor=scaling_factor,
846
+ base=self.rope_theta,
847
+ )
848
+ elif scaling_type == "dynamic":
849
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
850
+ self.qk_rope_head_dim,
851
+ max_position_embeddings=self.max_position_embeddings,
852
+ scaling_factor=scaling_factor,
853
+ base=self.rope_theta,
854
+ )
855
+ elif scaling_type == "yarn":
856
+ kwargs = {
857
+ key: self.config.rope_scaling[key]
858
+ for key in [
859
+ "original_max_position_embeddings",
860
+ "beta_fast",
861
+ "beta_slow",
862
+ "mscale",
863
+ "mscale_all_dim",
864
+ ]
865
+ if key in self.config.rope_scaling
866
+ }
867
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
868
+ self.qk_rope_head_dim,
869
+ max_position_embeddings=self.max_position_embeddings,
870
+ scaling_factor=scaling_factor,
871
+ base=self.rope_theta,
872
+ **kwargs,
873
+ )
874
+ else:
875
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
876
+
877
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
878
+ return (
879
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
880
+ .transpose(1, 2)
881
+ .contiguous()
882
+ )
883
+
884
+ def forward(
885
+ self,
886
+ hidden_states: torch.Tensor,
887
+ attention_mask: Optional[torch.Tensor] = None,
888
+ position_ids: Optional[torch.LongTensor] = None,
889
+ past_key_value: Optional[Cache] = None,
890
+ output_attentions: bool = False,
891
+ use_cache: bool = False,
892
+ **kwargs,
893
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
894
+ if "padding_mask" in kwargs:
895
+ warnings.warn(
896
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
897
+ )
898
+ bsz, q_len, _ = hidden_states.size()
899
+
900
+ if self.q_lora_rank is None:
901
+ q = self.q_proj(hidden_states)
902
+ else:
903
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
904
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
905
+ q_nope, q_pe = torch.split(
906
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
907
+ )
908
+
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
+ if past_key_value is not None:
925
+ if self.layer_idx is None:
926
+ raise ValueError(
927
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
928
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
929
+ "with a layer index."
930
+ )
931
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
932
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
933
+
934
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
935
+
936
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
937
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
938
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
939
+
940
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
941
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
942
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
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
+ attn_weights = (
950
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
951
+ )
952
+
953
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
954
+ raise ValueError(
955
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
956
+ f" {attn_weights.size()}"
957
+ )
958
+ assert attention_mask is not None
959
+ if attention_mask is not None:
960
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
961
+ raise ValueError(
962
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
963
+ )
964
+ attn_weights = attn_weights + attention_mask
965
+
966
+ # upcast attention to fp32
967
+ attn_weights = nn.functional.softmax(
968
+ attn_weights, dim=-1, dtype=torch.float32
969
+ ).to(query_states.dtype)
970
+ attn_weights = nn.functional.dropout(
971
+ attn_weights, p=self.attention_dropout, training=self.training
972
+ )
973
+ attn_output = torch.matmul(attn_weights, value_states)
974
+
975
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
976
+ raise ValueError(
977
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
978
+ f" {attn_output.size()}"
979
+ )
980
+
981
+ attn_output = attn_output.transpose(1, 2).contiguous()
982
+
983
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
984
+
985
+ attn_output = self.o_proj(attn_output)
986
+
987
+ if not output_attentions:
988
+ attn_weights = None
989
+
990
+ return attn_output, attn_weights, past_key_value
991
+
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
994
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
995
+ """
996
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
997
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
998
+ flash attention and deal with padding tokens in case the input contains any of them.
999
+ """
1000
+
1001
+ def __init__(self, *args, **kwargs):
1002
+ super().__init__(*args, **kwargs)
1003
+
1004
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1005
+ # 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.
1006
+ # 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).
1007
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1008
+
1009
+ def forward(
1010
+ self,
1011
+ hidden_states: torch.Tensor,
1012
+ attention_mask: Optional[torch.LongTensor] = None,
1013
+ position_ids: Optional[torch.LongTensor] = None,
1014
+ past_key_value: Optional[Cache] = None,
1015
+ output_attentions: bool = False,
1016
+ use_cache: bool = False,
1017
+ **kwargs,
1018
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1019
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1020
+ if "padding_mask" in kwargs:
1021
+ warnings.warn(
1022
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1023
+ )
1024
+
1025
+ # overwrite attention_mask with padding_mask
1026
+ attention_mask = kwargs.pop("padding_mask")
1027
+
1028
+ output_attentions = False
1029
+
1030
+ bsz, q_len, _ = hidden_states.size()
1031
+
1032
+ if self.q_lora_rank is None:
1033
+ q = self.q_proj(hidden_states)
1034
+ else:
1035
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1036
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1037
+ q_nope, q_pe = torch.split(
1038
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1039
+ )
1040
+
1041
+ # Flash attention requires the input to have the shape
1042
+ # batch_size x seq_length x head_dim x hidden_dim
1043
+ # therefore we just need to keep the original shape
1044
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1045
+ compressed_kv, k_pe = torch.split(
1046
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1047
+ )
1048
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1049
+ kv = (
1050
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1051
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1052
+ .transpose(1, 2)
1053
+ )
1054
+
1055
+ k_nope, value_states = torch.split(
1056
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1057
+ )
1058
+ kv_seq_len = value_states.shape[-2]
1059
+
1060
+ kv_seq_len = value_states.shape[-2]
1061
+ if past_key_value is not None:
1062
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1063
+
1064
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1065
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1066
+
1067
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1068
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1069
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1070
+
1071
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1072
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1073
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1074
+
1075
+ if self.q_head_dim != self.v_head_dim:
1076
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1077
+
1078
+ if past_key_value is not None:
1079
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1080
+ key_states, value_states = past_key_value.update(
1081
+ key_states, value_states, self.layer_idx, cache_kwargs
1082
+ )
1083
+
1084
+ # 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
1085
+ # to be able to avoid many of these transpose/reshape/view.
1086
+ query_states = query_states.transpose(1, 2)
1087
+ key_states = key_states.transpose(1, 2)
1088
+ value_states = value_states.transpose(1, 2)
1089
+
1090
+ dropout_rate = self.attention_dropout if self.training else 0.0
1091
+
1092
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1093
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1094
+ # cast them back in the correct dtype just to be sure everything works as expected.
1095
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1096
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1097
+
1098
+ input_dtype = query_states.dtype
1099
+ if input_dtype == torch.float32:
1100
+ # Handle the case where the model is quantized
1101
+ if hasattr(self.config, "_pre_quantization_dtype"):
1102
+ target_dtype = self.config._pre_quantization_dtype
1103
+ elif torch.is_autocast_enabled():
1104
+ target_dtype = torch.get_autocast_gpu_dtype()
1105
+ else:
1106
+ target_dtype = (
1107
+ self.q_proj.weight.dtype
1108
+ if self.q_lora_rank is None
1109
+ else self.q_a_proj.weight.dtype
1110
+ )
1111
+
1112
+ logger.warning_once(
1113
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1114
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1115
+ f" {target_dtype}."
1116
+ )
1117
+
1118
+ query_states = query_states.to(target_dtype)
1119
+ key_states = key_states.to(target_dtype)
1120
+ value_states = value_states.to(target_dtype)
1121
+
1122
+ attn_output = self._flash_attention_forward(
1123
+ query_states,
1124
+ key_states,
1125
+ value_states,
1126
+ attention_mask,
1127
+ q_len,
1128
+ dropout=dropout_rate,
1129
+ softmax_scale=self.softmax_scale,
1130
+ )
1131
+ if self.q_head_dim != self.v_head_dim:
1132
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1133
+
1134
+ attn_output = attn_output.reshape(
1135
+ bsz, q_len, self.num_heads * self.v_head_dim
1136
+ ).contiguous()
1137
+ attn_output = self.o_proj(attn_output)
1138
+
1139
+ if not output_attentions:
1140
+ attn_weights = None
1141
+
1142
+ return attn_output, attn_weights, past_key_value
1143
+
1144
+ def _flash_attention_forward(
1145
+ self,
1146
+ query_states,
1147
+ key_states,
1148
+ value_states,
1149
+ attention_mask,
1150
+ query_length,
1151
+ dropout=0.0,
1152
+ softmax_scale=None,
1153
+ ):
1154
+ """
1155
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1156
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1157
+
1158
+ Args:
1159
+ query_states (`torch.Tensor`):
1160
+ Input query states to be passed to Flash Attention API
1161
+ key_states (`torch.Tensor`):
1162
+ Input key states to be passed to Flash Attention API
1163
+ value_states (`torch.Tensor`):
1164
+ Input value states to be passed to Flash Attention API
1165
+ attention_mask (`torch.Tensor`):
1166
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1167
+ position of padding tokens and 1 for the position of non-padding tokens.
1168
+ dropout (`int`, *optional*):
1169
+ Attention dropout
1170
+ softmax_scale (`float`, *optional*):
1171
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1172
+ """
1173
+ if not self._flash_attn_uses_top_left_mask:
1174
+ causal = self.is_causal
1175
+ else:
1176
+ # 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__.
1177
+ causal = self.is_causal and query_length != 1
1178
+
1179
+ # Contains at least one padding token in the sequence
1180
+ if attention_mask is not None:
1181
+ batch_size = query_states.shape[0]
1182
+ (
1183
+ query_states,
1184
+ key_states,
1185
+ value_states,
1186
+ indices_q,
1187
+ cu_seq_lens,
1188
+ max_seq_lens,
1189
+ ) = self._upad_input(
1190
+ query_states, key_states, value_states, attention_mask, query_length
1191
+ )
1192
+
1193
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1194
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1195
+
1196
+ attn_output_unpad = flash_attn_varlen_func(
1197
+ query_states,
1198
+ key_states,
1199
+ value_states,
1200
+ cu_seqlens_q=cu_seqlens_q,
1201
+ cu_seqlens_k=cu_seqlens_k,
1202
+ max_seqlen_q=max_seqlen_in_batch_q,
1203
+ max_seqlen_k=max_seqlen_in_batch_k,
1204
+ dropout_p=dropout,
1205
+ softmax_scale=softmax_scale,
1206
+ causal=causal,
1207
+ )
1208
+
1209
+ attn_output = pad_input(
1210
+ attn_output_unpad, indices_q, batch_size, query_length
1211
+ )
1212
+ else:
1213
+ attn_output = flash_attn_func(
1214
+ query_states,
1215
+ key_states,
1216
+ value_states,
1217
+ dropout,
1218
+ softmax_scale=softmax_scale,
1219
+ causal=causal,
1220
+ )
1221
+
1222
+ return attn_output
1223
+
1224
+ def _upad_input(
1225
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1226
+ ):
1227
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1228
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1229
+
1230
+ key_layer = index_first_axis(
1231
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1232
+ indices_k,
1233
+ )
1234
+ value_layer = index_first_axis(
1235
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1236
+ indices_k,
1237
+ )
1238
+ if query_length == kv_seq_len:
1239
+ query_layer = index_first_axis(
1240
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1241
+ indices_k,
1242
+ )
1243
+ cu_seqlens_q = cu_seqlens_k
1244
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1245
+ indices_q = indices_k
1246
+ elif query_length == 1:
1247
+ max_seqlen_in_batch_q = 1
1248
+ cu_seqlens_q = torch.arange(
1249
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1250
+ ) # There is a memcpy here, that is very bad.
1251
+ indices_q = cu_seqlens_q[:-1]
1252
+ query_layer = query_layer.squeeze(1)
1253
+ else:
1254
+ # The -q_len: slice assumes left padding.
1255
+ attention_mask = attention_mask[:, -query_length:]
1256
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1257
+ query_layer, attention_mask
1258
+ )
1259
+
1260
+ return (
1261
+ query_layer,
1262
+ key_layer,
1263
+ value_layer,
1264
+ indices_q,
1265
+ (cu_seqlens_q, cu_seqlens_k),
1266
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1267
+ )
1268
+
1269
+
1270
+ ATTENTION_CLASSES = {
1271
+ "eager": DeepseekV3Attention,
1272
+ "flash_attention_2": DeepseekV3FlashAttention2,
1273
+ }
1274
+
1275
+
1276
+ class DeepseekV3DecoderLayer(nn.Module):
1277
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: int):
1278
+ super().__init__()
1279
+ self.hidden_size = config.hidden_size
1280
+
1281
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1282
+ config=config, layer_idx=layer_idx
1283
+ )
1284
+
1285
+ self.mlp = (
1286
+ TinyDeepseekV3MoE(config)
1287
+ if (
1288
+ config.n_routed_experts is not None
1289
+ and layer_idx >= config.first_k_dense_replace
1290
+ and layer_idx % config.moe_layer_freq == 0
1291
+ )
1292
+ else DeepseekV3MLP(config)
1293
+ )
1294
+ self.input_layernorm = DeepseekV3RMSNorm(
1295
+ config.hidden_size, eps=config.rms_norm_eps
1296
+ )
1297
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1298
+ config.hidden_size, eps=config.rms_norm_eps
1299
+ )
1300
+
1301
+ def forward(
1302
+ self,
1303
+ hidden_states: torch.Tensor,
1304
+ attention_mask: Optional[torch.Tensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1307
+ output_attentions: Optional[bool] = False,
1308
+ output_router_logits: Optional[bool] = False,
1309
+ use_cache: Optional[bool] = False,
1310
+ **kwargs,
1311
+ ) -> Tuple[
1312
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1313
+ ]:
1314
+ """
1315
+ Args:
1316
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1317
+ attention_mask (`torch.FloatTensor`, *optional*):
1318
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1319
+ query_sequence_length, key_sequence_length)` if default attention is used.
1320
+ output_attentions (`bool`, *optional*):
1321
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1322
+ returned tensors for more detail.
1323
+ use_cache (`bool`, *optional*):
1324
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1325
+ (see `past_key_values`).
1326
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1327
+ """
1328
+ if "padding_mask" in kwargs:
1329
+ warnings.warn(
1330
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1331
+ )
1332
+ residual = hidden_states
1333
+
1334
+ hidden_states = self.input_layernorm(hidden_states)
1335
+
1336
+ # Self Attention
1337
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1338
+ hidden_states=hidden_states,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_value=past_key_value,
1342
+ output_attentions=output_attentions,
1343
+ use_cache=use_cache,
1344
+ **kwargs,
1345
+ )
1346
+ hidden_states = residual + hidden_states
1347
+
1348
+ # Fully Connected
1349
+ residual = hidden_states
1350
+ hidden_states = self.post_attention_layernorm(hidden_states)
1351
+ hidden_states = self.mlp(hidden_states)
1352
+ if isinstance(hidden_states, tuple):
1353
+ hidden_states, router_scores = hidden_states
1354
+ else:
1355
+ router_scores = None
1356
+ hidden_states = residual + hidden_states
1357
+
1358
+ outputs = (hidden_states,)
1359
+
1360
+ if output_attentions:
1361
+ outputs += (self_attn_weights,)
1362
+
1363
+ if use_cache:
1364
+ outputs += (present_key_value,)
1365
+
1366
+ if output_router_logits:
1367
+ outputs += (router_scores, )
1368
+
1369
+ return outputs
1370
+
1371
+
1372
+ DeepseekV3_START_DOCSTRING = r"""
1373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1375
+ etc.)
1376
+
1377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1379
+ and behavior.
1380
+
1381
+ Parameters:
1382
+ config ([`TinyDeepseekV3Config`]):
1383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1384
+ load the weights associated with the model, only the configuration. Check out the
1385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1386
+ """
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1391
+ DeepseekV3_START_DOCSTRING,
1392
+ )
1393
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1394
+ config_class = TinyDeepseekV3Config
1395
+ base_model_prefix = "model"
1396
+ supports_gradient_checkpointing = True
1397
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1398
+ _skip_keys_device_placement = "past_key_values"
1399
+ _supports_flash_attn_2 = True
1400
+ _supports_cache_class = True
1401
+
1402
+ def _init_weights(self, module):
1403
+ std = self.config.initializer_range
1404
+ if isinstance(module, nn.Linear):
1405
+ module.weight.data.normal_(mean=0.0, std=std)
1406
+ if module.bias is not None:
1407
+ module.bias.data.zero_()
1408
+ elif isinstance(module, nn.Embedding):
1409
+ module.weight.data.normal_(mean=0.0, std=std)
1410
+ if module.padding_idx is not None:
1411
+ module.weight.data[module.padding_idx].zero_()
1412
+
1413
+
1414
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1415
+ Args:
1416
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1417
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1418
+ it.
1419
+
1420
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1421
+ [`PreTrainedTokenizer.__call__`] for details.
1422
+
1423
+ [What are input IDs?](../glossary#input-ids)
1424
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1425
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1426
+
1427
+ - 1 for tokens that are **not masked**,
1428
+ - 0 for tokens that are **masked**.
1429
+
1430
+ [What are attention masks?](../glossary#attention-mask)
1431
+
1432
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1433
+ [`PreTrainedTokenizer.__call__`] for details.
1434
+
1435
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1436
+ `past_key_values`).
1437
+
1438
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1439
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1440
+ information on the default strategy.
1441
+
1442
+ - 1 indicates the head is **not masked**,
1443
+ - 0 indicates the head is **masked**.
1444
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1446
+ config.n_positions - 1]`.
1447
+
1448
+ [What are position IDs?](../glossary#position-ids)
1449
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1450
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1451
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1452
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1453
+
1454
+ Two formats are allowed:
1455
+ - a [`~cache_utils.Cache`] instance;
1456
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1457
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1458
+ cache format.
1459
+
1460
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1461
+ legacy cache format will be returned.
1462
+
1463
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1464
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1465
+ of shape `(batch_size, sequence_length)`.
1466
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1467
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1468
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1469
+ model's internal embedding lookup matrix.
1470
+ use_cache (`bool`, *optional*):
1471
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1472
+ `past_key_values`).
1473
+ output_attentions (`bool`, *optional*):
1474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1475
+ tensors for more detail.
1476
+ output_hidden_states (`bool`, *optional*):
1477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1478
+ more detail.
1479
+ return_dict (`bool`, *optional*):
1480
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1481
+ """
1482
+
1483
+
1484
+ @add_start_docstrings(
1485
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1486
+ DeepseekV3_START_DOCSTRING,
1487
+ )
1488
+ class TinyDeepseekV3Model(DeepseekV3PreTrainedModel):
1489
+ """
1490
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1491
+
1492
+ Args:
1493
+ config: TinyDeepseekV3Config
1494
+ """
1495
+
1496
+ def __init__(self, config: TinyDeepseekV3Config):
1497
+ super().__init__(config)
1498
+ self.padding_idx = config.pad_token_id
1499
+ self.vocab_size = config.vocab_size
1500
+
1501
+ self.n_future_tokens = config.n_future_tokens
1502
+ assert self.n_future_tokens > 0, "At least one future token prediction needed, i.e., n_future_tokens>0"
1503
+ assert config.num_hidden_layers > self.n_future_tokens, "The number of layer should larger than the n_future_tokens, i.e., config.num_hidden_layers > config.n_future_tokens"
1504
+
1505
+ self.embed_tokens = nn.Embedding(
1506
+ config.vocab_size, config.hidden_size, self.padding_idx
1507
+ )
1508
+ self.layers = nn.ModuleList(
1509
+ [
1510
+ DeepseekV3DecoderLayer(config, layer_idx)
1511
+ for layer_idx in range(config.num_hidden_layers - self.n_future_tokens + 1)
1512
+ ]
1513
+ )
1514
+
1515
+ # Additional prediction heads for multi-token prediction.
1516
+ # `layer_id` counts contiguously from the first Transformer block.
1517
+ self.extra_heads = nn.ModuleList(
1518
+ [
1519
+ DeepseekV3DecoderLayer(config, len(self.layers) + layer_idx)
1520
+ for layer_idx in range(self.n_future_tokens - 1)
1521
+ ]
1522
+ )
1523
+ self.extra_heads_input_norms = nn.ModuleList(
1524
+ [
1525
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1526
+ for _ in range(self.n_future_tokens - 1)
1527
+ ]
1528
+ )
1529
+ self.extra_heads_hidden_norms = nn.ModuleList(
1530
+ [
1531
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1532
+ for _ in range(self.n_future_tokens - 1)
1533
+ ]
1534
+ )
1535
+ self.extra_heads_projections = nn.ModuleList(
1536
+ [
1537
+ nn.Linear(config.hidden_size*2, config.hidden_size, bias=False)
1538
+ for _ in range(self.n_future_tokens - 1)
1539
+ ]
1540
+ )
1541
+
1542
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1543
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1544
+
1545
+ self.gradient_checkpointing = False
1546
+ # Initialize weights and apply final processing
1547
+ self.post_init()
1548
+
1549
+ def get_input_embeddings(self):
1550
+ return self.embed_tokens
1551
+
1552
+ def set_input_embeddings(self, value):
1553
+ self.embed_tokens = value
1554
+
1555
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1556
+ def forward(
1557
+ self,
1558
+ input_ids: torch.LongTensor = None,
1559
+ attention_mask: Optional[torch.Tensor] = None,
1560
+ position_ids: Optional[torch.LongTensor] = None,
1561
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1562
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1563
+ use_cache: Optional[bool] = None,
1564
+ output_attentions: Optional[bool] = None,
1565
+ output_hidden_states: Optional[bool] = None,
1566
+ output_router_logits: Optional[bool] = None,
1567
+ return_dict: Optional[bool] = None,
1568
+ return_all_heads: Optional[bool] = False,
1569
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1570
+ output_attentions = (
1571
+ output_attentions
1572
+ if output_attentions is not None
1573
+ else self.config.output_attentions
1574
+ )
1575
+ output_router_logits = (
1576
+ output_router_logits
1577
+ if output_router_logits is not None
1578
+ else self.config.output_router_logits
1579
+ )
1580
+ output_hidden_states = (
1581
+ output_hidden_states
1582
+ if output_hidden_states is not None
1583
+ else self.config.output_hidden_states
1584
+ )
1585
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1586
+
1587
+ return_dict = (
1588
+ return_dict if return_dict is not None else self.config.use_return_dict
1589
+ )
1590
+
1591
+ # retrieve input_ids and inputs_embeds
1592
+ if input_ids is not None and inputs_embeds is not None:
1593
+ raise ValueError(
1594
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1595
+ )
1596
+ elif input_ids is not None:
1597
+ batch_size, seq_length = input_ids.shape[:2]
1598
+ elif inputs_embeds is not None:
1599
+ batch_size, seq_length = inputs_embeds.shape[:2]
1600
+ else:
1601
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1602
+
1603
+ past_key_values_length = 0
1604
+ if use_cache:
1605
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1606
+ if use_legacy_cache:
1607
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1608
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1609
+
1610
+ if position_ids is None:
1611
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1612
+ position_ids = torch.arange(
1613
+ past_key_values_length,
1614
+ seq_length + past_key_values_length,
1615
+ dtype=torch.long,
1616
+ device=device,
1617
+ )
1618
+ position_ids = position_ids.unsqueeze(0)
1619
+
1620
+ if inputs_embeds is None:
1621
+ inputs_embeds = self.embed_tokens(input_ids)
1622
+
1623
+ if self._use_flash_attention_2:
1624
+ # 2d mask is passed through the layers
1625
+ attention_mask = (
1626
+ attention_mask
1627
+ if (attention_mask is not None and 0 in attention_mask)
1628
+ else None
1629
+ )
1630
+ else:
1631
+ # 4d mask is passed through the layers
1632
+ attention_mask = _prepare_4d_causal_attention_mask(
1633
+ attention_mask,
1634
+ (batch_size, seq_length),
1635
+ inputs_embeds,
1636
+ past_key_values_length,
1637
+ )
1638
+
1639
+ # embed positions
1640
+ hidden_states = inputs_embeds
1641
+
1642
+ # decoder layers
1643
+ all_hidden_states = () if output_hidden_states or return_all_heads else None
1644
+ all_self_attns = () if output_attentions else None
1645
+ all_router_logits = () if output_router_logits else None
1646
+ next_decoder_cache = None
1647
+
1648
+ # layers = self.layers if not return_all_heads else self.layers + self.extra_heads
1649
+ for decoder_layer in self.layers:
1650
+ if output_hidden_states:
1651
+ all_hidden_states += (hidden_states,)
1652
+
1653
+ layer_outputs = decoder_layer(
1654
+ hidden_states,
1655
+ attention_mask=attention_mask,
1656
+ position_ids=position_ids,
1657
+ past_key_value=past_key_values,
1658
+ output_attentions=output_attentions,
1659
+ output_router_logits=output_router_logits,
1660
+ use_cache=use_cache,
1661
+ )
1662
+
1663
+ hidden_states = layer_outputs[0]
1664
+
1665
+ if use_cache:
1666
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1667
+
1668
+ if output_attentions:
1669
+ all_self_attns += (layer_outputs[1],)
1670
+
1671
+ if output_router_logits and layer_outputs[-1] is not None:
1672
+ all_router_logits += (layer_outputs[-1],)
1673
+
1674
+ # Multi-token prediction
1675
+ if return_all_heads:
1676
+ first_token_hidden_state = self.norm(hidden_states) # first next token prediction
1677
+
1678
+ all_hidden_states += (first_token_hidden_state,)
1679
+
1680
+ for extra_head_idx in range(len(self.extra_heads)):
1681
+ hidden_states = torch.cat(
1682
+ (self.extra_heads_input_norms[extra_head_idx](inputs_embeds),
1683
+ self.extra_heads_hidden_norms[extra_head_idx](hidden_states)),
1684
+ dim=-1
1685
+ ) # (bsz, seq_len, dim*2)
1686
+
1687
+ hidden_states = self.extra_heads_projections[extra_head_idx](hidden_states)
1688
+ # (bsz, seq_len, dim)
1689
+
1690
+ layer_outputs = self.extra_heads[extra_head_idx](
1691
+ hidden_states,
1692
+ attention_mask=attention_mask,
1693
+ position_ids=position_ids,
1694
+ past_key_value=past_key_values,
1695
+ output_attentions=output_attentions,
1696
+ use_cache=use_cache,
1697
+ )
1698
+
1699
+ hidden_states = layer_outputs[0]
1700
+
1701
+ if use_cache:
1702
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1703
+
1704
+ if output_attentions:
1705
+ all_self_attns += (layer_outputs[1],)
1706
+
1707
+ # always return extra_head hidden_states with norm
1708
+ all_hidden_states += (self.norm(hidden_states),)
1709
+
1710
+ hidden_states = first_token_hidden_state
1711
+
1712
+ else:
1713
+ hidden_states = self.norm(hidden_states)
1714
+
1715
+ # add hidden states from the last decoder layer
1716
+ if output_hidden_states:
1717
+ all_hidden_states += (hidden_states,)
1718
+
1719
+ next_cache = None
1720
+ if use_cache:
1721
+ next_cache = (
1722
+ next_decoder_cache.to_legacy_cache()
1723
+ if use_legacy_cache
1724
+ else next_decoder_cache
1725
+ )
1726
+ if not return_dict:
1727
+ return tuple(
1728
+ v
1729
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1730
+ if v is not None
1731
+ )
1732
+ return MoeModelOutputWithPast(
1733
+ last_hidden_state=hidden_states,
1734
+ past_key_values=next_cache,
1735
+ hidden_states=all_hidden_states,
1736
+ attentions=all_self_attns,
1737
+ router_logits=all_router_logits
1738
+ )
1739
+
1740
+
1741
+ class TinyDeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1742
+ _tied_weights_keys = ["lm_head.weight"]
1743
+
1744
+ def __init__(self, config):
1745
+ super().__init__(config)
1746
+ self.model = TinyDeepseekV3Model(config)
1747
+ self.vocab_size = config.vocab_size
1748
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1749
+ self.n_future_tokens = config.n_future_tokens
1750
+ self.mtp_loss_lambda = config.mtp_loss_lambda
1751
+
1752
+ self.seq_aux = config.seq_aux
1753
+ self.aux_loss_alpha = config.aux_loss_alpha
1754
+ self.n_routed_experts = config.n_routed_experts
1755
+ self.num_experts_per_tok = config.num_experts_per_tok
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ output_router_logits: Optional[bool] = None,
1794
+ return_dict: Optional[bool] = None,
1795
+ return_all_heads: Optional[bool] = False,
1796
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1797
+ r"""
1798
+ Args:
1799
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1800
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1801
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1802
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1803
+
1804
+ Returns:
1805
+
1806
+ Example:
1807
+
1808
+ ```python
1809
+ >>> from transformers import AutoTokenizer, TinyDeepseekV3ForCausalLM
1810
+
1811
+ >>> model = TinyDeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1812
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1813
+
1814
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1815
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1816
+
1817
+ >>> # Generate
1818
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1819
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1820
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1821
+ ```"""
1822
+ output_attentions = (
1823
+ output_attentions
1824
+ if output_attentions is not None
1825
+ else self.config.output_attentions
1826
+ )
1827
+ output_router_logits = (
1828
+ output_router_logits
1829
+ if output_router_logits is not None
1830
+ else self.config.output_router_logits
1831
+ )
1832
+ output_hidden_states = (
1833
+ output_hidden_states
1834
+ if output_hidden_states is not None
1835
+ else self.config.output_hidden_states
1836
+ )
1837
+ return_dict = (
1838
+ return_dict if return_dict is not None else self.config.use_return_dict
1839
+ )
1840
+
1841
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1842
+ outputs = self.model(
1843
+ input_ids=input_ids,
1844
+ attention_mask=attention_mask,
1845
+ position_ids=position_ids,
1846
+ past_key_values=past_key_values,
1847
+ inputs_embeds=inputs_embeds,
1848
+ use_cache=use_cache,
1849
+ output_attentions=output_attentions,
1850
+ output_hidden_states=output_hidden_states,
1851
+ output_router_logits=output_router_logits or self.seq_aux,
1852
+ return_dict=return_dict,
1853
+ return_all_heads=return_all_heads,
1854
+ )
1855
+
1856
+ if not return_all_heads:
1857
+ hidden_states = outputs[0]
1858
+ logits = self.lm_head(hidden_states)
1859
+ logits = logits.float()
1860
+
1861
+ loss = None
1862
+ if labels is not None:
1863
+ # Shift so that tokens < n predict n
1864
+ shift_logits = logits[..., :-1, :].contiguous()
1865
+ shift_labels = labels[..., 1:].contiguous()
1866
+ # Flatten the tokens
1867
+ loss_fct = CrossEntropyLoss()
1868
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1869
+ shift_labels = shift_labels.view(-1)
1870
+ # Enable model parallelism
1871
+ shift_labels = shift_labels.to(shift_logits.device)
1872
+ loss = loss_fct(shift_logits, shift_labels)
1873
+ else:
1874
+ # Multi-token prediction
1875
+ mtp_hidden_states = outputs[2][-self.n_future_tokens:]
1876
+ first_token_loss = None
1877
+ mtp_loss = None
1878
+ loss = None
1879
+
1880
+ add_loss = lambda x, y: y if x is None else x+y
1881
+
1882
+ for token_idx in range(self.n_future_tokens):
1883
+ logits = self.lm_head(mtp_hidden_states[token_idx])
1884
+ logits = logits.float()
1885
+
1886
+ if labels is not None:
1887
+ n_shift = token_idx + 1
1888
+ if n_shift > (logits.shape[1]-1):
1889
+ continue
1890
+
1891
+ # Shift so that tokens < n predict n
1892
+ shift_logits = logits[..., :-n_shift, :].contiguous()
1893
+ shift_labels = labels[..., n_shift:].contiguous()
1894
+ # Flatten the tokens
1895
+ loss_fct = CrossEntropyLoss()
1896
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1897
+ shift_labels = shift_labels.view(-1)
1898
+ # Enable model parallelism
1899
+ shift_labels = shift_labels.to(shift_logits.device)
1900
+
1901
+ loss = add_loss(loss, loss_fct(shift_logits, shift_labels))
1902
+
1903
+ if token_idx == 0:
1904
+ first_token_loss = add_loss(first_token_loss, loss)
1905
+ else:
1906
+ mtp_loss = add_loss(mtp_loss, loss)
1907
+
1908
+ if labels is not None:
1909
+ loss = first_token_loss + self.mtp_loss_lambda * mtp_loss / (self.n_future_tokens - 1)
1910
+ # ljh Loss debug
1911
+ # print(f"loss: {loss} first_token_loss: {first_token_loss}, mtp_loss: {mtp_loss} with n_future_tokens {self.n_future_tokens} and mtp_loss_lambda {self.mtp_loss_lambda}")
1912
+
1913
+
1914
+ # balancing loss
1915
+ aux_loss = None
1916
+ if self.seq_aux:
1917
+ aux_loss = load_balancing_loss_func(
1918
+ gate_logits=outputs.router_logits if return_dict else outputs[-1],
1919
+ num_experts=self.n_routed_experts,
1920
+ top_k=self.num_experts_per_tok,
1921
+ attention_mask=attention_mask,
1922
+ )
1923
+ aux_loss = self.aux_loss_alpha * aux_loss
1924
+ # ljh Loss debug
1925
+ # print(f"loss: {loss}, aux_loss: {aux_loss}")
1926
+ if labels is not None:
1927
+ loss += aux_loss.to(loss.device) # make sure to reside in the same device
1928
+
1929
+ if not return_dict:
1930
+ output = (logits,) + outputs[1:]
1931
+ if output_router_logits:
1932
+ output = (aux_loss,) + output
1933
+ return (loss,) + output if loss is not None else output
1934
+
1935
+ return MoeCausalLMOutputWithPast(
1936
+ loss=loss,
1937
+ logits=logits,
1938
+ past_key_values=outputs.past_key_values,
1939
+ hidden_states=outputs.hidden_states,
1940
+ attentions=outputs.attentions,
1941
+ router_logits=outputs.router_logits
1942
+ )
1943
+
1944
+ def prepare_inputs_for_generation(
1945
+ self,
1946
+ input_ids,
1947
+ past_key_values=None,
1948
+ attention_mask=None,
1949
+ inputs_embeds=None,
1950
+ **kwargs,
1951
+ ):
1952
+ if past_key_values is not None:
1953
+ if isinstance(past_key_values, Cache):
1954
+ cache_length = past_key_values.get_seq_length()
1955
+ past_length = past_key_values.seen_tokens
1956
+ max_cache_length = past_key_values.get_max_length()
1957
+ else:
1958
+ cache_length = past_length = past_key_values[0][0].shape[2]
1959
+ max_cache_length = None
1960
+
1961
+ # Keep only the unprocessed tokens:
1962
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1963
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1964
+ # input)
1965
+ if (
1966
+ attention_mask is not None
1967
+ and attention_mask.shape[1] > input_ids.shape[1]
1968
+ ):
1969
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1970
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1971
+ # input_ids based on the past_length.
1972
+ elif past_length < input_ids.shape[1]:
1973
+ input_ids = input_ids[:, past_length:]
1974
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1975
+
1976
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1977
+ if (
1978
+ max_cache_length is not None
1979
+ and attention_mask is not None
1980
+ and cache_length + input_ids.shape[1] > max_cache_length
1981
+ ):
1982
+ attention_mask = attention_mask[:, -max_cache_length:]
1983
+
1984
+ position_ids = kwargs.get("position_ids", None)
1985
+ if attention_mask is not None and position_ids is None:
1986
+ # create position_ids on the fly for batch generation
1987
+ position_ids = attention_mask.long().cumsum(-1) - 1
1988
+ position_ids.masked_fill_(attention_mask == 0, 1)
1989
+ if past_key_values:
1990
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1991
+
1992
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1993
+ if inputs_embeds is not None and past_key_values is None:
1994
+ model_inputs = {"inputs_embeds": inputs_embeds}
1995
+ else:
1996
+ model_inputs = {"input_ids": input_ids}
1997
+
1998
+ model_inputs.update(
1999
+ {
2000
+ "position_ids": position_ids,
2001
+ "past_key_values": past_key_values,
2002
+ "use_cache": kwargs.get("use_cache"),
2003
+ "attention_mask": attention_mask,
2004
+ }
2005
+ )
2006
+ return model_inputs
2007
+
2008
+ @staticmethod
2009
+ def _reorder_cache(past_key_values, beam_idx):
2010
+ reordered_past = ()
2011
+ for layer_past in past_key_values:
2012
+ reordered_past += (
2013
+ tuple(
2014
+ past_state.index_select(0, beam_idx.to(past_state.device))
2015
+ for past_state in layer_past
2016
+ ),
2017
+ )
2018
+ return reordered_past
2019
+
2020
+
2021
+ @add_start_docstrings(
2022
+ """
2023
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
2024
+
2025
+ [`TinyDeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2026
+ (e.g. GPT-2) do.
2027
+
2028
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2029
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2030
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2031
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2032
+ each row of the batch).
2033
+ """,
2034
+ DeepseekV3_START_DOCSTRING,
2035
+ )
2036
+ class TinyDeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
2037
+ def __init__(self, config):
2038
+ super().__init__(config)
2039
+ self.num_labels = config.num_labels
2040
+ self.model = TinyDeepseekV3Model(config)
2041
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2042
+
2043
+ # Initialize weights and apply final processing
2044
+ self.post_init()
2045
+
2046
+ def get_input_embeddings(self):
2047
+ return self.model.embed_tokens
2048
+
2049
+ def set_input_embeddings(self, value):
2050
+ self.model.embed_tokens = value
2051
+
2052
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
2053
+ def forward(
2054
+ self,
2055
+ input_ids: torch.LongTensor = None,
2056
+ attention_mask: Optional[torch.Tensor] = None,
2057
+ position_ids: Optional[torch.LongTensor] = None,
2058
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2059
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2060
+ labels: Optional[torch.LongTensor] = None,
2061
+ use_cache: Optional[bool] = None,
2062
+ output_attentions: Optional[bool] = None,
2063
+ output_hidden_states: Optional[bool] = None,
2064
+ return_dict: Optional[bool] = None,
2065
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2066
+ r"""
2067
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2068
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2069
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2070
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2071
+ """
2072
+ return_dict = (
2073
+ return_dict if return_dict is not None else self.config.use_return_dict
2074
+ )
2075
+
2076
+ transformer_outputs = self.model(
2077
+ input_ids,
2078
+ attention_mask=attention_mask,
2079
+ position_ids=position_ids,
2080
+ past_key_values=past_key_values,
2081
+ inputs_embeds=inputs_embeds,
2082
+ use_cache=use_cache,
2083
+ output_attentions=output_attentions,
2084
+ output_hidden_states=output_hidden_states,
2085
+ return_dict=return_dict,
2086
+ )
2087
+ hidden_states = transformer_outputs[0]
2088
+ logits = self.score(hidden_states)
2089
+
2090
+ if input_ids is not None:
2091
+ batch_size = input_ids.shape[0]
2092
+ else:
2093
+ batch_size = inputs_embeds.shape[0]
2094
+
2095
+ if self.config.pad_token_id is None and batch_size != 1:
2096
+ raise ValueError(
2097
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2098
+ )
2099
+ if self.config.pad_token_id is None:
2100
+ sequence_lengths = -1
2101
+ else:
2102
+ if input_ids is not None:
2103
+ sequence_lengths = (
2104
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2105
+ ).to(logits.device)
2106
+ else:
2107
+ sequence_lengths = -1
2108
+
2109
+ pooled_logits = logits[
2110
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2111
+ ]
2112
+
2113
+ loss = None
2114
+ if labels is not None:
2115
+ labels = labels.to(logits.device)
2116
+ if self.config.problem_type is None:
2117
+ if self.num_labels == 1:
2118
+ self.config.problem_type = "regression"
2119
+ elif self.num_labels > 1 and (
2120
+ labels.dtype == torch.long or labels.dtype == torch.int
2121
+ ):
2122
+ self.config.problem_type = "single_label_classification"
2123
+ else:
2124
+ self.config.problem_type = "multi_label_classification"
2125
+
2126
+ if self.config.problem_type == "regression":
2127
+ loss_fct = MSELoss()
2128
+ if self.num_labels == 1:
2129
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2130
+ else:
2131
+ loss = loss_fct(pooled_logits, labels)
2132
+ elif self.config.problem_type == "single_label_classification":
2133
+ loss_fct = CrossEntropyLoss()
2134
+ loss = loss_fct(
2135
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2136
+ )
2137
+ elif self.config.problem_type == "multi_label_classification":
2138
+ loss_fct = BCEWithLogitsLoss()
2139
+ loss = loss_fct(pooled_logits, labels)
2140
+ if not return_dict:
2141
+ output = (pooled_logits,) + transformer_outputs[1:]
2142
+ return ((loss,) + output) if loss is not None else output
2143
+
2144
+ return SequenceClassifierOutputWithPast(
2145
+ loss=loss,
2146
+ logits=pooled_logits,
2147
+ past_key_values=transformer_outputs.past_key_values,
2148
+ hidden_states=transformer_outputs.hidden_states,
2149
+ attentions=transformer_outputs.attentions,
2150
+ )
checkpoint-10000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-10000/tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 131072,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{{'<|Assistant|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}"
35
+ }
checkpoint-11000/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyDeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tinydeepseek.TinyDeepseekV3Config",
9
+ "AutoModel": "modeling_tinydeepseek.TinyDeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_tinydeepseek.TinyDeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.0001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4864,
21
+ "kv_lora_rank": 128,
22
+ "lossfreebalance_update_rate": 0.001,
23
+ "max_position_embeddings": 163840,
24
+ "model_type": "tinydeepseek_v3",
25
+ "moe_intermediate_size": 608,
26
+ "moe_layer_freq": 1,
27
+ "mtp_loss_lambda": 0.1,
28
+ "n_future_tokens": 2,
29
+ "n_group": 8,
30
+ "n_routed_experts": 64,
31
+ "n_shared_experts": 2,
32
+ "norm_topk_prob": true,
33
+ "num_attention_heads": 8,
34
+ "num_experts_per_tok": 6,
35
+ "num_hidden_layers": 27,
36
+ "num_key_value_heads": 8,
37
+ "num_nextn_predict_layers": 1,
38
+ "output_router_logits": false,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": null,
41
+ "qk_nope_head_dim": 32,
42
+ "qk_rope_head_dim": 16,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 0.707,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 1.0,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": false,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.48.3",
62
+ "use_cache": true,
63
+ "use_lossfreebalance": false,
64
+ "v_head_dim": 32,
65
+ "vocab_size": 129280
66
+ }
checkpoint-11000/configuration_tinydeepseek.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TinyDeepseekV3Config(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
+ n_future_tokens (int):
104
+ Number of prediction heads in the model (= 1 + `len(extra_heads)`).
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "tinydeepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'aux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.0001,
147
+ seq_aux=True,
148
+ output_router_logits=False,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ n_future_tokens=1,
164
+ mtp_loss_lambda=0.1,
165
+ use_lossfreebalance=True,
166
+ lossfreebalance_update_rate=0.001,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.moe_intermediate_size = moe_intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_nextn_predict_layers = num_nextn_predict_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.n_shared_experts = n_shared_experts
178
+ self.n_routed_experts = n_routed_experts
179
+ self.ep_size = ep_size
180
+ self.routed_scaling_factor = routed_scaling_factor
181
+ self.kv_lora_rank = kv_lora_rank
182
+ self.q_lora_rank = q_lora_rank if q_lora_rank else None
183
+ self.qk_rope_head_dim = qk_rope_head_dim
184
+ self.v_head_dim = v_head_dim
185
+ self.qk_nope_head_dim = qk_nope_head_dim
186
+ self.topk_method = topk_method
187
+ self.n_group = n_group
188
+ self.topk_group = topk_group
189
+ self.num_experts_per_tok = num_experts_per_tok
190
+ self.moe_layer_freq = moe_layer_freq
191
+ self.first_k_dense_replace = first_k_dense_replace
192
+ self.norm_topk_prob = norm_topk_prob
193
+ self.scoring_func = scoring_func
194
+ self.aux_loss_alpha = aux_loss_alpha
195
+ self.seq_aux = seq_aux
196
+ self.output_router_logits = output_router_logits
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.rms_norm_eps = rms_norm_eps
205
+ self.pretraining_tp = pretraining_tp
206
+ self.use_cache = use_cache
207
+ self.rope_theta = rope_theta
208
+ self.rope_scaling = rope_scaling
209
+ self.attention_bias = attention_bias
210
+ self.attention_dropout = attention_dropout
211
+ self.n_future_tokens = n_future_tokens
212
+ self.mtp_loss_lambda = mtp_loss_lambda
213
+ self.use_lossfreebalance = use_lossfreebalance
214
+ self.lossfreebalance_update_rate = lossfreebalance_update_rate
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
checkpoint-11000/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.48.3",
6
+ "use_cache": false
7
+ }
checkpoint-11000/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c45b84888d3985aaaac97452d81366a239e6ec436bbd4bf519c05b98b20c2362
3
+ size 5000243440
checkpoint-11000/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97165cc1b3a3f71425ed42c115567f23eee808ae77521ea084bdf273c5e52cfa
3
+ size 1591021104
checkpoint-11000/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-11000/modeling_tinydeepseek.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MoeModelOutputWithPast,
40
+ MoeCausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ # is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_tinydeepseek import TinyDeepseekV3Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ # if not is_torch_greater_or_equal_than_1_13:
70
+ # import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "TinyDeepseekV3Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
94
+ def load_balancing_loss_func(
95
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
96
+ num_experts: Optional[int] = None,
97
+ top_k=2,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ ) -> Union[torch.Tensor, int]:
100
+ r"""
101
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
102
+
103
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
104
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
105
+ experts is too unbalanced.
106
+
107
+ Args:
108
+ gate_logits:
109
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
110
+ shape [batch_size X sequence_length, num_experts].
111
+ num_experts:
112
+ Number of experts
113
+ top_k:
114
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
115
+ parameter.
116
+ attention_mask (`torch.Tensor`, *optional*):
117
+ The attention_mask used in forward function
118
+ shape [batch_size X sequence_length] if not None.
119
+
120
+ Returns:
121
+ The auxiliary loss.
122
+ """
123
+ if gate_logits is None or not isinstance(gate_logits, tuple):
124
+ return 0
125
+
126
+ if isinstance(gate_logits, tuple):
127
+ compute_device = gate_logits[0].device
128
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
129
+
130
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
131
+
132
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
133
+
134
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
135
+
136
+ if attention_mask is None:
137
+ # Compute the percentage of tokens routed to each experts
138
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
139
+
140
+ # Compute the average probability of routing to these experts
141
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
142
+ else:
143
+ batch_size, sequence_length = attention_mask.shape
144
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
145
+
146
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
147
+ expert_attention_mask = (
148
+ attention_mask[None, :, :, None, None]
149
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
150
+ .reshape(-1, top_k, num_experts)
151
+ .to(compute_device)
152
+ )
153
+
154
+ # Compute the percentage of tokens routed to each experts
155
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
156
+ expert_attention_mask, dim=0
157
+ )
158
+
159
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
160
+ router_per_expert_attention_mask = (
161
+ attention_mask[None, :, :, None]
162
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
163
+ .reshape(-1, num_experts)
164
+ .to(compute_device)
165
+ )
166
+
167
+ # Compute the average probability of routing to these experts
168
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
169
+ router_per_expert_attention_mask, dim=0
170
+ )
171
+
172
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
173
+ return overall_loss * num_experts
174
+
175
+
176
+ class DeepseekV3RMSNorm(nn.Module):
177
+ def __init__(self, hidden_size, eps=1e-6):
178
+ """
179
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
180
+ """
181
+ super().__init__()
182
+ self.weight = nn.Parameter(torch.ones(hidden_size))
183
+ self.variance_epsilon = eps
184
+
185
+ def forward(self, hidden_states):
186
+ input_dtype = hidden_states.dtype
187
+ hidden_states = hidden_states.to(torch.float32)
188
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
189
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
190
+ return self.weight * hidden_states.to(input_dtype)
191
+
192
+
193
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
194
+
195
+
196
+ class DeepseekV3RotaryEmbedding(nn.Module):
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
198
+ super().__init__()
199
+
200
+ self.dim = dim
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.base = base
203
+ inv_freq = 1.0 / (
204
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
205
+ )
206
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
207
+
208
+ # Build here to make `torch.jit.trace` work.
209
+ self._set_cos_sin_cache(
210
+ seq_len=max_position_embeddings,
211
+ device=self.inv_freq.device,
212
+ dtype=torch.get_default_dtype(),
213
+ )
214
+ self.max_seq_len_cached = None
215
+
216
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
217
+ self.max_seq_len_cached = seq_len
218
+ t = torch.arange(
219
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
220
+ )
221
+
222
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
223
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
224
+ emb = torch.cat((freqs, freqs), dim=-1)
225
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
226
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
227
+
228
+ def forward(self, x, seq_len=None):
229
+ # x: [bs, num_attention_heads, seq_len, head_size]
230
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
231
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
232
+
233
+ return (
234
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
235
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
236
+ )
237
+
238
+
239
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
240
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
241
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ max_position_embeddings=2048,
247
+ base=10000,
248
+ device=None,
249
+ scaling_factor=1.0,
250
+ ):
251
+ self.scaling_factor = scaling_factor
252
+ super().__init__(dim, max_position_embeddings, base, device)
253
+
254
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
255
+ self.max_seq_len_cached = seq_len
256
+ t = torch.arange(
257
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
258
+ )
259
+ t = t / self.scaling_factor
260
+
261
+ freqs = torch.outer(t, self.inv_freq)
262
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
263
+ emb = torch.cat((freqs, freqs), dim=-1)
264
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
265
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
266
+
267
+
268
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
269
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
270
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
271
+
272
+ def __init__(
273
+ self,
274
+ dim,
275
+ max_position_embeddings=2048,
276
+ base=10000,
277
+ device=None,
278
+ scaling_factor=1.0,
279
+ ):
280
+ self.scaling_factor = scaling_factor
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
+
286
+ if seq_len > self.max_position_embeddings:
287
+ base = self.base * (
288
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
289
+ - (self.scaling_factor - 1)
290
+ ) ** (self.dim / (self.dim - 2))
291
+ inv_freq = 1.0 / (
292
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
293
+ )
294
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
295
+
296
+ t = torch.arange(
297
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
298
+ )
299
+
300
+ freqs = torch.outer(t, self.inv_freq)
301
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
302
+ emb = torch.cat((freqs, freqs), dim=-1)
303
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
304
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
305
+
306
+
307
+ # Inverse dim formula to find dim based on number of rotations
308
+ def yarn_find_correction_dim(
309
+ num_rotations, dim, base=10000, max_position_embeddings=2048
310
+ ):
311
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
312
+ 2 * math.log(base)
313
+ )
314
+
315
+
316
+ # Find dim range bounds based on rotations
317
+ def yarn_find_correction_range(
318
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
319
+ ):
320
+ low = math.floor(
321
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
322
+ )
323
+ high = math.ceil(
324
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
325
+ )
326
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
327
+
328
+
329
+ def yarn_get_mscale(scale=1, mscale=1):
330
+ if scale <= 1:
331
+ return 1.0
332
+ return 0.1 * mscale * math.log(scale) + 1.0
333
+
334
+
335
+ def yarn_linear_ramp_mask(min, max, dim):
336
+ if min == max:
337
+ max += 0.001 # Prevent singularity
338
+
339
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
340
+ ramp_func = torch.clamp(linear_func, 0, 1)
341
+ return ramp_func
342
+
343
+
344
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
345
+
346
+ def __init__(
347
+ self,
348
+ dim,
349
+ max_position_embeddings=2048,
350
+ base=10000,
351
+ device=None,
352
+ scaling_factor=1.0,
353
+ original_max_position_embeddings=4096,
354
+ beta_fast=32,
355
+ beta_slow=1,
356
+ mscale=1,
357
+ mscale_all_dim=0,
358
+ ):
359
+ self.scaling_factor = scaling_factor
360
+ self.original_max_position_embeddings = original_max_position_embeddings
361
+ self.beta_fast = beta_fast
362
+ self.beta_slow = beta_slow
363
+ self.mscale = mscale
364
+ self.mscale_all_dim = mscale_all_dim
365
+ super().__init__(dim, max_position_embeddings, base, device)
366
+
367
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
368
+ self.max_seq_len_cached = seq_len
369
+ dim = self.dim
370
+
371
+ freq_extra = 1.0 / (
372
+ self.base
373
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
374
+ )
375
+ freq_inter = 1.0 / (
376
+ self.scaling_factor
377
+ * self.base
378
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
379
+ )
380
+
381
+ low, high = yarn_find_correction_range(
382
+ self.beta_fast,
383
+ self.beta_slow,
384
+ dim,
385
+ self.base,
386
+ self.original_max_position_embeddings,
387
+ )
388
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
389
+ device=device, dtype=torch.float32
390
+ )
391
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
392
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
393
+
394
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
395
+
396
+ freqs = torch.outer(t, inv_freq)
397
+
398
+ _mscale = float(
399
+ yarn_get_mscale(self.scaling_factor, self.mscale)
400
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
401
+ )
402
+
403
+ emb = torch.cat((freqs, freqs), dim=-1)
404
+ self.register_buffer(
405
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
406
+ )
407
+ self.register_buffer(
408
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
409
+ )
410
+
411
+
412
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
413
+ def rotate_half(x):
414
+ """Rotates half the hidden dims of the input."""
415
+ x1 = x[..., : x.shape[-1] // 2]
416
+ x2 = x[..., x.shape[-1] // 2 :]
417
+ return torch.cat((-x2, x1), dim=-1)
418
+
419
+
420
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
421
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
422
+ """Applies Rotary Position Embedding to the query and key tensors.
423
+
424
+ Args:
425
+ q (`torch.Tensor`): The query tensor.
426
+ k (`torch.Tensor`): The key tensor.
427
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
428
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
429
+ position_ids (`torch.Tensor`):
430
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
431
+ used to pass offsetted position ids when working with a KV-cache.
432
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
433
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
434
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
435
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
436
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
437
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
438
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
439
+ Returns:
440
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
441
+ """
442
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
443
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
444
+
445
+ b, h, s, d = q.shape
446
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
447
+
448
+ b, h, s, d = k.shape
449
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
450
+
451
+ q_embed = (q * cos) + (rotate_half(q) * sin)
452
+ k_embed = (k * cos) + (rotate_half(k) * sin)
453
+ return q_embed, k_embed
454
+
455
+
456
+ class DeepseekV3MLP(nn.Module):
457
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
458
+ super().__init__()
459
+ self.config = config
460
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
461
+ self.intermediate_size = (
462
+ config.intermediate_size if intermediate_size is None else intermediate_size
463
+ )
464
+
465
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
466
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
467
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
468
+ self.act_fn = ACT2FN[config.hidden_act]
469
+
470
+ def forward(self, x):
471
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
472
+ return down_proj
473
+
474
+
475
+ class MoEGate(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.config = config
479
+ self.top_k = config.num_experts_per_tok
480
+ self.n_routed_experts = config.n_routed_experts
481
+ self.routed_scaling_factor = config.routed_scaling_factor
482
+ self.scoring_func = config.scoring_func
483
+ self.seq_aux = config.seq_aux
484
+ self.topk_method = config.topk_method
485
+ self.n_group = config.n_group
486
+ self.topk_group = config.topk_group
487
+
488
+ # topk selection algorithm
489
+ self.norm_topk_prob = config.norm_topk_prob
490
+ self.gating_dim = config.hidden_size
491
+ self.weight = nn.Parameter(
492
+ torch.empty((self.n_routed_experts, self.gating_dim))
493
+ )
494
+ if self.topk_method == "noaux_tc":
495
+ self.e_score_correction_bias = nn.Parameter(
496
+ torch.empty((self.n_routed_experts))
497
+ )
498
+ elif self.topk_method == "aux_tc":
499
+ self.update_rate = config.lossfreebalance_update_rate
500
+ self.e_score_correction_bias = nn.Parameter(
501
+ torch.zeros((self.n_routed_experts))
502
+ )
503
+
504
+ self.reset_parameters()
505
+
506
+ def reset_parameters(self) -> None:
507
+ import torch.nn.init as init
508
+
509
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
510
+
511
+ def forward(self, hidden_states):
512
+ bsz, seq_len, h = hidden_states.shape
513
+ ### compute gating score
514
+ hidden_states = hidden_states.view(-1, h)
515
+ logits = F.linear(
516
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
517
+ )
518
+ if self.scoring_func == "sigmoid":
519
+ scores = logits.sigmoid()
520
+ else:
521
+ raise NotImplementedError(
522
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
523
+ )
524
+
525
+ ### select top-k experts
526
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
527
+ group_scores = (
528
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
529
+ ) # [n, n_group]
530
+ group_idx = torch.topk(
531
+ group_scores, k=self.topk_group, dim=-1, sorted=False
532
+ )[
533
+ 1
534
+ ] # [n, top_k_group]
535
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
536
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
537
+ score_mask = (
538
+ group_mask.unsqueeze(-1)
539
+ .expand(
540
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
541
+ )
542
+ .reshape(bsz * seq_len, -1)
543
+ ) # [n, e]
544
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
545
+ _, topk_idx = torch.topk(
546
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
547
+ )
548
+ topk_weight = scores.gather(1, topk_idx)
549
+
550
+ if self.topk_method == "aux_tc":
551
+ expert_counts = torch.bincount(
552
+ topk_idx.flatten(),
553
+ minlength=self.n_routed_experts
554
+ )
555
+
556
+ avg_count = expert_counts.float().mean()
557
+ #max_violation = torch.max(torch.abs(expert_counts.float() - avg_count) / avg_count)
558
+
559
+ # for monitoring the expert-balancing globallu
560
+ # min_violation = torch.min(expert_counts.float()) / avg_count
561
+ # max_violation = torch.max(expert_counts.float()) / avg_count
562
+ # return [min_violation.item(), max_violation.item()]
563
+
564
+ for expert_idx, expert_count in enumerate(expert_counts):
565
+ # b_i = b_i + u + sign(e_i)
566
+ # note: this is \bar{c_i} - c_i, NOT c_i - \bar{c_i}, which will push the network to
567
+ # be maximally unbalanced. Really important to get this part right!!!
568
+ count_error = avg_count - expert_count.float()
569
+ self.e_score_correction_bias.data[expert_idx] += (self.update_rate * torch.sign(count_error))
570
+
571
+ ### norm gate to sum 1
572
+ if self.top_k > 1 and self.norm_topk_prob:
573
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
574
+ topk_weight = topk_weight / denominator
575
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
576
+
577
+ return topk_idx, topk_weight, scores
578
+
579
+ class TinyDeepseekV3MoE(nn.Module):
580
+ """
581
+ A mixed expert module containing shared experts.
582
+ """
583
+
584
+ def __init__(self, config):
585
+ super().__init__()
586
+ self.config = config
587
+ self.num_experts_per_tok = config.num_experts_per_tok
588
+
589
+ if hasattr(config, "ep_size") and config.ep_size > 1:
590
+ assert config.ep_size == dist.get_world_size()
591
+ self.ep_size = config.ep_size
592
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
593
+ self.ep_rank = dist.get_rank()
594
+ self.experts = nn.ModuleList(
595
+ [
596
+ (
597
+ DeepseekV3MLP(
598
+ config, intermediate_size=config.moe_intermediate_size
599
+ )
600
+ if i >= self.ep_rank * self.experts_per_rank
601
+ and i < (self.ep_rank + 1) * self.experts_per_rank
602
+ else None
603
+ )
604
+ for i in range(config.n_routed_experts)
605
+ ]
606
+ )
607
+ else:
608
+ self.ep_size = 1
609
+ self.experts_per_rank = config.n_routed_experts
610
+ self.ep_rank = 0
611
+ self.experts = nn.ModuleList(
612
+ [
613
+ DeepseekV3MLP(
614
+ config, intermediate_size=config.moe_intermediate_size
615
+ )
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV3MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, router_scores = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if not self.training:
633
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
634
+ else:
635
+ # tinydeepseek: moe forward for training
636
+ y = self.moe_train(hidden_states, topk_idx, topk_weight).view(*orig_shape)
637
+ if self.config.n_shared_experts is not None:
638
+ y = y + self.shared_experts(identity)
639
+ return y, router_scores
640
+
641
+ @torch.no_grad()
642
+ def moe_infer(self, x, topk_ids, topk_weight):
643
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
644
+ cnts.scatter_(1, topk_ids, 1)
645
+ tokens_per_expert = cnts.sum(dim=0)
646
+ idxs = topk_ids.view(-1).argsort()
647
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
648
+ sorted_tokens_shape = sorted_tokens.shape
649
+ if self.ep_size > 1:
650
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
651
+ tokens_per_expert_group = tokens_per_expert.new_empty(
652
+ tokens_per_expert.shape[0]
653
+ )
654
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
655
+ output_splits = (
656
+ tokens_per_expert_group.view(self.ep_size, -1)
657
+ .sum(1)
658
+ .cpu()
659
+ .numpy()
660
+ .tolist()
661
+ )
662
+ gathered_tokens = sorted_tokens.new_empty(
663
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
664
+ )
665
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
666
+ dist.all_to_all(
667
+ list(gathered_tokens.split(output_splits)),
668
+ list(sorted_tokens.split(input_split_sizes)),
669
+ )
670
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
671
+ self.ep_size, self.experts_per_rank
672
+ ).sum(dim=0)
673
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
674
+ s = 0
675
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
676
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
677
+ s += k
678
+ gatherd_idxs = gatherd_idxs.argsort()
679
+ sorted_tokens = gathered_tokens[gatherd_idxs]
680
+ tokens_per_expert = tokens_per_expert_post_gather
681
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
682
+
683
+ outputs = []
684
+ start_idx = 0
685
+ for i, num_tokens in enumerate(tokens_per_expert):
686
+ end_idx = start_idx + num_tokens
687
+ if num_tokens == 0:
688
+ continue
689
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
690
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
691
+ expert_out = expert(tokens_for_this_expert)
692
+ outputs.append(expert_out)
693
+ start_idx = end_idx
694
+
695
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
696
+ if self.ep_size > 1:
697
+ new_x = torch.empty_like(outs)
698
+ new_x[gatherd_idxs] = outs
699
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
700
+ dist.all_to_all(
701
+ list(gathered_tokens.split(input_split_sizes)),
702
+ list(new_x.split(output_splits)),
703
+ )
704
+ outs = gathered_tokens
705
+
706
+ new_x = torch.empty_like(outs)
707
+ new_x[idxs] = outs
708
+ final_out = (
709
+ new_x.view(*topk_ids.shape, -1)
710
+ .type(topk_weight.dtype)
711
+ .mul_(topk_weight.unsqueeze(dim=-1))
712
+ .sum(dim=1)
713
+ .type(new_x.dtype)
714
+ )
715
+ return final_out
716
+
717
+
718
+ def moe_train(self, x, topk_ids, topk_weight):
719
+ token_size, hidden_dim = x.shape # token_size = bsz_size * seq_len
720
+ final_hidden_states = torch.zeros(
721
+ (token_size, hidden_dim), dtype=x.dtype, device=x.device
722
+ )
723
+
724
+ # One hot encode the selected experts to create an expert mask
725
+ # this will be used to easily index which expert is going to be sollicitated
726
+ expert_mask = torch.nn.functional.one_hot(topk_ids, num_classes=self.config.n_routed_experts).permute(2, 1, 0)
727
+
728
+ # Loop over all available experts in the model and perform the computation on each expert
729
+ for expert_idx in range(self.config.n_routed_experts):
730
+ expert_layer = self.experts[expert_idx]
731
+ idx, top_x = torch.where(expert_mask[expert_idx])
732
+
733
+ # Index the correct hidden states and compute the expert hidden state for
734
+ # the current expert. We need to make sure to multiply the output hidden
735
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
736
+ current_state = x[None, top_x].reshape(-1, hidden_dim)
737
+ current_hidden_states = expert_layer(current_state) * topk_weight[top_x, idx, None]
738
+
739
+ # However `index_add_` only support torch tensors for indexing so we'll use
740
+ # the `top_x` tensor here.
741
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(x.dtype))
742
+
743
+ return final_hidden_states.view(-1, hidden_dim)
744
+
745
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
746
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
747
+ """
748
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
749
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
750
+ """
751
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
752
+ if n_rep == 1:
753
+ return hidden_states
754
+ hidden_states = hidden_states[:, :, None, :, :].expand(
755
+ batch, num_key_value_heads, n_rep, slen, head_dim
756
+ )
757
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
758
+
759
+
760
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
761
+ class DeepseekV3Attention(nn.Module):
762
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
763
+
764
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: Optional[int] = None):
765
+ super().__init__()
766
+ self.config = config
767
+ self.layer_idx = layer_idx
768
+ if layer_idx is None:
769
+ logger.warning_once(
770
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
771
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
772
+ "when creating this class."
773
+ )
774
+
775
+ self.attention_dropout = config.attention_dropout
776
+ self.hidden_size = config.hidden_size
777
+ self.num_heads = config.num_attention_heads
778
+
779
+ self.max_position_embeddings = config.max_position_embeddings
780
+ self.rope_theta = config.rope_theta
781
+ self.q_lora_rank = config.q_lora_rank
782
+ self.qk_rope_head_dim = config.qk_rope_head_dim
783
+ self.kv_lora_rank = config.kv_lora_rank
784
+ self.v_head_dim = config.v_head_dim
785
+ self.qk_nope_head_dim = config.qk_nope_head_dim
786
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
787
+
788
+ self.is_causal = True
789
+
790
+ if self.q_lora_rank is None:
791
+ self.q_proj = nn.Linear(
792
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
793
+ )
794
+ else:
795
+ self.q_a_proj = nn.Linear(
796
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
797
+ )
798
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
799
+ self.q_b_proj = nn.Linear(
800
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
801
+ )
802
+
803
+ self.kv_a_proj_with_mqa = nn.Linear(
804
+ self.hidden_size,
805
+ config.kv_lora_rank + config.qk_rope_head_dim,
806
+ bias=config.attention_bias,
807
+ )
808
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
809
+ self.kv_b_proj = nn.Linear(
810
+ config.kv_lora_rank,
811
+ self.num_heads
812
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
813
+ bias=False,
814
+ )
815
+
816
+ self.o_proj = nn.Linear(
817
+ self.num_heads * self.v_head_dim,
818
+ self.hidden_size,
819
+ bias=config.attention_bias,
820
+ )
821
+ self._init_rope()
822
+
823
+ self.softmax_scale = self.q_head_dim ** (-0.5)
824
+ if self.config.rope_scaling is not None:
825
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
826
+ scaling_factor = self.config.rope_scaling["factor"]
827
+ if mscale_all_dim:
828
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
829
+ self.softmax_scale = self.softmax_scale * mscale * mscale
830
+
831
+ def _init_rope(self):
832
+ if self.config.rope_scaling is None:
833
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
834
+ self.qk_rope_head_dim,
835
+ max_position_embeddings=self.max_position_embeddings,
836
+ base=self.rope_theta,
837
+ )
838
+ else:
839
+ scaling_type = self.config.rope_scaling["type"]
840
+ scaling_factor = self.config.rope_scaling["factor"]
841
+ if scaling_type == "linear":
842
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
843
+ self.qk_rope_head_dim,
844
+ max_position_embeddings=self.max_position_embeddings,
845
+ scaling_factor=scaling_factor,
846
+ base=self.rope_theta,
847
+ )
848
+ elif scaling_type == "dynamic":
849
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
850
+ self.qk_rope_head_dim,
851
+ max_position_embeddings=self.max_position_embeddings,
852
+ scaling_factor=scaling_factor,
853
+ base=self.rope_theta,
854
+ )
855
+ elif scaling_type == "yarn":
856
+ kwargs = {
857
+ key: self.config.rope_scaling[key]
858
+ for key in [
859
+ "original_max_position_embeddings",
860
+ "beta_fast",
861
+ "beta_slow",
862
+ "mscale",
863
+ "mscale_all_dim",
864
+ ]
865
+ if key in self.config.rope_scaling
866
+ }
867
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
868
+ self.qk_rope_head_dim,
869
+ max_position_embeddings=self.max_position_embeddings,
870
+ scaling_factor=scaling_factor,
871
+ base=self.rope_theta,
872
+ **kwargs,
873
+ )
874
+ else:
875
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
876
+
877
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
878
+ return (
879
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
880
+ .transpose(1, 2)
881
+ .contiguous()
882
+ )
883
+
884
+ def forward(
885
+ self,
886
+ hidden_states: torch.Tensor,
887
+ attention_mask: Optional[torch.Tensor] = None,
888
+ position_ids: Optional[torch.LongTensor] = None,
889
+ past_key_value: Optional[Cache] = None,
890
+ output_attentions: bool = False,
891
+ use_cache: bool = False,
892
+ **kwargs,
893
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
894
+ if "padding_mask" in kwargs:
895
+ warnings.warn(
896
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
897
+ )
898
+ bsz, q_len, _ = hidden_states.size()
899
+
900
+ if self.q_lora_rank is None:
901
+ q = self.q_proj(hidden_states)
902
+ else:
903
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
904
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
905
+ q_nope, q_pe = torch.split(
906
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
907
+ )
908
+
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
+ if past_key_value is not None:
925
+ if self.layer_idx is None:
926
+ raise ValueError(
927
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
928
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
929
+ "with a layer index."
930
+ )
931
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
932
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
933
+
934
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
935
+
936
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
937
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
938
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
939
+
940
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
941
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
942
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
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
+ attn_weights = (
950
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
951
+ )
952
+
953
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
954
+ raise ValueError(
955
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
956
+ f" {attn_weights.size()}"
957
+ )
958
+ assert attention_mask is not None
959
+ if attention_mask is not None:
960
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
961
+ raise ValueError(
962
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
963
+ )
964
+ attn_weights = attn_weights + attention_mask
965
+
966
+ # upcast attention to fp32
967
+ attn_weights = nn.functional.softmax(
968
+ attn_weights, dim=-1, dtype=torch.float32
969
+ ).to(query_states.dtype)
970
+ attn_weights = nn.functional.dropout(
971
+ attn_weights, p=self.attention_dropout, training=self.training
972
+ )
973
+ attn_output = torch.matmul(attn_weights, value_states)
974
+
975
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
976
+ raise ValueError(
977
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
978
+ f" {attn_output.size()}"
979
+ )
980
+
981
+ attn_output = attn_output.transpose(1, 2).contiguous()
982
+
983
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
984
+
985
+ attn_output = self.o_proj(attn_output)
986
+
987
+ if not output_attentions:
988
+ attn_weights = None
989
+
990
+ return attn_output, attn_weights, past_key_value
991
+
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
994
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
995
+ """
996
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
997
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
998
+ flash attention and deal with padding tokens in case the input contains any of them.
999
+ """
1000
+
1001
+ def __init__(self, *args, **kwargs):
1002
+ super().__init__(*args, **kwargs)
1003
+
1004
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1005
+ # 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.
1006
+ # 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).
1007
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1008
+
1009
+ def forward(
1010
+ self,
1011
+ hidden_states: torch.Tensor,
1012
+ attention_mask: Optional[torch.LongTensor] = None,
1013
+ position_ids: Optional[torch.LongTensor] = None,
1014
+ past_key_value: Optional[Cache] = None,
1015
+ output_attentions: bool = False,
1016
+ use_cache: bool = False,
1017
+ **kwargs,
1018
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1019
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1020
+ if "padding_mask" in kwargs:
1021
+ warnings.warn(
1022
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1023
+ )
1024
+
1025
+ # overwrite attention_mask with padding_mask
1026
+ attention_mask = kwargs.pop("padding_mask")
1027
+
1028
+ output_attentions = False
1029
+
1030
+ bsz, q_len, _ = hidden_states.size()
1031
+
1032
+ if self.q_lora_rank is None:
1033
+ q = self.q_proj(hidden_states)
1034
+ else:
1035
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1036
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1037
+ q_nope, q_pe = torch.split(
1038
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1039
+ )
1040
+
1041
+ # Flash attention requires the input to have the shape
1042
+ # batch_size x seq_length x head_dim x hidden_dim
1043
+ # therefore we just need to keep the original shape
1044
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1045
+ compressed_kv, k_pe = torch.split(
1046
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1047
+ )
1048
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1049
+ kv = (
1050
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1051
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1052
+ .transpose(1, 2)
1053
+ )
1054
+
1055
+ k_nope, value_states = torch.split(
1056
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1057
+ )
1058
+ kv_seq_len = value_states.shape[-2]
1059
+
1060
+ kv_seq_len = value_states.shape[-2]
1061
+ if past_key_value is not None:
1062
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1063
+
1064
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1065
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1066
+
1067
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1068
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1069
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1070
+
1071
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1072
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1073
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1074
+
1075
+ if self.q_head_dim != self.v_head_dim:
1076
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1077
+
1078
+ if past_key_value is not None:
1079
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1080
+ key_states, value_states = past_key_value.update(
1081
+ key_states, value_states, self.layer_idx, cache_kwargs
1082
+ )
1083
+
1084
+ # 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
1085
+ # to be able to avoid many of these transpose/reshape/view.
1086
+ query_states = query_states.transpose(1, 2)
1087
+ key_states = key_states.transpose(1, 2)
1088
+ value_states = value_states.transpose(1, 2)
1089
+
1090
+ dropout_rate = self.attention_dropout if self.training else 0.0
1091
+
1092
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1093
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1094
+ # cast them back in the correct dtype just to be sure everything works as expected.
1095
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1096
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1097
+
1098
+ input_dtype = query_states.dtype
1099
+ if input_dtype == torch.float32:
1100
+ # Handle the case where the model is quantized
1101
+ if hasattr(self.config, "_pre_quantization_dtype"):
1102
+ target_dtype = self.config._pre_quantization_dtype
1103
+ elif torch.is_autocast_enabled():
1104
+ target_dtype = torch.get_autocast_gpu_dtype()
1105
+ else:
1106
+ target_dtype = (
1107
+ self.q_proj.weight.dtype
1108
+ if self.q_lora_rank is None
1109
+ else self.q_a_proj.weight.dtype
1110
+ )
1111
+
1112
+ logger.warning_once(
1113
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1114
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1115
+ f" {target_dtype}."
1116
+ )
1117
+
1118
+ query_states = query_states.to(target_dtype)
1119
+ key_states = key_states.to(target_dtype)
1120
+ value_states = value_states.to(target_dtype)
1121
+
1122
+ attn_output = self._flash_attention_forward(
1123
+ query_states,
1124
+ key_states,
1125
+ value_states,
1126
+ attention_mask,
1127
+ q_len,
1128
+ dropout=dropout_rate,
1129
+ softmax_scale=self.softmax_scale,
1130
+ )
1131
+ if self.q_head_dim != self.v_head_dim:
1132
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1133
+
1134
+ attn_output = attn_output.reshape(
1135
+ bsz, q_len, self.num_heads * self.v_head_dim
1136
+ ).contiguous()
1137
+ attn_output = self.o_proj(attn_output)
1138
+
1139
+ if not output_attentions:
1140
+ attn_weights = None
1141
+
1142
+ return attn_output, attn_weights, past_key_value
1143
+
1144
+ def _flash_attention_forward(
1145
+ self,
1146
+ query_states,
1147
+ key_states,
1148
+ value_states,
1149
+ attention_mask,
1150
+ query_length,
1151
+ dropout=0.0,
1152
+ softmax_scale=None,
1153
+ ):
1154
+ """
1155
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1156
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1157
+
1158
+ Args:
1159
+ query_states (`torch.Tensor`):
1160
+ Input query states to be passed to Flash Attention API
1161
+ key_states (`torch.Tensor`):
1162
+ Input key states to be passed to Flash Attention API
1163
+ value_states (`torch.Tensor`):
1164
+ Input value states to be passed to Flash Attention API
1165
+ attention_mask (`torch.Tensor`):
1166
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1167
+ position of padding tokens and 1 for the position of non-padding tokens.
1168
+ dropout (`int`, *optional*):
1169
+ Attention dropout
1170
+ softmax_scale (`float`, *optional*):
1171
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1172
+ """
1173
+ if not self._flash_attn_uses_top_left_mask:
1174
+ causal = self.is_causal
1175
+ else:
1176
+ # 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__.
1177
+ causal = self.is_causal and query_length != 1
1178
+
1179
+ # Contains at least one padding token in the sequence
1180
+ if attention_mask is not None:
1181
+ batch_size = query_states.shape[0]
1182
+ (
1183
+ query_states,
1184
+ key_states,
1185
+ value_states,
1186
+ indices_q,
1187
+ cu_seq_lens,
1188
+ max_seq_lens,
1189
+ ) = self._upad_input(
1190
+ query_states, key_states, value_states, attention_mask, query_length
1191
+ )
1192
+
1193
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1194
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1195
+
1196
+ attn_output_unpad = flash_attn_varlen_func(
1197
+ query_states,
1198
+ key_states,
1199
+ value_states,
1200
+ cu_seqlens_q=cu_seqlens_q,
1201
+ cu_seqlens_k=cu_seqlens_k,
1202
+ max_seqlen_q=max_seqlen_in_batch_q,
1203
+ max_seqlen_k=max_seqlen_in_batch_k,
1204
+ dropout_p=dropout,
1205
+ softmax_scale=softmax_scale,
1206
+ causal=causal,
1207
+ )
1208
+
1209
+ attn_output = pad_input(
1210
+ attn_output_unpad, indices_q, batch_size, query_length
1211
+ )
1212
+ else:
1213
+ attn_output = flash_attn_func(
1214
+ query_states,
1215
+ key_states,
1216
+ value_states,
1217
+ dropout,
1218
+ softmax_scale=softmax_scale,
1219
+ causal=causal,
1220
+ )
1221
+
1222
+ return attn_output
1223
+
1224
+ def _upad_input(
1225
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1226
+ ):
1227
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1228
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1229
+
1230
+ key_layer = index_first_axis(
1231
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1232
+ indices_k,
1233
+ )
1234
+ value_layer = index_first_axis(
1235
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1236
+ indices_k,
1237
+ )
1238
+ if query_length == kv_seq_len:
1239
+ query_layer = index_first_axis(
1240
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1241
+ indices_k,
1242
+ )
1243
+ cu_seqlens_q = cu_seqlens_k
1244
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1245
+ indices_q = indices_k
1246
+ elif query_length == 1:
1247
+ max_seqlen_in_batch_q = 1
1248
+ cu_seqlens_q = torch.arange(
1249
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1250
+ ) # There is a memcpy here, that is very bad.
1251
+ indices_q = cu_seqlens_q[:-1]
1252
+ query_layer = query_layer.squeeze(1)
1253
+ else:
1254
+ # The -q_len: slice assumes left padding.
1255
+ attention_mask = attention_mask[:, -query_length:]
1256
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1257
+ query_layer, attention_mask
1258
+ )
1259
+
1260
+ return (
1261
+ query_layer,
1262
+ key_layer,
1263
+ value_layer,
1264
+ indices_q,
1265
+ (cu_seqlens_q, cu_seqlens_k),
1266
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1267
+ )
1268
+
1269
+
1270
+ ATTENTION_CLASSES = {
1271
+ "eager": DeepseekV3Attention,
1272
+ "flash_attention_2": DeepseekV3FlashAttention2,
1273
+ }
1274
+
1275
+
1276
+ class DeepseekV3DecoderLayer(nn.Module):
1277
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: int):
1278
+ super().__init__()
1279
+ self.hidden_size = config.hidden_size
1280
+
1281
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1282
+ config=config, layer_idx=layer_idx
1283
+ )
1284
+
1285
+ self.mlp = (
1286
+ TinyDeepseekV3MoE(config)
1287
+ if (
1288
+ config.n_routed_experts is not None
1289
+ and layer_idx >= config.first_k_dense_replace
1290
+ and layer_idx % config.moe_layer_freq == 0
1291
+ )
1292
+ else DeepseekV3MLP(config)
1293
+ )
1294
+ self.input_layernorm = DeepseekV3RMSNorm(
1295
+ config.hidden_size, eps=config.rms_norm_eps
1296
+ )
1297
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1298
+ config.hidden_size, eps=config.rms_norm_eps
1299
+ )
1300
+
1301
+ def forward(
1302
+ self,
1303
+ hidden_states: torch.Tensor,
1304
+ attention_mask: Optional[torch.Tensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1307
+ output_attentions: Optional[bool] = False,
1308
+ output_router_logits: Optional[bool] = False,
1309
+ use_cache: Optional[bool] = False,
1310
+ **kwargs,
1311
+ ) -> Tuple[
1312
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1313
+ ]:
1314
+ """
1315
+ Args:
1316
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1317
+ attention_mask (`torch.FloatTensor`, *optional*):
1318
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1319
+ query_sequence_length, key_sequence_length)` if default attention is used.
1320
+ output_attentions (`bool`, *optional*):
1321
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1322
+ returned tensors for more detail.
1323
+ use_cache (`bool`, *optional*):
1324
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1325
+ (see `past_key_values`).
1326
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1327
+ """
1328
+ if "padding_mask" in kwargs:
1329
+ warnings.warn(
1330
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1331
+ )
1332
+ residual = hidden_states
1333
+
1334
+ hidden_states = self.input_layernorm(hidden_states)
1335
+
1336
+ # Self Attention
1337
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1338
+ hidden_states=hidden_states,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_value=past_key_value,
1342
+ output_attentions=output_attentions,
1343
+ use_cache=use_cache,
1344
+ **kwargs,
1345
+ )
1346
+ hidden_states = residual + hidden_states
1347
+
1348
+ # Fully Connected
1349
+ residual = hidden_states
1350
+ hidden_states = self.post_attention_layernorm(hidden_states)
1351
+ hidden_states = self.mlp(hidden_states)
1352
+ if isinstance(hidden_states, tuple):
1353
+ hidden_states, router_scores = hidden_states
1354
+ else:
1355
+ router_scores = None
1356
+ hidden_states = residual + hidden_states
1357
+
1358
+ outputs = (hidden_states,)
1359
+
1360
+ if output_attentions:
1361
+ outputs += (self_attn_weights,)
1362
+
1363
+ if use_cache:
1364
+ outputs += (present_key_value,)
1365
+
1366
+ if output_router_logits:
1367
+ outputs += (router_scores, )
1368
+
1369
+ return outputs
1370
+
1371
+
1372
+ DeepseekV3_START_DOCSTRING = r"""
1373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1375
+ etc.)
1376
+
1377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1379
+ and behavior.
1380
+
1381
+ Parameters:
1382
+ config ([`TinyDeepseekV3Config`]):
1383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1384
+ load the weights associated with the model, only the configuration. Check out the
1385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1386
+ """
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1391
+ DeepseekV3_START_DOCSTRING,
1392
+ )
1393
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1394
+ config_class = TinyDeepseekV3Config
1395
+ base_model_prefix = "model"
1396
+ supports_gradient_checkpointing = True
1397
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1398
+ _skip_keys_device_placement = "past_key_values"
1399
+ _supports_flash_attn_2 = True
1400
+ _supports_cache_class = True
1401
+
1402
+ def _init_weights(self, module):
1403
+ std = self.config.initializer_range
1404
+ if isinstance(module, nn.Linear):
1405
+ module.weight.data.normal_(mean=0.0, std=std)
1406
+ if module.bias is not None:
1407
+ module.bias.data.zero_()
1408
+ elif isinstance(module, nn.Embedding):
1409
+ module.weight.data.normal_(mean=0.0, std=std)
1410
+ if module.padding_idx is not None:
1411
+ module.weight.data[module.padding_idx].zero_()
1412
+
1413
+
1414
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1415
+ Args:
1416
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1417
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1418
+ it.
1419
+
1420
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1421
+ [`PreTrainedTokenizer.__call__`] for details.
1422
+
1423
+ [What are input IDs?](../glossary#input-ids)
1424
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1425
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1426
+
1427
+ - 1 for tokens that are **not masked**,
1428
+ - 0 for tokens that are **masked**.
1429
+
1430
+ [What are attention masks?](../glossary#attention-mask)
1431
+
1432
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1433
+ [`PreTrainedTokenizer.__call__`] for details.
1434
+
1435
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1436
+ `past_key_values`).
1437
+
1438
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1439
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1440
+ information on the default strategy.
1441
+
1442
+ - 1 indicates the head is **not masked**,
1443
+ - 0 indicates the head is **masked**.
1444
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1446
+ config.n_positions - 1]`.
1447
+
1448
+ [What are position IDs?](../glossary#position-ids)
1449
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1450
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1451
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1452
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1453
+
1454
+ Two formats are allowed:
1455
+ - a [`~cache_utils.Cache`] instance;
1456
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1457
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1458
+ cache format.
1459
+
1460
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1461
+ legacy cache format will be returned.
1462
+
1463
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1464
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1465
+ of shape `(batch_size, sequence_length)`.
1466
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1467
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1468
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1469
+ model's internal embedding lookup matrix.
1470
+ use_cache (`bool`, *optional*):
1471
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1472
+ `past_key_values`).
1473
+ output_attentions (`bool`, *optional*):
1474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1475
+ tensors for more detail.
1476
+ output_hidden_states (`bool`, *optional*):
1477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1478
+ more detail.
1479
+ return_dict (`bool`, *optional*):
1480
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1481
+ """
1482
+
1483
+
1484
+ @add_start_docstrings(
1485
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1486
+ DeepseekV3_START_DOCSTRING,
1487
+ )
1488
+ class TinyDeepseekV3Model(DeepseekV3PreTrainedModel):
1489
+ """
1490
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1491
+
1492
+ Args:
1493
+ config: TinyDeepseekV3Config
1494
+ """
1495
+
1496
+ def __init__(self, config: TinyDeepseekV3Config):
1497
+ super().__init__(config)
1498
+ self.padding_idx = config.pad_token_id
1499
+ self.vocab_size = config.vocab_size
1500
+
1501
+ self.n_future_tokens = config.n_future_tokens
1502
+ assert self.n_future_tokens > 0, "At least one future token prediction needed, i.e., n_future_tokens>0"
1503
+ assert config.num_hidden_layers > self.n_future_tokens, "The number of layer should larger than the n_future_tokens, i.e., config.num_hidden_layers > config.n_future_tokens"
1504
+
1505
+ self.embed_tokens = nn.Embedding(
1506
+ config.vocab_size, config.hidden_size, self.padding_idx
1507
+ )
1508
+ self.layers = nn.ModuleList(
1509
+ [
1510
+ DeepseekV3DecoderLayer(config, layer_idx)
1511
+ for layer_idx in range(config.num_hidden_layers - self.n_future_tokens + 1)
1512
+ ]
1513
+ )
1514
+
1515
+ # Additional prediction heads for multi-token prediction.
1516
+ # `layer_id` counts contiguously from the first Transformer block.
1517
+ self.extra_heads = nn.ModuleList(
1518
+ [
1519
+ DeepseekV3DecoderLayer(config, len(self.layers) + layer_idx)
1520
+ for layer_idx in range(self.n_future_tokens - 1)
1521
+ ]
1522
+ )
1523
+ self.extra_heads_input_norms = nn.ModuleList(
1524
+ [
1525
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1526
+ for _ in range(self.n_future_tokens - 1)
1527
+ ]
1528
+ )
1529
+ self.extra_heads_hidden_norms = nn.ModuleList(
1530
+ [
1531
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1532
+ for _ in range(self.n_future_tokens - 1)
1533
+ ]
1534
+ )
1535
+ self.extra_heads_projections = nn.ModuleList(
1536
+ [
1537
+ nn.Linear(config.hidden_size*2, config.hidden_size, bias=False)
1538
+ for _ in range(self.n_future_tokens - 1)
1539
+ ]
1540
+ )
1541
+
1542
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1543
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1544
+
1545
+ self.gradient_checkpointing = False
1546
+ # Initialize weights and apply final processing
1547
+ self.post_init()
1548
+
1549
+ def get_input_embeddings(self):
1550
+ return self.embed_tokens
1551
+
1552
+ def set_input_embeddings(self, value):
1553
+ self.embed_tokens = value
1554
+
1555
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1556
+ def forward(
1557
+ self,
1558
+ input_ids: torch.LongTensor = None,
1559
+ attention_mask: Optional[torch.Tensor] = None,
1560
+ position_ids: Optional[torch.LongTensor] = None,
1561
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1562
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1563
+ use_cache: Optional[bool] = None,
1564
+ output_attentions: Optional[bool] = None,
1565
+ output_hidden_states: Optional[bool] = None,
1566
+ output_router_logits: Optional[bool] = None,
1567
+ return_dict: Optional[bool] = None,
1568
+ return_all_heads: Optional[bool] = False,
1569
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1570
+ output_attentions = (
1571
+ output_attentions
1572
+ if output_attentions is not None
1573
+ else self.config.output_attentions
1574
+ )
1575
+ output_router_logits = (
1576
+ output_router_logits
1577
+ if output_router_logits is not None
1578
+ else self.config.output_router_logits
1579
+ )
1580
+ output_hidden_states = (
1581
+ output_hidden_states
1582
+ if output_hidden_states is not None
1583
+ else self.config.output_hidden_states
1584
+ )
1585
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1586
+
1587
+ return_dict = (
1588
+ return_dict if return_dict is not None else self.config.use_return_dict
1589
+ )
1590
+
1591
+ # retrieve input_ids and inputs_embeds
1592
+ if input_ids is not None and inputs_embeds is not None:
1593
+ raise ValueError(
1594
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1595
+ )
1596
+ elif input_ids is not None:
1597
+ batch_size, seq_length = input_ids.shape[:2]
1598
+ elif inputs_embeds is not None:
1599
+ batch_size, seq_length = inputs_embeds.shape[:2]
1600
+ else:
1601
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1602
+
1603
+ past_key_values_length = 0
1604
+ if use_cache:
1605
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1606
+ if use_legacy_cache:
1607
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1608
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1609
+
1610
+ if position_ids is None:
1611
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1612
+ position_ids = torch.arange(
1613
+ past_key_values_length,
1614
+ seq_length + past_key_values_length,
1615
+ dtype=torch.long,
1616
+ device=device,
1617
+ )
1618
+ position_ids = position_ids.unsqueeze(0)
1619
+
1620
+ if inputs_embeds is None:
1621
+ inputs_embeds = self.embed_tokens(input_ids)
1622
+
1623
+ if self._use_flash_attention_2:
1624
+ # 2d mask is passed through the layers
1625
+ attention_mask = (
1626
+ attention_mask
1627
+ if (attention_mask is not None and 0 in attention_mask)
1628
+ else None
1629
+ )
1630
+ else:
1631
+ # 4d mask is passed through the layers
1632
+ attention_mask = _prepare_4d_causal_attention_mask(
1633
+ attention_mask,
1634
+ (batch_size, seq_length),
1635
+ inputs_embeds,
1636
+ past_key_values_length,
1637
+ )
1638
+
1639
+ # embed positions
1640
+ hidden_states = inputs_embeds
1641
+
1642
+ # decoder layers
1643
+ all_hidden_states = () if output_hidden_states or return_all_heads else None
1644
+ all_self_attns = () if output_attentions else None
1645
+ all_router_logits = () if output_router_logits else None
1646
+ next_decoder_cache = None
1647
+
1648
+ # layers = self.layers if not return_all_heads else self.layers + self.extra_heads
1649
+ for decoder_layer in self.layers:
1650
+ if output_hidden_states:
1651
+ all_hidden_states += (hidden_states,)
1652
+
1653
+ layer_outputs = decoder_layer(
1654
+ hidden_states,
1655
+ attention_mask=attention_mask,
1656
+ position_ids=position_ids,
1657
+ past_key_value=past_key_values,
1658
+ output_attentions=output_attentions,
1659
+ output_router_logits=output_router_logits,
1660
+ use_cache=use_cache,
1661
+ )
1662
+
1663
+ hidden_states = layer_outputs[0]
1664
+
1665
+ if use_cache:
1666
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1667
+
1668
+ if output_attentions:
1669
+ all_self_attns += (layer_outputs[1],)
1670
+
1671
+ if output_router_logits and layer_outputs[-1] is not None:
1672
+ all_router_logits += (layer_outputs[-1],)
1673
+
1674
+ # Multi-token prediction
1675
+ if return_all_heads:
1676
+ first_token_hidden_state = self.norm(hidden_states) # first next token prediction
1677
+
1678
+ all_hidden_states += (first_token_hidden_state,)
1679
+
1680
+ for extra_head_idx in range(len(self.extra_heads)):
1681
+ hidden_states = torch.cat(
1682
+ (self.extra_heads_input_norms[extra_head_idx](inputs_embeds),
1683
+ self.extra_heads_hidden_norms[extra_head_idx](hidden_states)),
1684
+ dim=-1
1685
+ ) # (bsz, seq_len, dim*2)
1686
+
1687
+ hidden_states = self.extra_heads_projections[extra_head_idx](hidden_states)
1688
+ # (bsz, seq_len, dim)
1689
+
1690
+ layer_outputs = self.extra_heads[extra_head_idx](
1691
+ hidden_states,
1692
+ attention_mask=attention_mask,
1693
+ position_ids=position_ids,
1694
+ past_key_value=past_key_values,
1695
+ output_attentions=output_attentions,
1696
+ use_cache=use_cache,
1697
+ )
1698
+
1699
+ hidden_states = layer_outputs[0]
1700
+
1701
+ if use_cache:
1702
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1703
+
1704
+ if output_attentions:
1705
+ all_self_attns += (layer_outputs[1],)
1706
+
1707
+ # always return extra_head hidden_states with norm
1708
+ all_hidden_states += (self.norm(hidden_states),)
1709
+
1710
+ hidden_states = first_token_hidden_state
1711
+
1712
+ else:
1713
+ hidden_states = self.norm(hidden_states)
1714
+
1715
+ # add hidden states from the last decoder layer
1716
+ if output_hidden_states:
1717
+ all_hidden_states += (hidden_states,)
1718
+
1719
+ next_cache = None
1720
+ if use_cache:
1721
+ next_cache = (
1722
+ next_decoder_cache.to_legacy_cache()
1723
+ if use_legacy_cache
1724
+ else next_decoder_cache
1725
+ )
1726
+ if not return_dict:
1727
+ return tuple(
1728
+ v
1729
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1730
+ if v is not None
1731
+ )
1732
+ return MoeModelOutputWithPast(
1733
+ last_hidden_state=hidden_states,
1734
+ past_key_values=next_cache,
1735
+ hidden_states=all_hidden_states,
1736
+ attentions=all_self_attns,
1737
+ router_logits=all_router_logits
1738
+ )
1739
+
1740
+
1741
+ class TinyDeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1742
+ _tied_weights_keys = ["lm_head.weight"]
1743
+
1744
+ def __init__(self, config):
1745
+ super().__init__(config)
1746
+ self.model = TinyDeepseekV3Model(config)
1747
+ self.vocab_size = config.vocab_size
1748
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1749
+ self.n_future_tokens = config.n_future_tokens
1750
+ self.mtp_loss_lambda = config.mtp_loss_lambda
1751
+
1752
+ self.seq_aux = config.seq_aux
1753
+ self.aux_loss_alpha = config.aux_loss_alpha
1754
+ self.n_routed_experts = config.n_routed_experts
1755
+ self.num_experts_per_tok = config.num_experts_per_tok
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ output_router_logits: Optional[bool] = None,
1794
+ return_dict: Optional[bool] = None,
1795
+ return_all_heads: Optional[bool] = False,
1796
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1797
+ r"""
1798
+ Args:
1799
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1800
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1801
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1802
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1803
+
1804
+ Returns:
1805
+
1806
+ Example:
1807
+
1808
+ ```python
1809
+ >>> from transformers import AutoTokenizer, TinyDeepseekV3ForCausalLM
1810
+
1811
+ >>> model = TinyDeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1812
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1813
+
1814
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1815
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1816
+
1817
+ >>> # Generate
1818
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1819
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1820
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1821
+ ```"""
1822
+ output_attentions = (
1823
+ output_attentions
1824
+ if output_attentions is not None
1825
+ else self.config.output_attentions
1826
+ )
1827
+ output_router_logits = (
1828
+ output_router_logits
1829
+ if output_router_logits is not None
1830
+ else self.config.output_router_logits
1831
+ )
1832
+ output_hidden_states = (
1833
+ output_hidden_states
1834
+ if output_hidden_states is not None
1835
+ else self.config.output_hidden_states
1836
+ )
1837
+ return_dict = (
1838
+ return_dict if return_dict is not None else self.config.use_return_dict
1839
+ )
1840
+
1841
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1842
+ outputs = self.model(
1843
+ input_ids=input_ids,
1844
+ attention_mask=attention_mask,
1845
+ position_ids=position_ids,
1846
+ past_key_values=past_key_values,
1847
+ inputs_embeds=inputs_embeds,
1848
+ use_cache=use_cache,
1849
+ output_attentions=output_attentions,
1850
+ output_hidden_states=output_hidden_states,
1851
+ output_router_logits=output_router_logits or self.seq_aux,
1852
+ return_dict=return_dict,
1853
+ return_all_heads=return_all_heads,
1854
+ )
1855
+
1856
+ if not return_all_heads:
1857
+ hidden_states = outputs[0]
1858
+ logits = self.lm_head(hidden_states)
1859
+ logits = logits.float()
1860
+
1861
+ loss = None
1862
+ if labels is not None:
1863
+ # Shift so that tokens < n predict n
1864
+ shift_logits = logits[..., :-1, :].contiguous()
1865
+ shift_labels = labels[..., 1:].contiguous()
1866
+ # Flatten the tokens
1867
+ loss_fct = CrossEntropyLoss()
1868
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1869
+ shift_labels = shift_labels.view(-1)
1870
+ # Enable model parallelism
1871
+ shift_labels = shift_labels.to(shift_logits.device)
1872
+ loss = loss_fct(shift_logits, shift_labels)
1873
+ else:
1874
+ # Multi-token prediction
1875
+ mtp_hidden_states = outputs[2][-self.n_future_tokens:]
1876
+ first_token_loss = None
1877
+ mtp_loss = None
1878
+ loss = None
1879
+
1880
+ add_loss = lambda x, y: y if x is None else x+y
1881
+
1882
+ for token_idx in range(self.n_future_tokens):
1883
+ logits = self.lm_head(mtp_hidden_states[token_idx])
1884
+ logits = logits.float()
1885
+
1886
+ if labels is not None:
1887
+ n_shift = token_idx + 1
1888
+ if n_shift > (logits.shape[1]-1):
1889
+ continue
1890
+
1891
+ # Shift so that tokens < n predict n
1892
+ shift_logits = logits[..., :-n_shift, :].contiguous()
1893
+ shift_labels = labels[..., n_shift:].contiguous()
1894
+ # Flatten the tokens
1895
+ loss_fct = CrossEntropyLoss()
1896
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1897
+ shift_labels = shift_labels.view(-1)
1898
+ # Enable model parallelism
1899
+ shift_labels = shift_labels.to(shift_logits.device)
1900
+
1901
+ loss = add_loss(loss, loss_fct(shift_logits, shift_labels))
1902
+
1903
+ if token_idx == 0:
1904
+ first_token_loss = add_loss(first_token_loss, loss)
1905
+ else:
1906
+ mtp_loss = add_loss(mtp_loss, loss)
1907
+
1908
+ if labels is not None:
1909
+ loss = first_token_loss + self.mtp_loss_lambda * mtp_loss / (self.n_future_tokens - 1)
1910
+ # ljh Loss debug
1911
+ # print(f"loss: {loss} first_token_loss: {first_token_loss}, mtp_loss: {mtp_loss} with n_future_tokens {self.n_future_tokens} and mtp_loss_lambda {self.mtp_loss_lambda}")
1912
+
1913
+
1914
+ # balancing loss
1915
+ aux_loss = None
1916
+ if self.seq_aux:
1917
+ aux_loss = load_balancing_loss_func(
1918
+ gate_logits=outputs.router_logits if return_dict else outputs[-1],
1919
+ num_experts=self.n_routed_experts,
1920
+ top_k=self.num_experts_per_tok,
1921
+ attention_mask=attention_mask,
1922
+ )
1923
+ aux_loss = self.aux_loss_alpha * aux_loss
1924
+ # ljh Loss debug
1925
+ # print(f"loss: {loss}, aux_loss: {aux_loss}")
1926
+ if labels is not None:
1927
+ loss += aux_loss.to(loss.device) # make sure to reside in the same device
1928
+
1929
+ if not return_dict:
1930
+ output = (logits,) + outputs[1:]
1931
+ if output_router_logits:
1932
+ output = (aux_loss,) + output
1933
+ return (loss,) + output if loss is not None else output
1934
+
1935
+ return MoeCausalLMOutputWithPast(
1936
+ loss=loss,
1937
+ logits=logits,
1938
+ past_key_values=outputs.past_key_values,
1939
+ hidden_states=outputs.hidden_states,
1940
+ attentions=outputs.attentions,
1941
+ router_logits=outputs.router_logits
1942
+ )
1943
+
1944
+ def prepare_inputs_for_generation(
1945
+ self,
1946
+ input_ids,
1947
+ past_key_values=None,
1948
+ attention_mask=None,
1949
+ inputs_embeds=None,
1950
+ **kwargs,
1951
+ ):
1952
+ if past_key_values is not None:
1953
+ if isinstance(past_key_values, Cache):
1954
+ cache_length = past_key_values.get_seq_length()
1955
+ past_length = past_key_values.seen_tokens
1956
+ max_cache_length = past_key_values.get_max_length()
1957
+ else:
1958
+ cache_length = past_length = past_key_values[0][0].shape[2]
1959
+ max_cache_length = None
1960
+
1961
+ # Keep only the unprocessed tokens:
1962
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1963
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1964
+ # input)
1965
+ if (
1966
+ attention_mask is not None
1967
+ and attention_mask.shape[1] > input_ids.shape[1]
1968
+ ):
1969
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1970
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1971
+ # input_ids based on the past_length.
1972
+ elif past_length < input_ids.shape[1]:
1973
+ input_ids = input_ids[:, past_length:]
1974
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1975
+
1976
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1977
+ if (
1978
+ max_cache_length is not None
1979
+ and attention_mask is not None
1980
+ and cache_length + input_ids.shape[1] > max_cache_length
1981
+ ):
1982
+ attention_mask = attention_mask[:, -max_cache_length:]
1983
+
1984
+ position_ids = kwargs.get("position_ids", None)
1985
+ if attention_mask is not None and position_ids is None:
1986
+ # create position_ids on the fly for batch generation
1987
+ position_ids = attention_mask.long().cumsum(-1) - 1
1988
+ position_ids.masked_fill_(attention_mask == 0, 1)
1989
+ if past_key_values:
1990
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1991
+
1992
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1993
+ if inputs_embeds is not None and past_key_values is None:
1994
+ model_inputs = {"inputs_embeds": inputs_embeds}
1995
+ else:
1996
+ model_inputs = {"input_ids": input_ids}
1997
+
1998
+ model_inputs.update(
1999
+ {
2000
+ "position_ids": position_ids,
2001
+ "past_key_values": past_key_values,
2002
+ "use_cache": kwargs.get("use_cache"),
2003
+ "attention_mask": attention_mask,
2004
+ }
2005
+ )
2006
+ return model_inputs
2007
+
2008
+ @staticmethod
2009
+ def _reorder_cache(past_key_values, beam_idx):
2010
+ reordered_past = ()
2011
+ for layer_past in past_key_values:
2012
+ reordered_past += (
2013
+ tuple(
2014
+ past_state.index_select(0, beam_idx.to(past_state.device))
2015
+ for past_state in layer_past
2016
+ ),
2017
+ )
2018
+ return reordered_past
2019
+
2020
+
2021
+ @add_start_docstrings(
2022
+ """
2023
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
2024
+
2025
+ [`TinyDeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2026
+ (e.g. GPT-2) do.
2027
+
2028
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2029
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2030
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2031
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2032
+ each row of the batch).
2033
+ """,
2034
+ DeepseekV3_START_DOCSTRING,
2035
+ )
2036
+ class TinyDeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
2037
+ def __init__(self, config):
2038
+ super().__init__(config)
2039
+ self.num_labels = config.num_labels
2040
+ self.model = TinyDeepseekV3Model(config)
2041
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2042
+
2043
+ # Initialize weights and apply final processing
2044
+ self.post_init()
2045
+
2046
+ def get_input_embeddings(self):
2047
+ return self.model.embed_tokens
2048
+
2049
+ def set_input_embeddings(self, value):
2050
+ self.model.embed_tokens = value
2051
+
2052
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
2053
+ def forward(
2054
+ self,
2055
+ input_ids: torch.LongTensor = None,
2056
+ attention_mask: Optional[torch.Tensor] = None,
2057
+ position_ids: Optional[torch.LongTensor] = None,
2058
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2059
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2060
+ labels: Optional[torch.LongTensor] = None,
2061
+ use_cache: Optional[bool] = None,
2062
+ output_attentions: Optional[bool] = None,
2063
+ output_hidden_states: Optional[bool] = None,
2064
+ return_dict: Optional[bool] = None,
2065
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2066
+ r"""
2067
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2068
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2069
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2070
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2071
+ """
2072
+ return_dict = (
2073
+ return_dict if return_dict is not None else self.config.use_return_dict
2074
+ )
2075
+
2076
+ transformer_outputs = self.model(
2077
+ input_ids,
2078
+ attention_mask=attention_mask,
2079
+ position_ids=position_ids,
2080
+ past_key_values=past_key_values,
2081
+ inputs_embeds=inputs_embeds,
2082
+ use_cache=use_cache,
2083
+ output_attentions=output_attentions,
2084
+ output_hidden_states=output_hidden_states,
2085
+ return_dict=return_dict,
2086
+ )
2087
+ hidden_states = transformer_outputs[0]
2088
+ logits = self.score(hidden_states)
2089
+
2090
+ if input_ids is not None:
2091
+ batch_size = input_ids.shape[0]
2092
+ else:
2093
+ batch_size = inputs_embeds.shape[0]
2094
+
2095
+ if self.config.pad_token_id is None and batch_size != 1:
2096
+ raise ValueError(
2097
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2098
+ )
2099
+ if self.config.pad_token_id is None:
2100
+ sequence_lengths = -1
2101
+ else:
2102
+ if input_ids is not None:
2103
+ sequence_lengths = (
2104
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2105
+ ).to(logits.device)
2106
+ else:
2107
+ sequence_lengths = -1
2108
+
2109
+ pooled_logits = logits[
2110
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2111
+ ]
2112
+
2113
+ loss = None
2114
+ if labels is not None:
2115
+ labels = labels.to(logits.device)
2116
+ if self.config.problem_type is None:
2117
+ if self.num_labels == 1:
2118
+ self.config.problem_type = "regression"
2119
+ elif self.num_labels > 1 and (
2120
+ labels.dtype == torch.long or labels.dtype == torch.int
2121
+ ):
2122
+ self.config.problem_type = "single_label_classification"
2123
+ else:
2124
+ self.config.problem_type = "multi_label_classification"
2125
+
2126
+ if self.config.problem_type == "regression":
2127
+ loss_fct = MSELoss()
2128
+ if self.num_labels == 1:
2129
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2130
+ else:
2131
+ loss = loss_fct(pooled_logits, labels)
2132
+ elif self.config.problem_type == "single_label_classification":
2133
+ loss_fct = CrossEntropyLoss()
2134
+ loss = loss_fct(
2135
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2136
+ )
2137
+ elif self.config.problem_type == "multi_label_classification":
2138
+ loss_fct = BCEWithLogitsLoss()
2139
+ loss = loss_fct(pooled_logits, labels)
2140
+ if not return_dict:
2141
+ output = (pooled_logits,) + transformer_outputs[1:]
2142
+ return ((loss,) + output) if loss is not None else output
2143
+
2144
+ return SequenceClassifierOutputWithPast(
2145
+ loss=loss,
2146
+ logits=pooled_logits,
2147
+ past_key_values=transformer_outputs.past_key_values,
2148
+ hidden_states=transformer_outputs.hidden_states,
2149
+ attentions=transformer_outputs.attentions,
2150
+ )
checkpoint-11000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-11000/tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 131072,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{{'<|Assistant|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}"
35
+ }
checkpoint-12000/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyDeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tinydeepseek.TinyDeepseekV3Config",
9
+ "AutoModel": "modeling_tinydeepseek.TinyDeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_tinydeepseek.TinyDeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.0001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4864,
21
+ "kv_lora_rank": 128,
22
+ "lossfreebalance_update_rate": 0.001,
23
+ "max_position_embeddings": 163840,
24
+ "model_type": "tinydeepseek_v3",
25
+ "moe_intermediate_size": 608,
26
+ "moe_layer_freq": 1,
27
+ "mtp_loss_lambda": 0.1,
28
+ "n_future_tokens": 2,
29
+ "n_group": 8,
30
+ "n_routed_experts": 64,
31
+ "n_shared_experts": 2,
32
+ "norm_topk_prob": true,
33
+ "num_attention_heads": 8,
34
+ "num_experts_per_tok": 6,
35
+ "num_hidden_layers": 27,
36
+ "num_key_value_heads": 8,
37
+ "num_nextn_predict_layers": 1,
38
+ "output_router_logits": false,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": null,
41
+ "qk_nope_head_dim": 32,
42
+ "qk_rope_head_dim": 16,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 0.707,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 1.0,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": false,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.48.3",
62
+ "use_cache": true,
63
+ "use_lossfreebalance": false,
64
+ "v_head_dim": 32,
65
+ "vocab_size": 129280
66
+ }
checkpoint-12000/configuration_tinydeepseek.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TinyDeepseekV3Config(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
+ n_future_tokens (int):
104
+ Number of prediction heads in the model (= 1 + `len(extra_heads)`).
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "tinydeepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'aux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.0001,
147
+ seq_aux=True,
148
+ output_router_logits=False,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ n_future_tokens=1,
164
+ mtp_loss_lambda=0.1,
165
+ use_lossfreebalance=True,
166
+ lossfreebalance_update_rate=0.001,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.moe_intermediate_size = moe_intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_nextn_predict_layers = num_nextn_predict_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.n_shared_experts = n_shared_experts
178
+ self.n_routed_experts = n_routed_experts
179
+ self.ep_size = ep_size
180
+ self.routed_scaling_factor = routed_scaling_factor
181
+ self.kv_lora_rank = kv_lora_rank
182
+ self.q_lora_rank = q_lora_rank if q_lora_rank else None
183
+ self.qk_rope_head_dim = qk_rope_head_dim
184
+ self.v_head_dim = v_head_dim
185
+ self.qk_nope_head_dim = qk_nope_head_dim
186
+ self.topk_method = topk_method
187
+ self.n_group = n_group
188
+ self.topk_group = topk_group
189
+ self.num_experts_per_tok = num_experts_per_tok
190
+ self.moe_layer_freq = moe_layer_freq
191
+ self.first_k_dense_replace = first_k_dense_replace
192
+ self.norm_topk_prob = norm_topk_prob
193
+ self.scoring_func = scoring_func
194
+ self.aux_loss_alpha = aux_loss_alpha
195
+ self.seq_aux = seq_aux
196
+ self.output_router_logits = output_router_logits
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.rms_norm_eps = rms_norm_eps
205
+ self.pretraining_tp = pretraining_tp
206
+ self.use_cache = use_cache
207
+ self.rope_theta = rope_theta
208
+ self.rope_scaling = rope_scaling
209
+ self.attention_bias = attention_bias
210
+ self.attention_dropout = attention_dropout
211
+ self.n_future_tokens = n_future_tokens
212
+ self.mtp_loss_lambda = mtp_loss_lambda
213
+ self.use_lossfreebalance = use_lossfreebalance
214
+ self.lossfreebalance_update_rate = lossfreebalance_update_rate
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
checkpoint-12000/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.48.3",
6
+ "use_cache": false
7
+ }
checkpoint-12000/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:101614fdf2e8d66529dfbd121ad6c4249a90a5416eaa38f75ec775a1ad96e2cf
3
+ size 5000243440
checkpoint-12000/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f2f606f40c230b1aa03bddd121a0b7fcd2ff9e353cd23e0f9bc62f5cbb45025
3
+ size 1591021104
checkpoint-12000/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-12000/modeling_tinydeepseek.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MoeModelOutputWithPast,
40
+ MoeCausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ # is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_tinydeepseek import TinyDeepseekV3Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ # if not is_torch_greater_or_equal_than_1_13:
70
+ # import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "TinyDeepseekV3Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
94
+ def load_balancing_loss_func(
95
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
96
+ num_experts: Optional[int] = None,
97
+ top_k=2,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ ) -> Union[torch.Tensor, int]:
100
+ r"""
101
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
102
+
103
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
104
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
105
+ experts is too unbalanced.
106
+
107
+ Args:
108
+ gate_logits:
109
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
110
+ shape [batch_size X sequence_length, num_experts].
111
+ num_experts:
112
+ Number of experts
113
+ top_k:
114
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
115
+ parameter.
116
+ attention_mask (`torch.Tensor`, *optional*):
117
+ The attention_mask used in forward function
118
+ shape [batch_size X sequence_length] if not None.
119
+
120
+ Returns:
121
+ The auxiliary loss.
122
+ """
123
+ if gate_logits is None or not isinstance(gate_logits, tuple):
124
+ return 0
125
+
126
+ if isinstance(gate_logits, tuple):
127
+ compute_device = gate_logits[0].device
128
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
129
+
130
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
131
+
132
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
133
+
134
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
135
+
136
+ if attention_mask is None:
137
+ # Compute the percentage of tokens routed to each experts
138
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
139
+
140
+ # Compute the average probability of routing to these experts
141
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
142
+ else:
143
+ batch_size, sequence_length = attention_mask.shape
144
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
145
+
146
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
147
+ expert_attention_mask = (
148
+ attention_mask[None, :, :, None, None]
149
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
150
+ .reshape(-1, top_k, num_experts)
151
+ .to(compute_device)
152
+ )
153
+
154
+ # Compute the percentage of tokens routed to each experts
155
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
156
+ expert_attention_mask, dim=0
157
+ )
158
+
159
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
160
+ router_per_expert_attention_mask = (
161
+ attention_mask[None, :, :, None]
162
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
163
+ .reshape(-1, num_experts)
164
+ .to(compute_device)
165
+ )
166
+
167
+ # Compute the average probability of routing to these experts
168
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
169
+ router_per_expert_attention_mask, dim=0
170
+ )
171
+
172
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
173
+ return overall_loss * num_experts
174
+
175
+
176
+ class DeepseekV3RMSNorm(nn.Module):
177
+ def __init__(self, hidden_size, eps=1e-6):
178
+ """
179
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
180
+ """
181
+ super().__init__()
182
+ self.weight = nn.Parameter(torch.ones(hidden_size))
183
+ self.variance_epsilon = eps
184
+
185
+ def forward(self, hidden_states):
186
+ input_dtype = hidden_states.dtype
187
+ hidden_states = hidden_states.to(torch.float32)
188
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
189
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
190
+ return self.weight * hidden_states.to(input_dtype)
191
+
192
+
193
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
194
+
195
+
196
+ class DeepseekV3RotaryEmbedding(nn.Module):
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
198
+ super().__init__()
199
+
200
+ self.dim = dim
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.base = base
203
+ inv_freq = 1.0 / (
204
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
205
+ )
206
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
207
+
208
+ # Build here to make `torch.jit.trace` work.
209
+ self._set_cos_sin_cache(
210
+ seq_len=max_position_embeddings,
211
+ device=self.inv_freq.device,
212
+ dtype=torch.get_default_dtype(),
213
+ )
214
+ self.max_seq_len_cached = None
215
+
216
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
217
+ self.max_seq_len_cached = seq_len
218
+ t = torch.arange(
219
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
220
+ )
221
+
222
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
223
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
224
+ emb = torch.cat((freqs, freqs), dim=-1)
225
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
226
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
227
+
228
+ def forward(self, x, seq_len=None):
229
+ # x: [bs, num_attention_heads, seq_len, head_size]
230
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
231
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
232
+
233
+ return (
234
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
235
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
236
+ )
237
+
238
+
239
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
240
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
241
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ max_position_embeddings=2048,
247
+ base=10000,
248
+ device=None,
249
+ scaling_factor=1.0,
250
+ ):
251
+ self.scaling_factor = scaling_factor
252
+ super().__init__(dim, max_position_embeddings, base, device)
253
+
254
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
255
+ self.max_seq_len_cached = seq_len
256
+ t = torch.arange(
257
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
258
+ )
259
+ t = t / self.scaling_factor
260
+
261
+ freqs = torch.outer(t, self.inv_freq)
262
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
263
+ emb = torch.cat((freqs, freqs), dim=-1)
264
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
265
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
266
+
267
+
268
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
269
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
270
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
271
+
272
+ def __init__(
273
+ self,
274
+ dim,
275
+ max_position_embeddings=2048,
276
+ base=10000,
277
+ device=None,
278
+ scaling_factor=1.0,
279
+ ):
280
+ self.scaling_factor = scaling_factor
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
+
286
+ if seq_len > self.max_position_embeddings:
287
+ base = self.base * (
288
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
289
+ - (self.scaling_factor - 1)
290
+ ) ** (self.dim / (self.dim - 2))
291
+ inv_freq = 1.0 / (
292
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
293
+ )
294
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
295
+
296
+ t = torch.arange(
297
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
298
+ )
299
+
300
+ freqs = torch.outer(t, self.inv_freq)
301
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
302
+ emb = torch.cat((freqs, freqs), dim=-1)
303
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
304
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
305
+
306
+
307
+ # Inverse dim formula to find dim based on number of rotations
308
+ def yarn_find_correction_dim(
309
+ num_rotations, dim, base=10000, max_position_embeddings=2048
310
+ ):
311
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
312
+ 2 * math.log(base)
313
+ )
314
+
315
+
316
+ # Find dim range bounds based on rotations
317
+ def yarn_find_correction_range(
318
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
319
+ ):
320
+ low = math.floor(
321
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
322
+ )
323
+ high = math.ceil(
324
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
325
+ )
326
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
327
+
328
+
329
+ def yarn_get_mscale(scale=1, mscale=1):
330
+ if scale <= 1:
331
+ return 1.0
332
+ return 0.1 * mscale * math.log(scale) + 1.0
333
+
334
+
335
+ def yarn_linear_ramp_mask(min, max, dim):
336
+ if min == max:
337
+ max += 0.001 # Prevent singularity
338
+
339
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
340
+ ramp_func = torch.clamp(linear_func, 0, 1)
341
+ return ramp_func
342
+
343
+
344
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
345
+
346
+ def __init__(
347
+ self,
348
+ dim,
349
+ max_position_embeddings=2048,
350
+ base=10000,
351
+ device=None,
352
+ scaling_factor=1.0,
353
+ original_max_position_embeddings=4096,
354
+ beta_fast=32,
355
+ beta_slow=1,
356
+ mscale=1,
357
+ mscale_all_dim=0,
358
+ ):
359
+ self.scaling_factor = scaling_factor
360
+ self.original_max_position_embeddings = original_max_position_embeddings
361
+ self.beta_fast = beta_fast
362
+ self.beta_slow = beta_slow
363
+ self.mscale = mscale
364
+ self.mscale_all_dim = mscale_all_dim
365
+ super().__init__(dim, max_position_embeddings, base, device)
366
+
367
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
368
+ self.max_seq_len_cached = seq_len
369
+ dim = self.dim
370
+
371
+ freq_extra = 1.0 / (
372
+ self.base
373
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
374
+ )
375
+ freq_inter = 1.0 / (
376
+ self.scaling_factor
377
+ * self.base
378
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
379
+ )
380
+
381
+ low, high = yarn_find_correction_range(
382
+ self.beta_fast,
383
+ self.beta_slow,
384
+ dim,
385
+ self.base,
386
+ self.original_max_position_embeddings,
387
+ )
388
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
389
+ device=device, dtype=torch.float32
390
+ )
391
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
392
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
393
+
394
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
395
+
396
+ freqs = torch.outer(t, inv_freq)
397
+
398
+ _mscale = float(
399
+ yarn_get_mscale(self.scaling_factor, self.mscale)
400
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
401
+ )
402
+
403
+ emb = torch.cat((freqs, freqs), dim=-1)
404
+ self.register_buffer(
405
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
406
+ )
407
+ self.register_buffer(
408
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
409
+ )
410
+
411
+
412
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
413
+ def rotate_half(x):
414
+ """Rotates half the hidden dims of the input."""
415
+ x1 = x[..., : x.shape[-1] // 2]
416
+ x2 = x[..., x.shape[-1] // 2 :]
417
+ return torch.cat((-x2, x1), dim=-1)
418
+
419
+
420
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
421
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
422
+ """Applies Rotary Position Embedding to the query and key tensors.
423
+
424
+ Args:
425
+ q (`torch.Tensor`): The query tensor.
426
+ k (`torch.Tensor`): The key tensor.
427
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
428
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
429
+ position_ids (`torch.Tensor`):
430
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
431
+ used to pass offsetted position ids when working with a KV-cache.
432
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
433
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
434
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
435
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
436
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
437
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
438
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
439
+ Returns:
440
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
441
+ """
442
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
443
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
444
+
445
+ b, h, s, d = q.shape
446
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
447
+
448
+ b, h, s, d = k.shape
449
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
450
+
451
+ q_embed = (q * cos) + (rotate_half(q) * sin)
452
+ k_embed = (k * cos) + (rotate_half(k) * sin)
453
+ return q_embed, k_embed
454
+
455
+
456
+ class DeepseekV3MLP(nn.Module):
457
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
458
+ super().__init__()
459
+ self.config = config
460
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
461
+ self.intermediate_size = (
462
+ config.intermediate_size if intermediate_size is None else intermediate_size
463
+ )
464
+
465
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
466
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
467
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
468
+ self.act_fn = ACT2FN[config.hidden_act]
469
+
470
+ def forward(self, x):
471
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
472
+ return down_proj
473
+
474
+
475
+ class MoEGate(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.config = config
479
+ self.top_k = config.num_experts_per_tok
480
+ self.n_routed_experts = config.n_routed_experts
481
+ self.routed_scaling_factor = config.routed_scaling_factor
482
+ self.scoring_func = config.scoring_func
483
+ self.seq_aux = config.seq_aux
484
+ self.topk_method = config.topk_method
485
+ self.n_group = config.n_group
486
+ self.topk_group = config.topk_group
487
+
488
+ # topk selection algorithm
489
+ self.norm_topk_prob = config.norm_topk_prob
490
+ self.gating_dim = config.hidden_size
491
+ self.weight = nn.Parameter(
492
+ torch.empty((self.n_routed_experts, self.gating_dim))
493
+ )
494
+ if self.topk_method == "noaux_tc":
495
+ self.e_score_correction_bias = nn.Parameter(
496
+ torch.empty((self.n_routed_experts))
497
+ )
498
+ elif self.topk_method == "aux_tc":
499
+ self.update_rate = config.lossfreebalance_update_rate
500
+ self.e_score_correction_bias = nn.Parameter(
501
+ torch.zeros((self.n_routed_experts))
502
+ )
503
+
504
+ self.reset_parameters()
505
+
506
+ def reset_parameters(self) -> None:
507
+ import torch.nn.init as init
508
+
509
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
510
+
511
+ def forward(self, hidden_states):
512
+ bsz, seq_len, h = hidden_states.shape
513
+ ### compute gating score
514
+ hidden_states = hidden_states.view(-1, h)
515
+ logits = F.linear(
516
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
517
+ )
518
+ if self.scoring_func == "sigmoid":
519
+ scores = logits.sigmoid()
520
+ else:
521
+ raise NotImplementedError(
522
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
523
+ )
524
+
525
+ ### select top-k experts
526
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
527
+ group_scores = (
528
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
529
+ ) # [n, n_group]
530
+ group_idx = torch.topk(
531
+ group_scores, k=self.topk_group, dim=-1, sorted=False
532
+ )[
533
+ 1
534
+ ] # [n, top_k_group]
535
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
536
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
537
+ score_mask = (
538
+ group_mask.unsqueeze(-1)
539
+ .expand(
540
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
541
+ )
542
+ .reshape(bsz * seq_len, -1)
543
+ ) # [n, e]
544
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
545
+ _, topk_idx = torch.topk(
546
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
547
+ )
548
+ topk_weight = scores.gather(1, topk_idx)
549
+
550
+ if self.topk_method == "aux_tc":
551
+ expert_counts = torch.bincount(
552
+ topk_idx.flatten(),
553
+ minlength=self.n_routed_experts
554
+ )
555
+
556
+ avg_count = expert_counts.float().mean()
557
+ #max_violation = torch.max(torch.abs(expert_counts.float() - avg_count) / avg_count)
558
+
559
+ # for monitoring the expert-balancing globallu
560
+ # min_violation = torch.min(expert_counts.float()) / avg_count
561
+ # max_violation = torch.max(expert_counts.float()) / avg_count
562
+ # return [min_violation.item(), max_violation.item()]
563
+
564
+ for expert_idx, expert_count in enumerate(expert_counts):
565
+ # b_i = b_i + u + sign(e_i)
566
+ # note: this is \bar{c_i} - c_i, NOT c_i - \bar{c_i}, which will push the network to
567
+ # be maximally unbalanced. Really important to get this part right!!!
568
+ count_error = avg_count - expert_count.float()
569
+ self.e_score_correction_bias.data[expert_idx] += (self.update_rate * torch.sign(count_error))
570
+
571
+ ### norm gate to sum 1
572
+ if self.top_k > 1 and self.norm_topk_prob:
573
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
574
+ topk_weight = topk_weight / denominator
575
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
576
+
577
+ return topk_idx, topk_weight, scores
578
+
579
+ class TinyDeepseekV3MoE(nn.Module):
580
+ """
581
+ A mixed expert module containing shared experts.
582
+ """
583
+
584
+ def __init__(self, config):
585
+ super().__init__()
586
+ self.config = config
587
+ self.num_experts_per_tok = config.num_experts_per_tok
588
+
589
+ if hasattr(config, "ep_size") and config.ep_size > 1:
590
+ assert config.ep_size == dist.get_world_size()
591
+ self.ep_size = config.ep_size
592
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
593
+ self.ep_rank = dist.get_rank()
594
+ self.experts = nn.ModuleList(
595
+ [
596
+ (
597
+ DeepseekV3MLP(
598
+ config, intermediate_size=config.moe_intermediate_size
599
+ )
600
+ if i >= self.ep_rank * self.experts_per_rank
601
+ and i < (self.ep_rank + 1) * self.experts_per_rank
602
+ else None
603
+ )
604
+ for i in range(config.n_routed_experts)
605
+ ]
606
+ )
607
+ else:
608
+ self.ep_size = 1
609
+ self.experts_per_rank = config.n_routed_experts
610
+ self.ep_rank = 0
611
+ self.experts = nn.ModuleList(
612
+ [
613
+ DeepseekV3MLP(
614
+ config, intermediate_size=config.moe_intermediate_size
615
+ )
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV3MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, router_scores = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if not self.training:
633
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
634
+ else:
635
+ # tinydeepseek: moe forward for training
636
+ y = self.moe_train(hidden_states, topk_idx, topk_weight).view(*orig_shape)
637
+ if self.config.n_shared_experts is not None:
638
+ y = y + self.shared_experts(identity)
639
+ return y, router_scores
640
+
641
+ @torch.no_grad()
642
+ def moe_infer(self, x, topk_ids, topk_weight):
643
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
644
+ cnts.scatter_(1, topk_ids, 1)
645
+ tokens_per_expert = cnts.sum(dim=0)
646
+ idxs = topk_ids.view(-1).argsort()
647
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
648
+ sorted_tokens_shape = sorted_tokens.shape
649
+ if self.ep_size > 1:
650
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
651
+ tokens_per_expert_group = tokens_per_expert.new_empty(
652
+ tokens_per_expert.shape[0]
653
+ )
654
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
655
+ output_splits = (
656
+ tokens_per_expert_group.view(self.ep_size, -1)
657
+ .sum(1)
658
+ .cpu()
659
+ .numpy()
660
+ .tolist()
661
+ )
662
+ gathered_tokens = sorted_tokens.new_empty(
663
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
664
+ )
665
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
666
+ dist.all_to_all(
667
+ list(gathered_tokens.split(output_splits)),
668
+ list(sorted_tokens.split(input_split_sizes)),
669
+ )
670
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
671
+ self.ep_size, self.experts_per_rank
672
+ ).sum(dim=0)
673
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
674
+ s = 0
675
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
676
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
677
+ s += k
678
+ gatherd_idxs = gatherd_idxs.argsort()
679
+ sorted_tokens = gathered_tokens[gatherd_idxs]
680
+ tokens_per_expert = tokens_per_expert_post_gather
681
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
682
+
683
+ outputs = []
684
+ start_idx = 0
685
+ for i, num_tokens in enumerate(tokens_per_expert):
686
+ end_idx = start_idx + num_tokens
687
+ if num_tokens == 0:
688
+ continue
689
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
690
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
691
+ expert_out = expert(tokens_for_this_expert)
692
+ outputs.append(expert_out)
693
+ start_idx = end_idx
694
+
695
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
696
+ if self.ep_size > 1:
697
+ new_x = torch.empty_like(outs)
698
+ new_x[gatherd_idxs] = outs
699
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
700
+ dist.all_to_all(
701
+ list(gathered_tokens.split(input_split_sizes)),
702
+ list(new_x.split(output_splits)),
703
+ )
704
+ outs = gathered_tokens
705
+
706
+ new_x = torch.empty_like(outs)
707
+ new_x[idxs] = outs
708
+ final_out = (
709
+ new_x.view(*topk_ids.shape, -1)
710
+ .type(topk_weight.dtype)
711
+ .mul_(topk_weight.unsqueeze(dim=-1))
712
+ .sum(dim=1)
713
+ .type(new_x.dtype)
714
+ )
715
+ return final_out
716
+
717
+
718
+ def moe_train(self, x, topk_ids, topk_weight):
719
+ token_size, hidden_dim = x.shape # token_size = bsz_size * seq_len
720
+ final_hidden_states = torch.zeros(
721
+ (token_size, hidden_dim), dtype=x.dtype, device=x.device
722
+ )
723
+
724
+ # One hot encode the selected experts to create an expert mask
725
+ # this will be used to easily index which expert is going to be sollicitated
726
+ expert_mask = torch.nn.functional.one_hot(topk_ids, num_classes=self.config.n_routed_experts).permute(2, 1, 0)
727
+
728
+ # Loop over all available experts in the model and perform the computation on each expert
729
+ for expert_idx in range(self.config.n_routed_experts):
730
+ expert_layer = self.experts[expert_idx]
731
+ idx, top_x = torch.where(expert_mask[expert_idx])
732
+
733
+ # Index the correct hidden states and compute the expert hidden state for
734
+ # the current expert. We need to make sure to multiply the output hidden
735
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
736
+ current_state = x[None, top_x].reshape(-1, hidden_dim)
737
+ current_hidden_states = expert_layer(current_state) * topk_weight[top_x, idx, None]
738
+
739
+ # However `index_add_` only support torch tensors for indexing so we'll use
740
+ # the `top_x` tensor here.
741
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(x.dtype))
742
+
743
+ return final_hidden_states.view(-1, hidden_dim)
744
+
745
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
746
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
747
+ """
748
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
749
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
750
+ """
751
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
752
+ if n_rep == 1:
753
+ return hidden_states
754
+ hidden_states = hidden_states[:, :, None, :, :].expand(
755
+ batch, num_key_value_heads, n_rep, slen, head_dim
756
+ )
757
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
758
+
759
+
760
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
761
+ class DeepseekV3Attention(nn.Module):
762
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
763
+
764
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: Optional[int] = None):
765
+ super().__init__()
766
+ self.config = config
767
+ self.layer_idx = layer_idx
768
+ if layer_idx is None:
769
+ logger.warning_once(
770
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
771
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
772
+ "when creating this class."
773
+ )
774
+
775
+ self.attention_dropout = config.attention_dropout
776
+ self.hidden_size = config.hidden_size
777
+ self.num_heads = config.num_attention_heads
778
+
779
+ self.max_position_embeddings = config.max_position_embeddings
780
+ self.rope_theta = config.rope_theta
781
+ self.q_lora_rank = config.q_lora_rank
782
+ self.qk_rope_head_dim = config.qk_rope_head_dim
783
+ self.kv_lora_rank = config.kv_lora_rank
784
+ self.v_head_dim = config.v_head_dim
785
+ self.qk_nope_head_dim = config.qk_nope_head_dim
786
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
787
+
788
+ self.is_causal = True
789
+
790
+ if self.q_lora_rank is None:
791
+ self.q_proj = nn.Linear(
792
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
793
+ )
794
+ else:
795
+ self.q_a_proj = nn.Linear(
796
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
797
+ )
798
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
799
+ self.q_b_proj = nn.Linear(
800
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
801
+ )
802
+
803
+ self.kv_a_proj_with_mqa = nn.Linear(
804
+ self.hidden_size,
805
+ config.kv_lora_rank + config.qk_rope_head_dim,
806
+ bias=config.attention_bias,
807
+ )
808
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
809
+ self.kv_b_proj = nn.Linear(
810
+ config.kv_lora_rank,
811
+ self.num_heads
812
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
813
+ bias=False,
814
+ )
815
+
816
+ self.o_proj = nn.Linear(
817
+ self.num_heads * self.v_head_dim,
818
+ self.hidden_size,
819
+ bias=config.attention_bias,
820
+ )
821
+ self._init_rope()
822
+
823
+ self.softmax_scale = self.q_head_dim ** (-0.5)
824
+ if self.config.rope_scaling is not None:
825
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
826
+ scaling_factor = self.config.rope_scaling["factor"]
827
+ if mscale_all_dim:
828
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
829
+ self.softmax_scale = self.softmax_scale * mscale * mscale
830
+
831
+ def _init_rope(self):
832
+ if self.config.rope_scaling is None:
833
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
834
+ self.qk_rope_head_dim,
835
+ max_position_embeddings=self.max_position_embeddings,
836
+ base=self.rope_theta,
837
+ )
838
+ else:
839
+ scaling_type = self.config.rope_scaling["type"]
840
+ scaling_factor = self.config.rope_scaling["factor"]
841
+ if scaling_type == "linear":
842
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
843
+ self.qk_rope_head_dim,
844
+ max_position_embeddings=self.max_position_embeddings,
845
+ scaling_factor=scaling_factor,
846
+ base=self.rope_theta,
847
+ )
848
+ elif scaling_type == "dynamic":
849
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
850
+ self.qk_rope_head_dim,
851
+ max_position_embeddings=self.max_position_embeddings,
852
+ scaling_factor=scaling_factor,
853
+ base=self.rope_theta,
854
+ )
855
+ elif scaling_type == "yarn":
856
+ kwargs = {
857
+ key: self.config.rope_scaling[key]
858
+ for key in [
859
+ "original_max_position_embeddings",
860
+ "beta_fast",
861
+ "beta_slow",
862
+ "mscale",
863
+ "mscale_all_dim",
864
+ ]
865
+ if key in self.config.rope_scaling
866
+ }
867
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
868
+ self.qk_rope_head_dim,
869
+ max_position_embeddings=self.max_position_embeddings,
870
+ scaling_factor=scaling_factor,
871
+ base=self.rope_theta,
872
+ **kwargs,
873
+ )
874
+ else:
875
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
876
+
877
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
878
+ return (
879
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
880
+ .transpose(1, 2)
881
+ .contiguous()
882
+ )
883
+
884
+ def forward(
885
+ self,
886
+ hidden_states: torch.Tensor,
887
+ attention_mask: Optional[torch.Tensor] = None,
888
+ position_ids: Optional[torch.LongTensor] = None,
889
+ past_key_value: Optional[Cache] = None,
890
+ output_attentions: bool = False,
891
+ use_cache: bool = False,
892
+ **kwargs,
893
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
894
+ if "padding_mask" in kwargs:
895
+ warnings.warn(
896
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
897
+ )
898
+ bsz, q_len, _ = hidden_states.size()
899
+
900
+ if self.q_lora_rank is None:
901
+ q = self.q_proj(hidden_states)
902
+ else:
903
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
904
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
905
+ q_nope, q_pe = torch.split(
906
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
907
+ )
908
+
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
+ if past_key_value is not None:
925
+ if self.layer_idx is None:
926
+ raise ValueError(
927
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
928
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
929
+ "with a layer index."
930
+ )
931
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
932
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
933
+
934
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
935
+
936
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
937
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
938
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
939
+
940
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
941
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
942
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
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
+ attn_weights = (
950
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
951
+ )
952
+
953
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
954
+ raise ValueError(
955
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
956
+ f" {attn_weights.size()}"
957
+ )
958
+ assert attention_mask is not None
959
+ if attention_mask is not None:
960
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
961
+ raise ValueError(
962
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
963
+ )
964
+ attn_weights = attn_weights + attention_mask
965
+
966
+ # upcast attention to fp32
967
+ attn_weights = nn.functional.softmax(
968
+ attn_weights, dim=-1, dtype=torch.float32
969
+ ).to(query_states.dtype)
970
+ attn_weights = nn.functional.dropout(
971
+ attn_weights, p=self.attention_dropout, training=self.training
972
+ )
973
+ attn_output = torch.matmul(attn_weights, value_states)
974
+
975
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
976
+ raise ValueError(
977
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
978
+ f" {attn_output.size()}"
979
+ )
980
+
981
+ attn_output = attn_output.transpose(1, 2).contiguous()
982
+
983
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
984
+
985
+ attn_output = self.o_proj(attn_output)
986
+
987
+ if not output_attentions:
988
+ attn_weights = None
989
+
990
+ return attn_output, attn_weights, past_key_value
991
+
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
994
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
995
+ """
996
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
997
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
998
+ flash attention and deal with padding tokens in case the input contains any of them.
999
+ """
1000
+
1001
+ def __init__(self, *args, **kwargs):
1002
+ super().__init__(*args, **kwargs)
1003
+
1004
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1005
+ # 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.
1006
+ # 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).
1007
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1008
+
1009
+ def forward(
1010
+ self,
1011
+ hidden_states: torch.Tensor,
1012
+ attention_mask: Optional[torch.LongTensor] = None,
1013
+ position_ids: Optional[torch.LongTensor] = None,
1014
+ past_key_value: Optional[Cache] = None,
1015
+ output_attentions: bool = False,
1016
+ use_cache: bool = False,
1017
+ **kwargs,
1018
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1019
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1020
+ if "padding_mask" in kwargs:
1021
+ warnings.warn(
1022
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1023
+ )
1024
+
1025
+ # overwrite attention_mask with padding_mask
1026
+ attention_mask = kwargs.pop("padding_mask")
1027
+
1028
+ output_attentions = False
1029
+
1030
+ bsz, q_len, _ = hidden_states.size()
1031
+
1032
+ if self.q_lora_rank is None:
1033
+ q = self.q_proj(hidden_states)
1034
+ else:
1035
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1036
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1037
+ q_nope, q_pe = torch.split(
1038
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1039
+ )
1040
+
1041
+ # Flash attention requires the input to have the shape
1042
+ # batch_size x seq_length x head_dim x hidden_dim
1043
+ # therefore we just need to keep the original shape
1044
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1045
+ compressed_kv, k_pe = torch.split(
1046
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1047
+ )
1048
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1049
+ kv = (
1050
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1051
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1052
+ .transpose(1, 2)
1053
+ )
1054
+
1055
+ k_nope, value_states = torch.split(
1056
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1057
+ )
1058
+ kv_seq_len = value_states.shape[-2]
1059
+
1060
+ kv_seq_len = value_states.shape[-2]
1061
+ if past_key_value is not None:
1062
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1063
+
1064
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1065
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1066
+
1067
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1068
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1069
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1070
+
1071
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1072
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1073
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1074
+
1075
+ if self.q_head_dim != self.v_head_dim:
1076
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1077
+
1078
+ if past_key_value is not None:
1079
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1080
+ key_states, value_states = past_key_value.update(
1081
+ key_states, value_states, self.layer_idx, cache_kwargs
1082
+ )
1083
+
1084
+ # 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
1085
+ # to be able to avoid many of these transpose/reshape/view.
1086
+ query_states = query_states.transpose(1, 2)
1087
+ key_states = key_states.transpose(1, 2)
1088
+ value_states = value_states.transpose(1, 2)
1089
+
1090
+ dropout_rate = self.attention_dropout if self.training else 0.0
1091
+
1092
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1093
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1094
+ # cast them back in the correct dtype just to be sure everything works as expected.
1095
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1096
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1097
+
1098
+ input_dtype = query_states.dtype
1099
+ if input_dtype == torch.float32:
1100
+ # Handle the case where the model is quantized
1101
+ if hasattr(self.config, "_pre_quantization_dtype"):
1102
+ target_dtype = self.config._pre_quantization_dtype
1103
+ elif torch.is_autocast_enabled():
1104
+ target_dtype = torch.get_autocast_gpu_dtype()
1105
+ else:
1106
+ target_dtype = (
1107
+ self.q_proj.weight.dtype
1108
+ if self.q_lora_rank is None
1109
+ else self.q_a_proj.weight.dtype
1110
+ )
1111
+
1112
+ logger.warning_once(
1113
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1114
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1115
+ f" {target_dtype}."
1116
+ )
1117
+
1118
+ query_states = query_states.to(target_dtype)
1119
+ key_states = key_states.to(target_dtype)
1120
+ value_states = value_states.to(target_dtype)
1121
+
1122
+ attn_output = self._flash_attention_forward(
1123
+ query_states,
1124
+ key_states,
1125
+ value_states,
1126
+ attention_mask,
1127
+ q_len,
1128
+ dropout=dropout_rate,
1129
+ softmax_scale=self.softmax_scale,
1130
+ )
1131
+ if self.q_head_dim != self.v_head_dim:
1132
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1133
+
1134
+ attn_output = attn_output.reshape(
1135
+ bsz, q_len, self.num_heads * self.v_head_dim
1136
+ ).contiguous()
1137
+ attn_output = self.o_proj(attn_output)
1138
+
1139
+ if not output_attentions:
1140
+ attn_weights = None
1141
+
1142
+ return attn_output, attn_weights, past_key_value
1143
+
1144
+ def _flash_attention_forward(
1145
+ self,
1146
+ query_states,
1147
+ key_states,
1148
+ value_states,
1149
+ attention_mask,
1150
+ query_length,
1151
+ dropout=0.0,
1152
+ softmax_scale=None,
1153
+ ):
1154
+ """
1155
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1156
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1157
+
1158
+ Args:
1159
+ query_states (`torch.Tensor`):
1160
+ Input query states to be passed to Flash Attention API
1161
+ key_states (`torch.Tensor`):
1162
+ Input key states to be passed to Flash Attention API
1163
+ value_states (`torch.Tensor`):
1164
+ Input value states to be passed to Flash Attention API
1165
+ attention_mask (`torch.Tensor`):
1166
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1167
+ position of padding tokens and 1 for the position of non-padding tokens.
1168
+ dropout (`int`, *optional*):
1169
+ Attention dropout
1170
+ softmax_scale (`float`, *optional*):
1171
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1172
+ """
1173
+ if not self._flash_attn_uses_top_left_mask:
1174
+ causal = self.is_causal
1175
+ else:
1176
+ # 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__.
1177
+ causal = self.is_causal and query_length != 1
1178
+
1179
+ # Contains at least one padding token in the sequence
1180
+ if attention_mask is not None:
1181
+ batch_size = query_states.shape[0]
1182
+ (
1183
+ query_states,
1184
+ key_states,
1185
+ value_states,
1186
+ indices_q,
1187
+ cu_seq_lens,
1188
+ max_seq_lens,
1189
+ ) = self._upad_input(
1190
+ query_states, key_states, value_states, attention_mask, query_length
1191
+ )
1192
+
1193
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1194
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1195
+
1196
+ attn_output_unpad = flash_attn_varlen_func(
1197
+ query_states,
1198
+ key_states,
1199
+ value_states,
1200
+ cu_seqlens_q=cu_seqlens_q,
1201
+ cu_seqlens_k=cu_seqlens_k,
1202
+ max_seqlen_q=max_seqlen_in_batch_q,
1203
+ max_seqlen_k=max_seqlen_in_batch_k,
1204
+ dropout_p=dropout,
1205
+ softmax_scale=softmax_scale,
1206
+ causal=causal,
1207
+ )
1208
+
1209
+ attn_output = pad_input(
1210
+ attn_output_unpad, indices_q, batch_size, query_length
1211
+ )
1212
+ else:
1213
+ attn_output = flash_attn_func(
1214
+ query_states,
1215
+ key_states,
1216
+ value_states,
1217
+ dropout,
1218
+ softmax_scale=softmax_scale,
1219
+ causal=causal,
1220
+ )
1221
+
1222
+ return attn_output
1223
+
1224
+ def _upad_input(
1225
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1226
+ ):
1227
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1228
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1229
+
1230
+ key_layer = index_first_axis(
1231
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1232
+ indices_k,
1233
+ )
1234
+ value_layer = index_first_axis(
1235
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1236
+ indices_k,
1237
+ )
1238
+ if query_length == kv_seq_len:
1239
+ query_layer = index_first_axis(
1240
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1241
+ indices_k,
1242
+ )
1243
+ cu_seqlens_q = cu_seqlens_k
1244
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1245
+ indices_q = indices_k
1246
+ elif query_length == 1:
1247
+ max_seqlen_in_batch_q = 1
1248
+ cu_seqlens_q = torch.arange(
1249
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1250
+ ) # There is a memcpy here, that is very bad.
1251
+ indices_q = cu_seqlens_q[:-1]
1252
+ query_layer = query_layer.squeeze(1)
1253
+ else:
1254
+ # The -q_len: slice assumes left padding.
1255
+ attention_mask = attention_mask[:, -query_length:]
1256
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1257
+ query_layer, attention_mask
1258
+ )
1259
+
1260
+ return (
1261
+ query_layer,
1262
+ key_layer,
1263
+ value_layer,
1264
+ indices_q,
1265
+ (cu_seqlens_q, cu_seqlens_k),
1266
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1267
+ )
1268
+
1269
+
1270
+ ATTENTION_CLASSES = {
1271
+ "eager": DeepseekV3Attention,
1272
+ "flash_attention_2": DeepseekV3FlashAttention2,
1273
+ }
1274
+
1275
+
1276
+ class DeepseekV3DecoderLayer(nn.Module):
1277
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: int):
1278
+ super().__init__()
1279
+ self.hidden_size = config.hidden_size
1280
+
1281
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1282
+ config=config, layer_idx=layer_idx
1283
+ )
1284
+
1285
+ self.mlp = (
1286
+ TinyDeepseekV3MoE(config)
1287
+ if (
1288
+ config.n_routed_experts is not None
1289
+ and layer_idx >= config.first_k_dense_replace
1290
+ and layer_idx % config.moe_layer_freq == 0
1291
+ )
1292
+ else DeepseekV3MLP(config)
1293
+ )
1294
+ self.input_layernorm = DeepseekV3RMSNorm(
1295
+ config.hidden_size, eps=config.rms_norm_eps
1296
+ )
1297
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1298
+ config.hidden_size, eps=config.rms_norm_eps
1299
+ )
1300
+
1301
+ def forward(
1302
+ self,
1303
+ hidden_states: torch.Tensor,
1304
+ attention_mask: Optional[torch.Tensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1307
+ output_attentions: Optional[bool] = False,
1308
+ output_router_logits: Optional[bool] = False,
1309
+ use_cache: Optional[bool] = False,
1310
+ **kwargs,
1311
+ ) -> Tuple[
1312
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1313
+ ]:
1314
+ """
1315
+ Args:
1316
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1317
+ attention_mask (`torch.FloatTensor`, *optional*):
1318
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1319
+ query_sequence_length, key_sequence_length)` if default attention is used.
1320
+ output_attentions (`bool`, *optional*):
1321
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1322
+ returned tensors for more detail.
1323
+ use_cache (`bool`, *optional*):
1324
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1325
+ (see `past_key_values`).
1326
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1327
+ """
1328
+ if "padding_mask" in kwargs:
1329
+ warnings.warn(
1330
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1331
+ )
1332
+ residual = hidden_states
1333
+
1334
+ hidden_states = self.input_layernorm(hidden_states)
1335
+
1336
+ # Self Attention
1337
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1338
+ hidden_states=hidden_states,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_value=past_key_value,
1342
+ output_attentions=output_attentions,
1343
+ use_cache=use_cache,
1344
+ **kwargs,
1345
+ )
1346
+ hidden_states = residual + hidden_states
1347
+
1348
+ # Fully Connected
1349
+ residual = hidden_states
1350
+ hidden_states = self.post_attention_layernorm(hidden_states)
1351
+ hidden_states = self.mlp(hidden_states)
1352
+ if isinstance(hidden_states, tuple):
1353
+ hidden_states, router_scores = hidden_states
1354
+ else:
1355
+ router_scores = None
1356
+ hidden_states = residual + hidden_states
1357
+
1358
+ outputs = (hidden_states,)
1359
+
1360
+ if output_attentions:
1361
+ outputs += (self_attn_weights,)
1362
+
1363
+ if use_cache:
1364
+ outputs += (present_key_value,)
1365
+
1366
+ if output_router_logits:
1367
+ outputs += (router_scores, )
1368
+
1369
+ return outputs
1370
+
1371
+
1372
+ DeepseekV3_START_DOCSTRING = r"""
1373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1375
+ etc.)
1376
+
1377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1379
+ and behavior.
1380
+
1381
+ Parameters:
1382
+ config ([`TinyDeepseekV3Config`]):
1383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1384
+ load the weights associated with the model, only the configuration. Check out the
1385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1386
+ """
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1391
+ DeepseekV3_START_DOCSTRING,
1392
+ )
1393
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1394
+ config_class = TinyDeepseekV3Config
1395
+ base_model_prefix = "model"
1396
+ supports_gradient_checkpointing = True
1397
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1398
+ _skip_keys_device_placement = "past_key_values"
1399
+ _supports_flash_attn_2 = True
1400
+ _supports_cache_class = True
1401
+
1402
+ def _init_weights(self, module):
1403
+ std = self.config.initializer_range
1404
+ if isinstance(module, nn.Linear):
1405
+ module.weight.data.normal_(mean=0.0, std=std)
1406
+ if module.bias is not None:
1407
+ module.bias.data.zero_()
1408
+ elif isinstance(module, nn.Embedding):
1409
+ module.weight.data.normal_(mean=0.0, std=std)
1410
+ if module.padding_idx is not None:
1411
+ module.weight.data[module.padding_idx].zero_()
1412
+
1413
+
1414
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1415
+ Args:
1416
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1417
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1418
+ it.
1419
+
1420
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1421
+ [`PreTrainedTokenizer.__call__`] for details.
1422
+
1423
+ [What are input IDs?](../glossary#input-ids)
1424
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1425
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1426
+
1427
+ - 1 for tokens that are **not masked**,
1428
+ - 0 for tokens that are **masked**.
1429
+
1430
+ [What are attention masks?](../glossary#attention-mask)
1431
+
1432
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1433
+ [`PreTrainedTokenizer.__call__`] for details.
1434
+
1435
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1436
+ `past_key_values`).
1437
+
1438
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1439
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1440
+ information on the default strategy.
1441
+
1442
+ - 1 indicates the head is **not masked**,
1443
+ - 0 indicates the head is **masked**.
1444
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1446
+ config.n_positions - 1]`.
1447
+
1448
+ [What are position IDs?](../glossary#position-ids)
1449
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1450
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1451
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1452
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1453
+
1454
+ Two formats are allowed:
1455
+ - a [`~cache_utils.Cache`] instance;
1456
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1457
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1458
+ cache format.
1459
+
1460
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1461
+ legacy cache format will be returned.
1462
+
1463
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1464
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1465
+ of shape `(batch_size, sequence_length)`.
1466
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1467
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1468
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1469
+ model's internal embedding lookup matrix.
1470
+ use_cache (`bool`, *optional*):
1471
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1472
+ `past_key_values`).
1473
+ output_attentions (`bool`, *optional*):
1474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1475
+ tensors for more detail.
1476
+ output_hidden_states (`bool`, *optional*):
1477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1478
+ more detail.
1479
+ return_dict (`bool`, *optional*):
1480
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1481
+ """
1482
+
1483
+
1484
+ @add_start_docstrings(
1485
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1486
+ DeepseekV3_START_DOCSTRING,
1487
+ )
1488
+ class TinyDeepseekV3Model(DeepseekV3PreTrainedModel):
1489
+ """
1490
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1491
+
1492
+ Args:
1493
+ config: TinyDeepseekV3Config
1494
+ """
1495
+
1496
+ def __init__(self, config: TinyDeepseekV3Config):
1497
+ super().__init__(config)
1498
+ self.padding_idx = config.pad_token_id
1499
+ self.vocab_size = config.vocab_size
1500
+
1501
+ self.n_future_tokens = config.n_future_tokens
1502
+ assert self.n_future_tokens > 0, "At least one future token prediction needed, i.e., n_future_tokens>0"
1503
+ assert config.num_hidden_layers > self.n_future_tokens, "The number of layer should larger than the n_future_tokens, i.e., config.num_hidden_layers > config.n_future_tokens"
1504
+
1505
+ self.embed_tokens = nn.Embedding(
1506
+ config.vocab_size, config.hidden_size, self.padding_idx
1507
+ )
1508
+ self.layers = nn.ModuleList(
1509
+ [
1510
+ DeepseekV3DecoderLayer(config, layer_idx)
1511
+ for layer_idx in range(config.num_hidden_layers - self.n_future_tokens + 1)
1512
+ ]
1513
+ )
1514
+
1515
+ # Additional prediction heads for multi-token prediction.
1516
+ # `layer_id` counts contiguously from the first Transformer block.
1517
+ self.extra_heads = nn.ModuleList(
1518
+ [
1519
+ DeepseekV3DecoderLayer(config, len(self.layers) + layer_idx)
1520
+ for layer_idx in range(self.n_future_tokens - 1)
1521
+ ]
1522
+ )
1523
+ self.extra_heads_input_norms = nn.ModuleList(
1524
+ [
1525
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1526
+ for _ in range(self.n_future_tokens - 1)
1527
+ ]
1528
+ )
1529
+ self.extra_heads_hidden_norms = nn.ModuleList(
1530
+ [
1531
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1532
+ for _ in range(self.n_future_tokens - 1)
1533
+ ]
1534
+ )
1535
+ self.extra_heads_projections = nn.ModuleList(
1536
+ [
1537
+ nn.Linear(config.hidden_size*2, config.hidden_size, bias=False)
1538
+ for _ in range(self.n_future_tokens - 1)
1539
+ ]
1540
+ )
1541
+
1542
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1543
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1544
+
1545
+ self.gradient_checkpointing = False
1546
+ # Initialize weights and apply final processing
1547
+ self.post_init()
1548
+
1549
+ def get_input_embeddings(self):
1550
+ return self.embed_tokens
1551
+
1552
+ def set_input_embeddings(self, value):
1553
+ self.embed_tokens = value
1554
+
1555
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1556
+ def forward(
1557
+ self,
1558
+ input_ids: torch.LongTensor = None,
1559
+ attention_mask: Optional[torch.Tensor] = None,
1560
+ position_ids: Optional[torch.LongTensor] = None,
1561
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1562
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1563
+ use_cache: Optional[bool] = None,
1564
+ output_attentions: Optional[bool] = None,
1565
+ output_hidden_states: Optional[bool] = None,
1566
+ output_router_logits: Optional[bool] = None,
1567
+ return_dict: Optional[bool] = None,
1568
+ return_all_heads: Optional[bool] = False,
1569
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1570
+ output_attentions = (
1571
+ output_attentions
1572
+ if output_attentions is not None
1573
+ else self.config.output_attentions
1574
+ )
1575
+ output_router_logits = (
1576
+ output_router_logits
1577
+ if output_router_logits is not None
1578
+ else self.config.output_router_logits
1579
+ )
1580
+ output_hidden_states = (
1581
+ output_hidden_states
1582
+ if output_hidden_states is not None
1583
+ else self.config.output_hidden_states
1584
+ )
1585
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1586
+
1587
+ return_dict = (
1588
+ return_dict if return_dict is not None else self.config.use_return_dict
1589
+ )
1590
+
1591
+ # retrieve input_ids and inputs_embeds
1592
+ if input_ids is not None and inputs_embeds is not None:
1593
+ raise ValueError(
1594
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1595
+ )
1596
+ elif input_ids is not None:
1597
+ batch_size, seq_length = input_ids.shape[:2]
1598
+ elif inputs_embeds is not None:
1599
+ batch_size, seq_length = inputs_embeds.shape[:2]
1600
+ else:
1601
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1602
+
1603
+ past_key_values_length = 0
1604
+ if use_cache:
1605
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1606
+ if use_legacy_cache:
1607
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1608
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1609
+
1610
+ if position_ids is None:
1611
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1612
+ position_ids = torch.arange(
1613
+ past_key_values_length,
1614
+ seq_length + past_key_values_length,
1615
+ dtype=torch.long,
1616
+ device=device,
1617
+ )
1618
+ position_ids = position_ids.unsqueeze(0)
1619
+
1620
+ if inputs_embeds is None:
1621
+ inputs_embeds = self.embed_tokens(input_ids)
1622
+
1623
+ if self._use_flash_attention_2:
1624
+ # 2d mask is passed through the layers
1625
+ attention_mask = (
1626
+ attention_mask
1627
+ if (attention_mask is not None and 0 in attention_mask)
1628
+ else None
1629
+ )
1630
+ else:
1631
+ # 4d mask is passed through the layers
1632
+ attention_mask = _prepare_4d_causal_attention_mask(
1633
+ attention_mask,
1634
+ (batch_size, seq_length),
1635
+ inputs_embeds,
1636
+ past_key_values_length,
1637
+ )
1638
+
1639
+ # embed positions
1640
+ hidden_states = inputs_embeds
1641
+
1642
+ # decoder layers
1643
+ all_hidden_states = () if output_hidden_states or return_all_heads else None
1644
+ all_self_attns = () if output_attentions else None
1645
+ all_router_logits = () if output_router_logits else None
1646
+ next_decoder_cache = None
1647
+
1648
+ # layers = self.layers if not return_all_heads else self.layers + self.extra_heads
1649
+ for decoder_layer in self.layers:
1650
+ if output_hidden_states:
1651
+ all_hidden_states += (hidden_states,)
1652
+
1653
+ layer_outputs = decoder_layer(
1654
+ hidden_states,
1655
+ attention_mask=attention_mask,
1656
+ position_ids=position_ids,
1657
+ past_key_value=past_key_values,
1658
+ output_attentions=output_attentions,
1659
+ output_router_logits=output_router_logits,
1660
+ use_cache=use_cache,
1661
+ )
1662
+
1663
+ hidden_states = layer_outputs[0]
1664
+
1665
+ if use_cache:
1666
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1667
+
1668
+ if output_attentions:
1669
+ all_self_attns += (layer_outputs[1],)
1670
+
1671
+ if output_router_logits and layer_outputs[-1] is not None:
1672
+ all_router_logits += (layer_outputs[-1],)
1673
+
1674
+ # Multi-token prediction
1675
+ if return_all_heads:
1676
+ first_token_hidden_state = self.norm(hidden_states) # first next token prediction
1677
+
1678
+ all_hidden_states += (first_token_hidden_state,)
1679
+
1680
+ for extra_head_idx in range(len(self.extra_heads)):
1681
+ hidden_states = torch.cat(
1682
+ (self.extra_heads_input_norms[extra_head_idx](inputs_embeds),
1683
+ self.extra_heads_hidden_norms[extra_head_idx](hidden_states)),
1684
+ dim=-1
1685
+ ) # (bsz, seq_len, dim*2)
1686
+
1687
+ hidden_states = self.extra_heads_projections[extra_head_idx](hidden_states)
1688
+ # (bsz, seq_len, dim)
1689
+
1690
+ layer_outputs = self.extra_heads[extra_head_idx](
1691
+ hidden_states,
1692
+ attention_mask=attention_mask,
1693
+ position_ids=position_ids,
1694
+ past_key_value=past_key_values,
1695
+ output_attentions=output_attentions,
1696
+ use_cache=use_cache,
1697
+ )
1698
+
1699
+ hidden_states = layer_outputs[0]
1700
+
1701
+ if use_cache:
1702
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1703
+
1704
+ if output_attentions:
1705
+ all_self_attns += (layer_outputs[1],)
1706
+
1707
+ # always return extra_head hidden_states with norm
1708
+ all_hidden_states += (self.norm(hidden_states),)
1709
+
1710
+ hidden_states = first_token_hidden_state
1711
+
1712
+ else:
1713
+ hidden_states = self.norm(hidden_states)
1714
+
1715
+ # add hidden states from the last decoder layer
1716
+ if output_hidden_states:
1717
+ all_hidden_states += (hidden_states,)
1718
+
1719
+ next_cache = None
1720
+ if use_cache:
1721
+ next_cache = (
1722
+ next_decoder_cache.to_legacy_cache()
1723
+ if use_legacy_cache
1724
+ else next_decoder_cache
1725
+ )
1726
+ if not return_dict:
1727
+ return tuple(
1728
+ v
1729
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1730
+ if v is not None
1731
+ )
1732
+ return MoeModelOutputWithPast(
1733
+ last_hidden_state=hidden_states,
1734
+ past_key_values=next_cache,
1735
+ hidden_states=all_hidden_states,
1736
+ attentions=all_self_attns,
1737
+ router_logits=all_router_logits
1738
+ )
1739
+
1740
+
1741
+ class TinyDeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1742
+ _tied_weights_keys = ["lm_head.weight"]
1743
+
1744
+ def __init__(self, config):
1745
+ super().__init__(config)
1746
+ self.model = TinyDeepseekV3Model(config)
1747
+ self.vocab_size = config.vocab_size
1748
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1749
+ self.n_future_tokens = config.n_future_tokens
1750
+ self.mtp_loss_lambda = config.mtp_loss_lambda
1751
+
1752
+ self.seq_aux = config.seq_aux
1753
+ self.aux_loss_alpha = config.aux_loss_alpha
1754
+ self.n_routed_experts = config.n_routed_experts
1755
+ self.num_experts_per_tok = config.num_experts_per_tok
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ output_router_logits: Optional[bool] = None,
1794
+ return_dict: Optional[bool] = None,
1795
+ return_all_heads: Optional[bool] = False,
1796
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1797
+ r"""
1798
+ Args:
1799
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1800
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1801
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1802
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1803
+
1804
+ Returns:
1805
+
1806
+ Example:
1807
+
1808
+ ```python
1809
+ >>> from transformers import AutoTokenizer, TinyDeepseekV3ForCausalLM
1810
+
1811
+ >>> model = TinyDeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1812
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1813
+
1814
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1815
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1816
+
1817
+ >>> # Generate
1818
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1819
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1820
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1821
+ ```"""
1822
+ output_attentions = (
1823
+ output_attentions
1824
+ if output_attentions is not None
1825
+ else self.config.output_attentions
1826
+ )
1827
+ output_router_logits = (
1828
+ output_router_logits
1829
+ if output_router_logits is not None
1830
+ else self.config.output_router_logits
1831
+ )
1832
+ output_hidden_states = (
1833
+ output_hidden_states
1834
+ if output_hidden_states is not None
1835
+ else self.config.output_hidden_states
1836
+ )
1837
+ return_dict = (
1838
+ return_dict if return_dict is not None else self.config.use_return_dict
1839
+ )
1840
+
1841
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1842
+ outputs = self.model(
1843
+ input_ids=input_ids,
1844
+ attention_mask=attention_mask,
1845
+ position_ids=position_ids,
1846
+ past_key_values=past_key_values,
1847
+ inputs_embeds=inputs_embeds,
1848
+ use_cache=use_cache,
1849
+ output_attentions=output_attentions,
1850
+ output_hidden_states=output_hidden_states,
1851
+ output_router_logits=output_router_logits or self.seq_aux,
1852
+ return_dict=return_dict,
1853
+ return_all_heads=return_all_heads,
1854
+ )
1855
+
1856
+ if not return_all_heads:
1857
+ hidden_states = outputs[0]
1858
+ logits = self.lm_head(hidden_states)
1859
+ logits = logits.float()
1860
+
1861
+ loss = None
1862
+ if labels is not None:
1863
+ # Shift so that tokens < n predict n
1864
+ shift_logits = logits[..., :-1, :].contiguous()
1865
+ shift_labels = labels[..., 1:].contiguous()
1866
+ # Flatten the tokens
1867
+ loss_fct = CrossEntropyLoss()
1868
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1869
+ shift_labels = shift_labels.view(-1)
1870
+ # Enable model parallelism
1871
+ shift_labels = shift_labels.to(shift_logits.device)
1872
+ loss = loss_fct(shift_logits, shift_labels)
1873
+ else:
1874
+ # Multi-token prediction
1875
+ mtp_hidden_states = outputs[2][-self.n_future_tokens:]
1876
+ first_token_loss = None
1877
+ mtp_loss = None
1878
+ loss = None
1879
+
1880
+ add_loss = lambda x, y: y if x is None else x+y
1881
+
1882
+ for token_idx in range(self.n_future_tokens):
1883
+ logits = self.lm_head(mtp_hidden_states[token_idx])
1884
+ logits = logits.float()
1885
+
1886
+ if labels is not None:
1887
+ n_shift = token_idx + 1
1888
+ if n_shift > (logits.shape[1]-1):
1889
+ continue
1890
+
1891
+ # Shift so that tokens < n predict n
1892
+ shift_logits = logits[..., :-n_shift, :].contiguous()
1893
+ shift_labels = labels[..., n_shift:].contiguous()
1894
+ # Flatten the tokens
1895
+ loss_fct = CrossEntropyLoss()
1896
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1897
+ shift_labels = shift_labels.view(-1)
1898
+ # Enable model parallelism
1899
+ shift_labels = shift_labels.to(shift_logits.device)
1900
+
1901
+ loss = add_loss(loss, loss_fct(shift_logits, shift_labels))
1902
+
1903
+ if token_idx == 0:
1904
+ first_token_loss = add_loss(first_token_loss, loss)
1905
+ else:
1906
+ mtp_loss = add_loss(mtp_loss, loss)
1907
+
1908
+ if labels is not None:
1909
+ loss = first_token_loss + self.mtp_loss_lambda * mtp_loss / (self.n_future_tokens - 1)
1910
+ # ljh Loss debug
1911
+ # print(f"loss: {loss} first_token_loss: {first_token_loss}, mtp_loss: {mtp_loss} with n_future_tokens {self.n_future_tokens} and mtp_loss_lambda {self.mtp_loss_lambda}")
1912
+
1913
+
1914
+ # balancing loss
1915
+ aux_loss = None
1916
+ if self.seq_aux:
1917
+ aux_loss = load_balancing_loss_func(
1918
+ gate_logits=outputs.router_logits if return_dict else outputs[-1],
1919
+ num_experts=self.n_routed_experts,
1920
+ top_k=self.num_experts_per_tok,
1921
+ attention_mask=attention_mask,
1922
+ )
1923
+ aux_loss = self.aux_loss_alpha * aux_loss
1924
+ # ljh Loss debug
1925
+ # print(f"loss: {loss}, aux_loss: {aux_loss}")
1926
+ if labels is not None:
1927
+ loss += aux_loss.to(loss.device) # make sure to reside in the same device
1928
+
1929
+ if not return_dict:
1930
+ output = (logits,) + outputs[1:]
1931
+ if output_router_logits:
1932
+ output = (aux_loss,) + output
1933
+ return (loss,) + output if loss is not None else output
1934
+
1935
+ return MoeCausalLMOutputWithPast(
1936
+ loss=loss,
1937
+ logits=logits,
1938
+ past_key_values=outputs.past_key_values,
1939
+ hidden_states=outputs.hidden_states,
1940
+ attentions=outputs.attentions,
1941
+ router_logits=outputs.router_logits
1942
+ )
1943
+
1944
+ def prepare_inputs_for_generation(
1945
+ self,
1946
+ input_ids,
1947
+ past_key_values=None,
1948
+ attention_mask=None,
1949
+ inputs_embeds=None,
1950
+ **kwargs,
1951
+ ):
1952
+ if past_key_values is not None:
1953
+ if isinstance(past_key_values, Cache):
1954
+ cache_length = past_key_values.get_seq_length()
1955
+ past_length = past_key_values.seen_tokens
1956
+ max_cache_length = past_key_values.get_max_length()
1957
+ else:
1958
+ cache_length = past_length = past_key_values[0][0].shape[2]
1959
+ max_cache_length = None
1960
+
1961
+ # Keep only the unprocessed tokens:
1962
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1963
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1964
+ # input)
1965
+ if (
1966
+ attention_mask is not None
1967
+ and attention_mask.shape[1] > input_ids.shape[1]
1968
+ ):
1969
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1970
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1971
+ # input_ids based on the past_length.
1972
+ elif past_length < input_ids.shape[1]:
1973
+ input_ids = input_ids[:, past_length:]
1974
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1975
+
1976
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1977
+ if (
1978
+ max_cache_length is not None
1979
+ and attention_mask is not None
1980
+ and cache_length + input_ids.shape[1] > max_cache_length
1981
+ ):
1982
+ attention_mask = attention_mask[:, -max_cache_length:]
1983
+
1984
+ position_ids = kwargs.get("position_ids", None)
1985
+ if attention_mask is not None and position_ids is None:
1986
+ # create position_ids on the fly for batch generation
1987
+ position_ids = attention_mask.long().cumsum(-1) - 1
1988
+ position_ids.masked_fill_(attention_mask == 0, 1)
1989
+ if past_key_values:
1990
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1991
+
1992
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1993
+ if inputs_embeds is not None and past_key_values is None:
1994
+ model_inputs = {"inputs_embeds": inputs_embeds}
1995
+ else:
1996
+ model_inputs = {"input_ids": input_ids}
1997
+
1998
+ model_inputs.update(
1999
+ {
2000
+ "position_ids": position_ids,
2001
+ "past_key_values": past_key_values,
2002
+ "use_cache": kwargs.get("use_cache"),
2003
+ "attention_mask": attention_mask,
2004
+ }
2005
+ )
2006
+ return model_inputs
2007
+
2008
+ @staticmethod
2009
+ def _reorder_cache(past_key_values, beam_idx):
2010
+ reordered_past = ()
2011
+ for layer_past in past_key_values:
2012
+ reordered_past += (
2013
+ tuple(
2014
+ past_state.index_select(0, beam_idx.to(past_state.device))
2015
+ for past_state in layer_past
2016
+ ),
2017
+ )
2018
+ return reordered_past
2019
+
2020
+
2021
+ @add_start_docstrings(
2022
+ """
2023
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
2024
+
2025
+ [`TinyDeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2026
+ (e.g. GPT-2) do.
2027
+
2028
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2029
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2030
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2031
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2032
+ each row of the batch).
2033
+ """,
2034
+ DeepseekV3_START_DOCSTRING,
2035
+ )
2036
+ class TinyDeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
2037
+ def __init__(self, config):
2038
+ super().__init__(config)
2039
+ self.num_labels = config.num_labels
2040
+ self.model = TinyDeepseekV3Model(config)
2041
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2042
+
2043
+ # Initialize weights and apply final processing
2044
+ self.post_init()
2045
+
2046
+ def get_input_embeddings(self):
2047
+ return self.model.embed_tokens
2048
+
2049
+ def set_input_embeddings(self, value):
2050
+ self.model.embed_tokens = value
2051
+
2052
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
2053
+ def forward(
2054
+ self,
2055
+ input_ids: torch.LongTensor = None,
2056
+ attention_mask: Optional[torch.Tensor] = None,
2057
+ position_ids: Optional[torch.LongTensor] = None,
2058
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2059
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2060
+ labels: Optional[torch.LongTensor] = None,
2061
+ use_cache: Optional[bool] = None,
2062
+ output_attentions: Optional[bool] = None,
2063
+ output_hidden_states: Optional[bool] = None,
2064
+ return_dict: Optional[bool] = None,
2065
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2066
+ r"""
2067
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2068
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2069
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2070
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2071
+ """
2072
+ return_dict = (
2073
+ return_dict if return_dict is not None else self.config.use_return_dict
2074
+ )
2075
+
2076
+ transformer_outputs = self.model(
2077
+ input_ids,
2078
+ attention_mask=attention_mask,
2079
+ position_ids=position_ids,
2080
+ past_key_values=past_key_values,
2081
+ inputs_embeds=inputs_embeds,
2082
+ use_cache=use_cache,
2083
+ output_attentions=output_attentions,
2084
+ output_hidden_states=output_hidden_states,
2085
+ return_dict=return_dict,
2086
+ )
2087
+ hidden_states = transformer_outputs[0]
2088
+ logits = self.score(hidden_states)
2089
+
2090
+ if input_ids is not None:
2091
+ batch_size = input_ids.shape[0]
2092
+ else:
2093
+ batch_size = inputs_embeds.shape[0]
2094
+
2095
+ if self.config.pad_token_id is None and batch_size != 1:
2096
+ raise ValueError(
2097
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2098
+ )
2099
+ if self.config.pad_token_id is None:
2100
+ sequence_lengths = -1
2101
+ else:
2102
+ if input_ids is not None:
2103
+ sequence_lengths = (
2104
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2105
+ ).to(logits.device)
2106
+ else:
2107
+ sequence_lengths = -1
2108
+
2109
+ pooled_logits = logits[
2110
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2111
+ ]
2112
+
2113
+ loss = None
2114
+ if labels is not None:
2115
+ labels = labels.to(logits.device)
2116
+ if self.config.problem_type is None:
2117
+ if self.num_labels == 1:
2118
+ self.config.problem_type = "regression"
2119
+ elif self.num_labels > 1 and (
2120
+ labels.dtype == torch.long or labels.dtype == torch.int
2121
+ ):
2122
+ self.config.problem_type = "single_label_classification"
2123
+ else:
2124
+ self.config.problem_type = "multi_label_classification"
2125
+
2126
+ if self.config.problem_type == "regression":
2127
+ loss_fct = MSELoss()
2128
+ if self.num_labels == 1:
2129
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2130
+ else:
2131
+ loss = loss_fct(pooled_logits, labels)
2132
+ elif self.config.problem_type == "single_label_classification":
2133
+ loss_fct = CrossEntropyLoss()
2134
+ loss = loss_fct(
2135
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2136
+ )
2137
+ elif self.config.problem_type == "multi_label_classification":
2138
+ loss_fct = BCEWithLogitsLoss()
2139
+ loss = loss_fct(pooled_logits, labels)
2140
+ if not return_dict:
2141
+ output = (pooled_logits,) + transformer_outputs[1:]
2142
+ return ((loss,) + output) if loss is not None else output
2143
+
2144
+ return SequenceClassifierOutputWithPast(
2145
+ loss=loss,
2146
+ logits=pooled_logits,
2147
+ past_key_values=transformer_outputs.past_key_values,
2148
+ hidden_states=transformer_outputs.hidden_states,
2149
+ attentions=transformer_outputs.attentions,
2150
+ )
checkpoint-12000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-12000/tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 131072,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{{'<|Assistant|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}"
35
+ }
checkpoint-13000/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyDeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tinydeepseek.TinyDeepseekV3Config",
9
+ "AutoModel": "modeling_tinydeepseek.TinyDeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_tinydeepseek.TinyDeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.0001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4864,
21
+ "kv_lora_rank": 128,
22
+ "lossfreebalance_update_rate": 0.001,
23
+ "max_position_embeddings": 163840,
24
+ "model_type": "tinydeepseek_v3",
25
+ "moe_intermediate_size": 608,
26
+ "moe_layer_freq": 1,
27
+ "mtp_loss_lambda": 0.1,
28
+ "n_future_tokens": 2,
29
+ "n_group": 8,
30
+ "n_routed_experts": 64,
31
+ "n_shared_experts": 2,
32
+ "norm_topk_prob": true,
33
+ "num_attention_heads": 8,
34
+ "num_experts_per_tok": 6,
35
+ "num_hidden_layers": 27,
36
+ "num_key_value_heads": 8,
37
+ "num_nextn_predict_layers": 1,
38
+ "output_router_logits": false,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": null,
41
+ "qk_nope_head_dim": 32,
42
+ "qk_rope_head_dim": 16,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 0.707,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 1.0,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": false,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.48.3",
62
+ "use_cache": true,
63
+ "use_lossfreebalance": false,
64
+ "v_head_dim": 32,
65
+ "vocab_size": 129280
66
+ }
checkpoint-13000/configuration_tinydeepseek.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TinyDeepseekV3Config(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
+ n_future_tokens (int):
104
+ Number of prediction heads in the model (= 1 + `len(extra_heads)`).
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "tinydeepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'aux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.0001,
147
+ seq_aux=True,
148
+ output_router_logits=False,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ n_future_tokens=1,
164
+ mtp_loss_lambda=0.1,
165
+ use_lossfreebalance=True,
166
+ lossfreebalance_update_rate=0.001,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.moe_intermediate_size = moe_intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_nextn_predict_layers = num_nextn_predict_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.n_shared_experts = n_shared_experts
178
+ self.n_routed_experts = n_routed_experts
179
+ self.ep_size = ep_size
180
+ self.routed_scaling_factor = routed_scaling_factor
181
+ self.kv_lora_rank = kv_lora_rank
182
+ self.q_lora_rank = q_lora_rank if q_lora_rank else None
183
+ self.qk_rope_head_dim = qk_rope_head_dim
184
+ self.v_head_dim = v_head_dim
185
+ self.qk_nope_head_dim = qk_nope_head_dim
186
+ self.topk_method = topk_method
187
+ self.n_group = n_group
188
+ self.topk_group = topk_group
189
+ self.num_experts_per_tok = num_experts_per_tok
190
+ self.moe_layer_freq = moe_layer_freq
191
+ self.first_k_dense_replace = first_k_dense_replace
192
+ self.norm_topk_prob = norm_topk_prob
193
+ self.scoring_func = scoring_func
194
+ self.aux_loss_alpha = aux_loss_alpha
195
+ self.seq_aux = seq_aux
196
+ self.output_router_logits = output_router_logits
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.rms_norm_eps = rms_norm_eps
205
+ self.pretraining_tp = pretraining_tp
206
+ self.use_cache = use_cache
207
+ self.rope_theta = rope_theta
208
+ self.rope_scaling = rope_scaling
209
+ self.attention_bias = attention_bias
210
+ self.attention_dropout = attention_dropout
211
+ self.n_future_tokens = n_future_tokens
212
+ self.mtp_loss_lambda = mtp_loss_lambda
213
+ self.use_lossfreebalance = use_lossfreebalance
214
+ self.lossfreebalance_update_rate = lossfreebalance_update_rate
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
checkpoint-13000/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.48.3",
6
+ "use_cache": false
7
+ }
checkpoint-13000/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58da607427a90a7d99b8b6062b79ee9608325e44754ed0666e008beee3a7a886
3
+ size 5000243440
checkpoint-13000/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d262f13d7c0c484197c2cd4e1558f82ddbb848ced2d9e1235f59b992b62dcc0d
3
+ size 1591021104
checkpoint-13000/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-13000/modeling_tinydeepseek.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MoeModelOutputWithPast,
40
+ MoeCausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ # is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_tinydeepseek import TinyDeepseekV3Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ # if not is_torch_greater_or_equal_than_1_13:
70
+ # import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "TinyDeepseekV3Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
94
+ def load_balancing_loss_func(
95
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
96
+ num_experts: Optional[int] = None,
97
+ top_k=2,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ ) -> Union[torch.Tensor, int]:
100
+ r"""
101
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
102
+
103
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
104
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
105
+ experts is too unbalanced.
106
+
107
+ Args:
108
+ gate_logits:
109
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
110
+ shape [batch_size X sequence_length, num_experts].
111
+ num_experts:
112
+ Number of experts
113
+ top_k:
114
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
115
+ parameter.
116
+ attention_mask (`torch.Tensor`, *optional*):
117
+ The attention_mask used in forward function
118
+ shape [batch_size X sequence_length] if not None.
119
+
120
+ Returns:
121
+ The auxiliary loss.
122
+ """
123
+ if gate_logits is None or not isinstance(gate_logits, tuple):
124
+ return 0
125
+
126
+ if isinstance(gate_logits, tuple):
127
+ compute_device = gate_logits[0].device
128
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
129
+
130
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
131
+
132
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
133
+
134
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
135
+
136
+ if attention_mask is None:
137
+ # Compute the percentage of tokens routed to each experts
138
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
139
+
140
+ # Compute the average probability of routing to these experts
141
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
142
+ else:
143
+ batch_size, sequence_length = attention_mask.shape
144
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
145
+
146
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
147
+ expert_attention_mask = (
148
+ attention_mask[None, :, :, None, None]
149
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
150
+ .reshape(-1, top_k, num_experts)
151
+ .to(compute_device)
152
+ )
153
+
154
+ # Compute the percentage of tokens routed to each experts
155
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
156
+ expert_attention_mask, dim=0
157
+ )
158
+
159
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
160
+ router_per_expert_attention_mask = (
161
+ attention_mask[None, :, :, None]
162
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
163
+ .reshape(-1, num_experts)
164
+ .to(compute_device)
165
+ )
166
+
167
+ # Compute the average probability of routing to these experts
168
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
169
+ router_per_expert_attention_mask, dim=0
170
+ )
171
+
172
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
173
+ return overall_loss * num_experts
174
+
175
+
176
+ class DeepseekV3RMSNorm(nn.Module):
177
+ def __init__(self, hidden_size, eps=1e-6):
178
+ """
179
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
180
+ """
181
+ super().__init__()
182
+ self.weight = nn.Parameter(torch.ones(hidden_size))
183
+ self.variance_epsilon = eps
184
+
185
+ def forward(self, hidden_states):
186
+ input_dtype = hidden_states.dtype
187
+ hidden_states = hidden_states.to(torch.float32)
188
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
189
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
190
+ return self.weight * hidden_states.to(input_dtype)
191
+
192
+
193
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
194
+
195
+
196
+ class DeepseekV3RotaryEmbedding(nn.Module):
197
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
198
+ super().__init__()
199
+
200
+ self.dim = dim
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.base = base
203
+ inv_freq = 1.0 / (
204
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
205
+ )
206
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
207
+
208
+ # Build here to make `torch.jit.trace` work.
209
+ self._set_cos_sin_cache(
210
+ seq_len=max_position_embeddings,
211
+ device=self.inv_freq.device,
212
+ dtype=torch.get_default_dtype(),
213
+ )
214
+ self.max_seq_len_cached = None
215
+
216
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
217
+ self.max_seq_len_cached = seq_len
218
+ t = torch.arange(
219
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
220
+ )
221
+
222
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
223
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
224
+ emb = torch.cat((freqs, freqs), dim=-1)
225
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
226
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
227
+
228
+ def forward(self, x, seq_len=None):
229
+ # x: [bs, num_attention_heads, seq_len, head_size]
230
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
231
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
232
+
233
+ return (
234
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
235
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
236
+ )
237
+
238
+
239
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
240
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
241
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ max_position_embeddings=2048,
247
+ base=10000,
248
+ device=None,
249
+ scaling_factor=1.0,
250
+ ):
251
+ self.scaling_factor = scaling_factor
252
+ super().__init__(dim, max_position_embeddings, base, device)
253
+
254
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
255
+ self.max_seq_len_cached = seq_len
256
+ t = torch.arange(
257
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
258
+ )
259
+ t = t / self.scaling_factor
260
+
261
+ freqs = torch.outer(t, self.inv_freq)
262
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
263
+ emb = torch.cat((freqs, freqs), dim=-1)
264
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
265
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
266
+
267
+
268
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
269
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
270
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
271
+
272
+ def __init__(
273
+ self,
274
+ dim,
275
+ max_position_embeddings=2048,
276
+ base=10000,
277
+ device=None,
278
+ scaling_factor=1.0,
279
+ ):
280
+ self.scaling_factor = scaling_factor
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
+
286
+ if seq_len > self.max_position_embeddings:
287
+ base = self.base * (
288
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
289
+ - (self.scaling_factor - 1)
290
+ ) ** (self.dim / (self.dim - 2))
291
+ inv_freq = 1.0 / (
292
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
293
+ )
294
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
295
+
296
+ t = torch.arange(
297
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
298
+ )
299
+
300
+ freqs = torch.outer(t, self.inv_freq)
301
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
302
+ emb = torch.cat((freqs, freqs), dim=-1)
303
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
304
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
305
+
306
+
307
+ # Inverse dim formula to find dim based on number of rotations
308
+ def yarn_find_correction_dim(
309
+ num_rotations, dim, base=10000, max_position_embeddings=2048
310
+ ):
311
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
312
+ 2 * math.log(base)
313
+ )
314
+
315
+
316
+ # Find dim range bounds based on rotations
317
+ def yarn_find_correction_range(
318
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
319
+ ):
320
+ low = math.floor(
321
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
322
+ )
323
+ high = math.ceil(
324
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
325
+ )
326
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
327
+
328
+
329
+ def yarn_get_mscale(scale=1, mscale=1):
330
+ if scale <= 1:
331
+ return 1.0
332
+ return 0.1 * mscale * math.log(scale) + 1.0
333
+
334
+
335
+ def yarn_linear_ramp_mask(min, max, dim):
336
+ if min == max:
337
+ max += 0.001 # Prevent singularity
338
+
339
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
340
+ ramp_func = torch.clamp(linear_func, 0, 1)
341
+ return ramp_func
342
+
343
+
344
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
345
+
346
+ def __init__(
347
+ self,
348
+ dim,
349
+ max_position_embeddings=2048,
350
+ base=10000,
351
+ device=None,
352
+ scaling_factor=1.0,
353
+ original_max_position_embeddings=4096,
354
+ beta_fast=32,
355
+ beta_slow=1,
356
+ mscale=1,
357
+ mscale_all_dim=0,
358
+ ):
359
+ self.scaling_factor = scaling_factor
360
+ self.original_max_position_embeddings = original_max_position_embeddings
361
+ self.beta_fast = beta_fast
362
+ self.beta_slow = beta_slow
363
+ self.mscale = mscale
364
+ self.mscale_all_dim = mscale_all_dim
365
+ super().__init__(dim, max_position_embeddings, base, device)
366
+
367
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
368
+ self.max_seq_len_cached = seq_len
369
+ dim = self.dim
370
+
371
+ freq_extra = 1.0 / (
372
+ self.base
373
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
374
+ )
375
+ freq_inter = 1.0 / (
376
+ self.scaling_factor
377
+ * self.base
378
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
379
+ )
380
+
381
+ low, high = yarn_find_correction_range(
382
+ self.beta_fast,
383
+ self.beta_slow,
384
+ dim,
385
+ self.base,
386
+ self.original_max_position_embeddings,
387
+ )
388
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
389
+ device=device, dtype=torch.float32
390
+ )
391
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
392
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
393
+
394
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
395
+
396
+ freqs = torch.outer(t, inv_freq)
397
+
398
+ _mscale = float(
399
+ yarn_get_mscale(self.scaling_factor, self.mscale)
400
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
401
+ )
402
+
403
+ emb = torch.cat((freqs, freqs), dim=-1)
404
+ self.register_buffer(
405
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
406
+ )
407
+ self.register_buffer(
408
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
409
+ )
410
+
411
+
412
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
413
+ def rotate_half(x):
414
+ """Rotates half the hidden dims of the input."""
415
+ x1 = x[..., : x.shape[-1] // 2]
416
+ x2 = x[..., x.shape[-1] // 2 :]
417
+ return torch.cat((-x2, x1), dim=-1)
418
+
419
+
420
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
421
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
422
+ """Applies Rotary Position Embedding to the query and key tensors.
423
+
424
+ Args:
425
+ q (`torch.Tensor`): The query tensor.
426
+ k (`torch.Tensor`): The key tensor.
427
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
428
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
429
+ position_ids (`torch.Tensor`):
430
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
431
+ used to pass offsetted position ids when working with a KV-cache.
432
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
433
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
434
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
435
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
436
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
437
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
438
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
439
+ Returns:
440
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
441
+ """
442
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
443
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
444
+
445
+ b, h, s, d = q.shape
446
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
447
+
448
+ b, h, s, d = k.shape
449
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
450
+
451
+ q_embed = (q * cos) + (rotate_half(q) * sin)
452
+ k_embed = (k * cos) + (rotate_half(k) * sin)
453
+ return q_embed, k_embed
454
+
455
+
456
+ class DeepseekV3MLP(nn.Module):
457
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
458
+ super().__init__()
459
+ self.config = config
460
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
461
+ self.intermediate_size = (
462
+ config.intermediate_size if intermediate_size is None else intermediate_size
463
+ )
464
+
465
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
466
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
467
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
468
+ self.act_fn = ACT2FN[config.hidden_act]
469
+
470
+ def forward(self, x):
471
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
472
+ return down_proj
473
+
474
+
475
+ class MoEGate(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.config = config
479
+ self.top_k = config.num_experts_per_tok
480
+ self.n_routed_experts = config.n_routed_experts
481
+ self.routed_scaling_factor = config.routed_scaling_factor
482
+ self.scoring_func = config.scoring_func
483
+ self.seq_aux = config.seq_aux
484
+ self.topk_method = config.topk_method
485
+ self.n_group = config.n_group
486
+ self.topk_group = config.topk_group
487
+
488
+ # topk selection algorithm
489
+ self.norm_topk_prob = config.norm_topk_prob
490
+ self.gating_dim = config.hidden_size
491
+ self.weight = nn.Parameter(
492
+ torch.empty((self.n_routed_experts, self.gating_dim))
493
+ )
494
+ if self.topk_method == "noaux_tc":
495
+ self.e_score_correction_bias = nn.Parameter(
496
+ torch.empty((self.n_routed_experts))
497
+ )
498
+ elif self.topk_method == "aux_tc":
499
+ self.update_rate = config.lossfreebalance_update_rate
500
+ self.e_score_correction_bias = nn.Parameter(
501
+ torch.zeros((self.n_routed_experts))
502
+ )
503
+
504
+ self.reset_parameters()
505
+
506
+ def reset_parameters(self) -> None:
507
+ import torch.nn.init as init
508
+
509
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
510
+
511
+ def forward(self, hidden_states):
512
+ bsz, seq_len, h = hidden_states.shape
513
+ ### compute gating score
514
+ hidden_states = hidden_states.view(-1, h)
515
+ logits = F.linear(
516
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
517
+ )
518
+ if self.scoring_func == "sigmoid":
519
+ scores = logits.sigmoid()
520
+ else:
521
+ raise NotImplementedError(
522
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
523
+ )
524
+
525
+ ### select top-k experts
526
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
527
+ group_scores = (
528
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
529
+ ) # [n, n_group]
530
+ group_idx = torch.topk(
531
+ group_scores, k=self.topk_group, dim=-1, sorted=False
532
+ )[
533
+ 1
534
+ ] # [n, top_k_group]
535
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
536
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
537
+ score_mask = (
538
+ group_mask.unsqueeze(-1)
539
+ .expand(
540
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
541
+ )
542
+ .reshape(bsz * seq_len, -1)
543
+ ) # [n, e]
544
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
545
+ _, topk_idx = torch.topk(
546
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
547
+ )
548
+ topk_weight = scores.gather(1, topk_idx)
549
+
550
+ if self.topk_method == "aux_tc":
551
+ expert_counts = torch.bincount(
552
+ topk_idx.flatten(),
553
+ minlength=self.n_routed_experts
554
+ )
555
+
556
+ avg_count = expert_counts.float().mean()
557
+ #max_violation = torch.max(torch.abs(expert_counts.float() - avg_count) / avg_count)
558
+
559
+ # for monitoring the expert-balancing globallu
560
+ # min_violation = torch.min(expert_counts.float()) / avg_count
561
+ # max_violation = torch.max(expert_counts.float()) / avg_count
562
+ # return [min_violation.item(), max_violation.item()]
563
+
564
+ for expert_idx, expert_count in enumerate(expert_counts):
565
+ # b_i = b_i + u + sign(e_i)
566
+ # note: this is \bar{c_i} - c_i, NOT c_i - \bar{c_i}, which will push the network to
567
+ # be maximally unbalanced. Really important to get this part right!!!
568
+ count_error = avg_count - expert_count.float()
569
+ self.e_score_correction_bias.data[expert_idx] += (self.update_rate * torch.sign(count_error))
570
+
571
+ ### norm gate to sum 1
572
+ if self.top_k > 1 and self.norm_topk_prob:
573
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
574
+ topk_weight = topk_weight / denominator
575
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
576
+
577
+ return topk_idx, topk_weight, scores
578
+
579
+ class TinyDeepseekV3MoE(nn.Module):
580
+ """
581
+ A mixed expert module containing shared experts.
582
+ """
583
+
584
+ def __init__(self, config):
585
+ super().__init__()
586
+ self.config = config
587
+ self.num_experts_per_tok = config.num_experts_per_tok
588
+
589
+ if hasattr(config, "ep_size") and config.ep_size > 1:
590
+ assert config.ep_size == dist.get_world_size()
591
+ self.ep_size = config.ep_size
592
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
593
+ self.ep_rank = dist.get_rank()
594
+ self.experts = nn.ModuleList(
595
+ [
596
+ (
597
+ DeepseekV3MLP(
598
+ config, intermediate_size=config.moe_intermediate_size
599
+ )
600
+ if i >= self.ep_rank * self.experts_per_rank
601
+ and i < (self.ep_rank + 1) * self.experts_per_rank
602
+ else None
603
+ )
604
+ for i in range(config.n_routed_experts)
605
+ ]
606
+ )
607
+ else:
608
+ self.ep_size = 1
609
+ self.experts_per_rank = config.n_routed_experts
610
+ self.ep_rank = 0
611
+ self.experts = nn.ModuleList(
612
+ [
613
+ DeepseekV3MLP(
614
+ config, intermediate_size=config.moe_intermediate_size
615
+ )
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV3MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, router_scores = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if not self.training:
633
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
634
+ else:
635
+ # tinydeepseek: moe forward for training
636
+ y = self.moe_train(hidden_states, topk_idx, topk_weight).view(*orig_shape)
637
+ if self.config.n_shared_experts is not None:
638
+ y = y + self.shared_experts(identity)
639
+ return y, router_scores
640
+
641
+ @torch.no_grad()
642
+ def moe_infer(self, x, topk_ids, topk_weight):
643
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
644
+ cnts.scatter_(1, topk_ids, 1)
645
+ tokens_per_expert = cnts.sum(dim=0)
646
+ idxs = topk_ids.view(-1).argsort()
647
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
648
+ sorted_tokens_shape = sorted_tokens.shape
649
+ if self.ep_size > 1:
650
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
651
+ tokens_per_expert_group = tokens_per_expert.new_empty(
652
+ tokens_per_expert.shape[0]
653
+ )
654
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
655
+ output_splits = (
656
+ tokens_per_expert_group.view(self.ep_size, -1)
657
+ .sum(1)
658
+ .cpu()
659
+ .numpy()
660
+ .tolist()
661
+ )
662
+ gathered_tokens = sorted_tokens.new_empty(
663
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
664
+ )
665
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
666
+ dist.all_to_all(
667
+ list(gathered_tokens.split(output_splits)),
668
+ list(sorted_tokens.split(input_split_sizes)),
669
+ )
670
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
671
+ self.ep_size, self.experts_per_rank
672
+ ).sum(dim=0)
673
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
674
+ s = 0
675
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
676
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
677
+ s += k
678
+ gatherd_idxs = gatherd_idxs.argsort()
679
+ sorted_tokens = gathered_tokens[gatherd_idxs]
680
+ tokens_per_expert = tokens_per_expert_post_gather
681
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
682
+
683
+ outputs = []
684
+ start_idx = 0
685
+ for i, num_tokens in enumerate(tokens_per_expert):
686
+ end_idx = start_idx + num_tokens
687
+ if num_tokens == 0:
688
+ continue
689
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
690
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
691
+ expert_out = expert(tokens_for_this_expert)
692
+ outputs.append(expert_out)
693
+ start_idx = end_idx
694
+
695
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
696
+ if self.ep_size > 1:
697
+ new_x = torch.empty_like(outs)
698
+ new_x[gatherd_idxs] = outs
699
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
700
+ dist.all_to_all(
701
+ list(gathered_tokens.split(input_split_sizes)),
702
+ list(new_x.split(output_splits)),
703
+ )
704
+ outs = gathered_tokens
705
+
706
+ new_x = torch.empty_like(outs)
707
+ new_x[idxs] = outs
708
+ final_out = (
709
+ new_x.view(*topk_ids.shape, -1)
710
+ .type(topk_weight.dtype)
711
+ .mul_(topk_weight.unsqueeze(dim=-1))
712
+ .sum(dim=1)
713
+ .type(new_x.dtype)
714
+ )
715
+ return final_out
716
+
717
+
718
+ def moe_train(self, x, topk_ids, topk_weight):
719
+ token_size, hidden_dim = x.shape # token_size = bsz_size * seq_len
720
+ final_hidden_states = torch.zeros(
721
+ (token_size, hidden_dim), dtype=x.dtype, device=x.device
722
+ )
723
+
724
+ # One hot encode the selected experts to create an expert mask
725
+ # this will be used to easily index which expert is going to be sollicitated
726
+ expert_mask = torch.nn.functional.one_hot(topk_ids, num_classes=self.config.n_routed_experts).permute(2, 1, 0)
727
+
728
+ # Loop over all available experts in the model and perform the computation on each expert
729
+ for expert_idx in range(self.config.n_routed_experts):
730
+ expert_layer = self.experts[expert_idx]
731
+ idx, top_x = torch.where(expert_mask[expert_idx])
732
+
733
+ # Index the correct hidden states and compute the expert hidden state for
734
+ # the current expert. We need to make sure to multiply the output hidden
735
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
736
+ current_state = x[None, top_x].reshape(-1, hidden_dim)
737
+ current_hidden_states = expert_layer(current_state) * topk_weight[top_x, idx, None]
738
+
739
+ # However `index_add_` only support torch tensors for indexing so we'll use
740
+ # the `top_x` tensor here.
741
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(x.dtype))
742
+
743
+ return final_hidden_states.view(-1, hidden_dim)
744
+
745
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
746
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
747
+ """
748
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
749
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
750
+ """
751
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
752
+ if n_rep == 1:
753
+ return hidden_states
754
+ hidden_states = hidden_states[:, :, None, :, :].expand(
755
+ batch, num_key_value_heads, n_rep, slen, head_dim
756
+ )
757
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
758
+
759
+
760
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
761
+ class DeepseekV3Attention(nn.Module):
762
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
763
+
764
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: Optional[int] = None):
765
+ super().__init__()
766
+ self.config = config
767
+ self.layer_idx = layer_idx
768
+ if layer_idx is None:
769
+ logger.warning_once(
770
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
771
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
772
+ "when creating this class."
773
+ )
774
+
775
+ self.attention_dropout = config.attention_dropout
776
+ self.hidden_size = config.hidden_size
777
+ self.num_heads = config.num_attention_heads
778
+
779
+ self.max_position_embeddings = config.max_position_embeddings
780
+ self.rope_theta = config.rope_theta
781
+ self.q_lora_rank = config.q_lora_rank
782
+ self.qk_rope_head_dim = config.qk_rope_head_dim
783
+ self.kv_lora_rank = config.kv_lora_rank
784
+ self.v_head_dim = config.v_head_dim
785
+ self.qk_nope_head_dim = config.qk_nope_head_dim
786
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
787
+
788
+ self.is_causal = True
789
+
790
+ if self.q_lora_rank is None:
791
+ self.q_proj = nn.Linear(
792
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
793
+ )
794
+ else:
795
+ self.q_a_proj = nn.Linear(
796
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
797
+ )
798
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
799
+ self.q_b_proj = nn.Linear(
800
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
801
+ )
802
+
803
+ self.kv_a_proj_with_mqa = nn.Linear(
804
+ self.hidden_size,
805
+ config.kv_lora_rank + config.qk_rope_head_dim,
806
+ bias=config.attention_bias,
807
+ )
808
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
809
+ self.kv_b_proj = nn.Linear(
810
+ config.kv_lora_rank,
811
+ self.num_heads
812
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
813
+ bias=False,
814
+ )
815
+
816
+ self.o_proj = nn.Linear(
817
+ self.num_heads * self.v_head_dim,
818
+ self.hidden_size,
819
+ bias=config.attention_bias,
820
+ )
821
+ self._init_rope()
822
+
823
+ self.softmax_scale = self.q_head_dim ** (-0.5)
824
+ if self.config.rope_scaling is not None:
825
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
826
+ scaling_factor = self.config.rope_scaling["factor"]
827
+ if mscale_all_dim:
828
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
829
+ self.softmax_scale = self.softmax_scale * mscale * mscale
830
+
831
+ def _init_rope(self):
832
+ if self.config.rope_scaling is None:
833
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
834
+ self.qk_rope_head_dim,
835
+ max_position_embeddings=self.max_position_embeddings,
836
+ base=self.rope_theta,
837
+ )
838
+ else:
839
+ scaling_type = self.config.rope_scaling["type"]
840
+ scaling_factor = self.config.rope_scaling["factor"]
841
+ if scaling_type == "linear":
842
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
843
+ self.qk_rope_head_dim,
844
+ max_position_embeddings=self.max_position_embeddings,
845
+ scaling_factor=scaling_factor,
846
+ base=self.rope_theta,
847
+ )
848
+ elif scaling_type == "dynamic":
849
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
850
+ self.qk_rope_head_dim,
851
+ max_position_embeddings=self.max_position_embeddings,
852
+ scaling_factor=scaling_factor,
853
+ base=self.rope_theta,
854
+ )
855
+ elif scaling_type == "yarn":
856
+ kwargs = {
857
+ key: self.config.rope_scaling[key]
858
+ for key in [
859
+ "original_max_position_embeddings",
860
+ "beta_fast",
861
+ "beta_slow",
862
+ "mscale",
863
+ "mscale_all_dim",
864
+ ]
865
+ if key in self.config.rope_scaling
866
+ }
867
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
868
+ self.qk_rope_head_dim,
869
+ max_position_embeddings=self.max_position_embeddings,
870
+ scaling_factor=scaling_factor,
871
+ base=self.rope_theta,
872
+ **kwargs,
873
+ )
874
+ else:
875
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
876
+
877
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
878
+ return (
879
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
880
+ .transpose(1, 2)
881
+ .contiguous()
882
+ )
883
+
884
+ def forward(
885
+ self,
886
+ hidden_states: torch.Tensor,
887
+ attention_mask: Optional[torch.Tensor] = None,
888
+ position_ids: Optional[torch.LongTensor] = None,
889
+ past_key_value: Optional[Cache] = None,
890
+ output_attentions: bool = False,
891
+ use_cache: bool = False,
892
+ **kwargs,
893
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
894
+ if "padding_mask" in kwargs:
895
+ warnings.warn(
896
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
897
+ )
898
+ bsz, q_len, _ = hidden_states.size()
899
+
900
+ if self.q_lora_rank is None:
901
+ q = self.q_proj(hidden_states)
902
+ else:
903
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
904
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
905
+ q_nope, q_pe = torch.split(
906
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
907
+ )
908
+
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
+ if past_key_value is not None:
925
+ if self.layer_idx is None:
926
+ raise ValueError(
927
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
928
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
929
+ "with a layer index."
930
+ )
931
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
932
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
933
+
934
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
935
+
936
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
937
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
938
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
939
+
940
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
941
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
942
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
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
+ attn_weights = (
950
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
951
+ )
952
+
953
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
954
+ raise ValueError(
955
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
956
+ f" {attn_weights.size()}"
957
+ )
958
+ assert attention_mask is not None
959
+ if attention_mask is not None:
960
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
961
+ raise ValueError(
962
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
963
+ )
964
+ attn_weights = attn_weights + attention_mask
965
+
966
+ # upcast attention to fp32
967
+ attn_weights = nn.functional.softmax(
968
+ attn_weights, dim=-1, dtype=torch.float32
969
+ ).to(query_states.dtype)
970
+ attn_weights = nn.functional.dropout(
971
+ attn_weights, p=self.attention_dropout, training=self.training
972
+ )
973
+ attn_output = torch.matmul(attn_weights, value_states)
974
+
975
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
976
+ raise ValueError(
977
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
978
+ f" {attn_output.size()}"
979
+ )
980
+
981
+ attn_output = attn_output.transpose(1, 2).contiguous()
982
+
983
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
984
+
985
+ attn_output = self.o_proj(attn_output)
986
+
987
+ if not output_attentions:
988
+ attn_weights = None
989
+
990
+ return attn_output, attn_weights, past_key_value
991
+
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
994
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
995
+ """
996
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
997
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
998
+ flash attention and deal with padding tokens in case the input contains any of them.
999
+ """
1000
+
1001
+ def __init__(self, *args, **kwargs):
1002
+ super().__init__(*args, **kwargs)
1003
+
1004
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1005
+ # 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.
1006
+ # 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).
1007
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1008
+
1009
+ def forward(
1010
+ self,
1011
+ hidden_states: torch.Tensor,
1012
+ attention_mask: Optional[torch.LongTensor] = None,
1013
+ position_ids: Optional[torch.LongTensor] = None,
1014
+ past_key_value: Optional[Cache] = None,
1015
+ output_attentions: bool = False,
1016
+ use_cache: bool = False,
1017
+ **kwargs,
1018
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1019
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1020
+ if "padding_mask" in kwargs:
1021
+ warnings.warn(
1022
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1023
+ )
1024
+
1025
+ # overwrite attention_mask with padding_mask
1026
+ attention_mask = kwargs.pop("padding_mask")
1027
+
1028
+ output_attentions = False
1029
+
1030
+ bsz, q_len, _ = hidden_states.size()
1031
+
1032
+ if self.q_lora_rank is None:
1033
+ q = self.q_proj(hidden_states)
1034
+ else:
1035
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1036
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1037
+ q_nope, q_pe = torch.split(
1038
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1039
+ )
1040
+
1041
+ # Flash attention requires the input to have the shape
1042
+ # batch_size x seq_length x head_dim x hidden_dim
1043
+ # therefore we just need to keep the original shape
1044
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1045
+ compressed_kv, k_pe = torch.split(
1046
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1047
+ )
1048
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1049
+ kv = (
1050
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1051
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1052
+ .transpose(1, 2)
1053
+ )
1054
+
1055
+ k_nope, value_states = torch.split(
1056
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1057
+ )
1058
+ kv_seq_len = value_states.shape[-2]
1059
+
1060
+ kv_seq_len = value_states.shape[-2]
1061
+ if past_key_value is not None:
1062
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1063
+
1064
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1065
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1066
+
1067
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1068
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1069
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1070
+
1071
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1072
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1073
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1074
+
1075
+ if self.q_head_dim != self.v_head_dim:
1076
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1077
+
1078
+ if past_key_value is not None:
1079
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1080
+ key_states, value_states = past_key_value.update(
1081
+ key_states, value_states, self.layer_idx, cache_kwargs
1082
+ )
1083
+
1084
+ # 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
1085
+ # to be able to avoid many of these transpose/reshape/view.
1086
+ query_states = query_states.transpose(1, 2)
1087
+ key_states = key_states.transpose(1, 2)
1088
+ value_states = value_states.transpose(1, 2)
1089
+
1090
+ dropout_rate = self.attention_dropout if self.training else 0.0
1091
+
1092
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1093
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1094
+ # cast them back in the correct dtype just to be sure everything works as expected.
1095
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1096
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1097
+
1098
+ input_dtype = query_states.dtype
1099
+ if input_dtype == torch.float32:
1100
+ # Handle the case where the model is quantized
1101
+ if hasattr(self.config, "_pre_quantization_dtype"):
1102
+ target_dtype = self.config._pre_quantization_dtype
1103
+ elif torch.is_autocast_enabled():
1104
+ target_dtype = torch.get_autocast_gpu_dtype()
1105
+ else:
1106
+ target_dtype = (
1107
+ self.q_proj.weight.dtype
1108
+ if self.q_lora_rank is None
1109
+ else self.q_a_proj.weight.dtype
1110
+ )
1111
+
1112
+ logger.warning_once(
1113
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1114
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1115
+ f" {target_dtype}."
1116
+ )
1117
+
1118
+ query_states = query_states.to(target_dtype)
1119
+ key_states = key_states.to(target_dtype)
1120
+ value_states = value_states.to(target_dtype)
1121
+
1122
+ attn_output = self._flash_attention_forward(
1123
+ query_states,
1124
+ key_states,
1125
+ value_states,
1126
+ attention_mask,
1127
+ q_len,
1128
+ dropout=dropout_rate,
1129
+ softmax_scale=self.softmax_scale,
1130
+ )
1131
+ if self.q_head_dim != self.v_head_dim:
1132
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1133
+
1134
+ attn_output = attn_output.reshape(
1135
+ bsz, q_len, self.num_heads * self.v_head_dim
1136
+ ).contiguous()
1137
+ attn_output = self.o_proj(attn_output)
1138
+
1139
+ if not output_attentions:
1140
+ attn_weights = None
1141
+
1142
+ return attn_output, attn_weights, past_key_value
1143
+
1144
+ def _flash_attention_forward(
1145
+ self,
1146
+ query_states,
1147
+ key_states,
1148
+ value_states,
1149
+ attention_mask,
1150
+ query_length,
1151
+ dropout=0.0,
1152
+ softmax_scale=None,
1153
+ ):
1154
+ """
1155
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1156
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1157
+
1158
+ Args:
1159
+ query_states (`torch.Tensor`):
1160
+ Input query states to be passed to Flash Attention API
1161
+ key_states (`torch.Tensor`):
1162
+ Input key states to be passed to Flash Attention API
1163
+ value_states (`torch.Tensor`):
1164
+ Input value states to be passed to Flash Attention API
1165
+ attention_mask (`torch.Tensor`):
1166
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1167
+ position of padding tokens and 1 for the position of non-padding tokens.
1168
+ dropout (`int`, *optional*):
1169
+ Attention dropout
1170
+ softmax_scale (`float`, *optional*):
1171
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1172
+ """
1173
+ if not self._flash_attn_uses_top_left_mask:
1174
+ causal = self.is_causal
1175
+ else:
1176
+ # 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__.
1177
+ causal = self.is_causal and query_length != 1
1178
+
1179
+ # Contains at least one padding token in the sequence
1180
+ if attention_mask is not None:
1181
+ batch_size = query_states.shape[0]
1182
+ (
1183
+ query_states,
1184
+ key_states,
1185
+ value_states,
1186
+ indices_q,
1187
+ cu_seq_lens,
1188
+ max_seq_lens,
1189
+ ) = self._upad_input(
1190
+ query_states, key_states, value_states, attention_mask, query_length
1191
+ )
1192
+
1193
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1194
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1195
+
1196
+ attn_output_unpad = flash_attn_varlen_func(
1197
+ query_states,
1198
+ key_states,
1199
+ value_states,
1200
+ cu_seqlens_q=cu_seqlens_q,
1201
+ cu_seqlens_k=cu_seqlens_k,
1202
+ max_seqlen_q=max_seqlen_in_batch_q,
1203
+ max_seqlen_k=max_seqlen_in_batch_k,
1204
+ dropout_p=dropout,
1205
+ softmax_scale=softmax_scale,
1206
+ causal=causal,
1207
+ )
1208
+
1209
+ attn_output = pad_input(
1210
+ attn_output_unpad, indices_q, batch_size, query_length
1211
+ )
1212
+ else:
1213
+ attn_output = flash_attn_func(
1214
+ query_states,
1215
+ key_states,
1216
+ value_states,
1217
+ dropout,
1218
+ softmax_scale=softmax_scale,
1219
+ causal=causal,
1220
+ )
1221
+
1222
+ return attn_output
1223
+
1224
+ def _upad_input(
1225
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1226
+ ):
1227
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1228
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1229
+
1230
+ key_layer = index_first_axis(
1231
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1232
+ indices_k,
1233
+ )
1234
+ value_layer = index_first_axis(
1235
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1236
+ indices_k,
1237
+ )
1238
+ if query_length == kv_seq_len:
1239
+ query_layer = index_first_axis(
1240
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1241
+ indices_k,
1242
+ )
1243
+ cu_seqlens_q = cu_seqlens_k
1244
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1245
+ indices_q = indices_k
1246
+ elif query_length == 1:
1247
+ max_seqlen_in_batch_q = 1
1248
+ cu_seqlens_q = torch.arange(
1249
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1250
+ ) # There is a memcpy here, that is very bad.
1251
+ indices_q = cu_seqlens_q[:-1]
1252
+ query_layer = query_layer.squeeze(1)
1253
+ else:
1254
+ # The -q_len: slice assumes left padding.
1255
+ attention_mask = attention_mask[:, -query_length:]
1256
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1257
+ query_layer, attention_mask
1258
+ )
1259
+
1260
+ return (
1261
+ query_layer,
1262
+ key_layer,
1263
+ value_layer,
1264
+ indices_q,
1265
+ (cu_seqlens_q, cu_seqlens_k),
1266
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1267
+ )
1268
+
1269
+
1270
+ ATTENTION_CLASSES = {
1271
+ "eager": DeepseekV3Attention,
1272
+ "flash_attention_2": DeepseekV3FlashAttention2,
1273
+ }
1274
+
1275
+
1276
+ class DeepseekV3DecoderLayer(nn.Module):
1277
+ def __init__(self, config: TinyDeepseekV3Config, layer_idx: int):
1278
+ super().__init__()
1279
+ self.hidden_size = config.hidden_size
1280
+
1281
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1282
+ config=config, layer_idx=layer_idx
1283
+ )
1284
+
1285
+ self.mlp = (
1286
+ TinyDeepseekV3MoE(config)
1287
+ if (
1288
+ config.n_routed_experts is not None
1289
+ and layer_idx >= config.first_k_dense_replace
1290
+ and layer_idx % config.moe_layer_freq == 0
1291
+ )
1292
+ else DeepseekV3MLP(config)
1293
+ )
1294
+ self.input_layernorm = DeepseekV3RMSNorm(
1295
+ config.hidden_size, eps=config.rms_norm_eps
1296
+ )
1297
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1298
+ config.hidden_size, eps=config.rms_norm_eps
1299
+ )
1300
+
1301
+ def forward(
1302
+ self,
1303
+ hidden_states: torch.Tensor,
1304
+ attention_mask: Optional[torch.Tensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1307
+ output_attentions: Optional[bool] = False,
1308
+ output_router_logits: Optional[bool] = False,
1309
+ use_cache: Optional[bool] = False,
1310
+ **kwargs,
1311
+ ) -> Tuple[
1312
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1313
+ ]:
1314
+ """
1315
+ Args:
1316
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1317
+ attention_mask (`torch.FloatTensor`, *optional*):
1318
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1319
+ query_sequence_length, key_sequence_length)` if default attention is used.
1320
+ output_attentions (`bool`, *optional*):
1321
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1322
+ returned tensors for more detail.
1323
+ use_cache (`bool`, *optional*):
1324
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1325
+ (see `past_key_values`).
1326
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1327
+ """
1328
+ if "padding_mask" in kwargs:
1329
+ warnings.warn(
1330
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1331
+ )
1332
+ residual = hidden_states
1333
+
1334
+ hidden_states = self.input_layernorm(hidden_states)
1335
+
1336
+ # Self Attention
1337
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1338
+ hidden_states=hidden_states,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_value=past_key_value,
1342
+ output_attentions=output_attentions,
1343
+ use_cache=use_cache,
1344
+ **kwargs,
1345
+ )
1346
+ hidden_states = residual + hidden_states
1347
+
1348
+ # Fully Connected
1349
+ residual = hidden_states
1350
+ hidden_states = self.post_attention_layernorm(hidden_states)
1351
+ hidden_states = self.mlp(hidden_states)
1352
+ if isinstance(hidden_states, tuple):
1353
+ hidden_states, router_scores = hidden_states
1354
+ else:
1355
+ router_scores = None
1356
+ hidden_states = residual + hidden_states
1357
+
1358
+ outputs = (hidden_states,)
1359
+
1360
+ if output_attentions:
1361
+ outputs += (self_attn_weights,)
1362
+
1363
+ if use_cache:
1364
+ outputs += (present_key_value,)
1365
+
1366
+ if output_router_logits:
1367
+ outputs += (router_scores, )
1368
+
1369
+ return outputs
1370
+
1371
+
1372
+ DeepseekV3_START_DOCSTRING = r"""
1373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1375
+ etc.)
1376
+
1377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1379
+ and behavior.
1380
+
1381
+ Parameters:
1382
+ config ([`TinyDeepseekV3Config`]):
1383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1384
+ load the weights associated with the model, only the configuration. Check out the
1385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1386
+ """
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1391
+ DeepseekV3_START_DOCSTRING,
1392
+ )
1393
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1394
+ config_class = TinyDeepseekV3Config
1395
+ base_model_prefix = "model"
1396
+ supports_gradient_checkpointing = True
1397
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1398
+ _skip_keys_device_placement = "past_key_values"
1399
+ _supports_flash_attn_2 = True
1400
+ _supports_cache_class = True
1401
+
1402
+ def _init_weights(self, module):
1403
+ std = self.config.initializer_range
1404
+ if isinstance(module, nn.Linear):
1405
+ module.weight.data.normal_(mean=0.0, std=std)
1406
+ if module.bias is not None:
1407
+ module.bias.data.zero_()
1408
+ elif isinstance(module, nn.Embedding):
1409
+ module.weight.data.normal_(mean=0.0, std=std)
1410
+ if module.padding_idx is not None:
1411
+ module.weight.data[module.padding_idx].zero_()
1412
+
1413
+
1414
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1415
+ Args:
1416
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1417
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1418
+ it.
1419
+
1420
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1421
+ [`PreTrainedTokenizer.__call__`] for details.
1422
+
1423
+ [What are input IDs?](../glossary#input-ids)
1424
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1425
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1426
+
1427
+ - 1 for tokens that are **not masked**,
1428
+ - 0 for tokens that are **masked**.
1429
+
1430
+ [What are attention masks?](../glossary#attention-mask)
1431
+
1432
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1433
+ [`PreTrainedTokenizer.__call__`] for details.
1434
+
1435
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1436
+ `past_key_values`).
1437
+
1438
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1439
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1440
+ information on the default strategy.
1441
+
1442
+ - 1 indicates the head is **not masked**,
1443
+ - 0 indicates the head is **masked**.
1444
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1446
+ config.n_positions - 1]`.
1447
+
1448
+ [What are position IDs?](../glossary#position-ids)
1449
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1450
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1451
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1452
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1453
+
1454
+ Two formats are allowed:
1455
+ - a [`~cache_utils.Cache`] instance;
1456
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1457
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1458
+ cache format.
1459
+
1460
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1461
+ legacy cache format will be returned.
1462
+
1463
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1464
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1465
+ of shape `(batch_size, sequence_length)`.
1466
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1467
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1468
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1469
+ model's internal embedding lookup matrix.
1470
+ use_cache (`bool`, *optional*):
1471
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1472
+ `past_key_values`).
1473
+ output_attentions (`bool`, *optional*):
1474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1475
+ tensors for more detail.
1476
+ output_hidden_states (`bool`, *optional*):
1477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1478
+ more detail.
1479
+ return_dict (`bool`, *optional*):
1480
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1481
+ """
1482
+
1483
+
1484
+ @add_start_docstrings(
1485
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1486
+ DeepseekV3_START_DOCSTRING,
1487
+ )
1488
+ class TinyDeepseekV3Model(DeepseekV3PreTrainedModel):
1489
+ """
1490
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1491
+
1492
+ Args:
1493
+ config: TinyDeepseekV3Config
1494
+ """
1495
+
1496
+ def __init__(self, config: TinyDeepseekV3Config):
1497
+ super().__init__(config)
1498
+ self.padding_idx = config.pad_token_id
1499
+ self.vocab_size = config.vocab_size
1500
+
1501
+ self.n_future_tokens = config.n_future_tokens
1502
+ assert self.n_future_tokens > 0, "At least one future token prediction needed, i.e., n_future_tokens>0"
1503
+ assert config.num_hidden_layers > self.n_future_tokens, "The number of layer should larger than the n_future_tokens, i.e., config.num_hidden_layers > config.n_future_tokens"
1504
+
1505
+ self.embed_tokens = nn.Embedding(
1506
+ config.vocab_size, config.hidden_size, self.padding_idx
1507
+ )
1508
+ self.layers = nn.ModuleList(
1509
+ [
1510
+ DeepseekV3DecoderLayer(config, layer_idx)
1511
+ for layer_idx in range(config.num_hidden_layers - self.n_future_tokens + 1)
1512
+ ]
1513
+ )
1514
+
1515
+ # Additional prediction heads for multi-token prediction.
1516
+ # `layer_id` counts contiguously from the first Transformer block.
1517
+ self.extra_heads = nn.ModuleList(
1518
+ [
1519
+ DeepseekV3DecoderLayer(config, len(self.layers) + layer_idx)
1520
+ for layer_idx in range(self.n_future_tokens - 1)
1521
+ ]
1522
+ )
1523
+ self.extra_heads_input_norms = nn.ModuleList(
1524
+ [
1525
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1526
+ for _ in range(self.n_future_tokens - 1)
1527
+ ]
1528
+ )
1529
+ self.extra_heads_hidden_norms = nn.ModuleList(
1530
+ [
1531
+ DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1532
+ for _ in range(self.n_future_tokens - 1)
1533
+ ]
1534
+ )
1535
+ self.extra_heads_projections = nn.ModuleList(
1536
+ [
1537
+ nn.Linear(config.hidden_size*2, config.hidden_size, bias=False)
1538
+ for _ in range(self.n_future_tokens - 1)
1539
+ ]
1540
+ )
1541
+
1542
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1543
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1544
+
1545
+ self.gradient_checkpointing = False
1546
+ # Initialize weights and apply final processing
1547
+ self.post_init()
1548
+
1549
+ def get_input_embeddings(self):
1550
+ return self.embed_tokens
1551
+
1552
+ def set_input_embeddings(self, value):
1553
+ self.embed_tokens = value
1554
+
1555
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1556
+ def forward(
1557
+ self,
1558
+ input_ids: torch.LongTensor = None,
1559
+ attention_mask: Optional[torch.Tensor] = None,
1560
+ position_ids: Optional[torch.LongTensor] = None,
1561
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1562
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1563
+ use_cache: Optional[bool] = None,
1564
+ output_attentions: Optional[bool] = None,
1565
+ output_hidden_states: Optional[bool] = None,
1566
+ output_router_logits: Optional[bool] = None,
1567
+ return_dict: Optional[bool] = None,
1568
+ return_all_heads: Optional[bool] = False,
1569
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1570
+ output_attentions = (
1571
+ output_attentions
1572
+ if output_attentions is not None
1573
+ else self.config.output_attentions
1574
+ )
1575
+ output_router_logits = (
1576
+ output_router_logits
1577
+ if output_router_logits is not None
1578
+ else self.config.output_router_logits
1579
+ )
1580
+ output_hidden_states = (
1581
+ output_hidden_states
1582
+ if output_hidden_states is not None
1583
+ else self.config.output_hidden_states
1584
+ )
1585
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1586
+
1587
+ return_dict = (
1588
+ return_dict if return_dict is not None else self.config.use_return_dict
1589
+ )
1590
+
1591
+ # retrieve input_ids and inputs_embeds
1592
+ if input_ids is not None and inputs_embeds is not None:
1593
+ raise ValueError(
1594
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1595
+ )
1596
+ elif input_ids is not None:
1597
+ batch_size, seq_length = input_ids.shape[:2]
1598
+ elif inputs_embeds is not None:
1599
+ batch_size, seq_length = inputs_embeds.shape[:2]
1600
+ else:
1601
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1602
+
1603
+ past_key_values_length = 0
1604
+ if use_cache:
1605
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1606
+ if use_legacy_cache:
1607
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1608
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1609
+
1610
+ if position_ids is None:
1611
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1612
+ position_ids = torch.arange(
1613
+ past_key_values_length,
1614
+ seq_length + past_key_values_length,
1615
+ dtype=torch.long,
1616
+ device=device,
1617
+ )
1618
+ position_ids = position_ids.unsqueeze(0)
1619
+
1620
+ if inputs_embeds is None:
1621
+ inputs_embeds = self.embed_tokens(input_ids)
1622
+
1623
+ if self._use_flash_attention_2:
1624
+ # 2d mask is passed through the layers
1625
+ attention_mask = (
1626
+ attention_mask
1627
+ if (attention_mask is not None and 0 in attention_mask)
1628
+ else None
1629
+ )
1630
+ else:
1631
+ # 4d mask is passed through the layers
1632
+ attention_mask = _prepare_4d_causal_attention_mask(
1633
+ attention_mask,
1634
+ (batch_size, seq_length),
1635
+ inputs_embeds,
1636
+ past_key_values_length,
1637
+ )
1638
+
1639
+ # embed positions
1640
+ hidden_states = inputs_embeds
1641
+
1642
+ # decoder layers
1643
+ all_hidden_states = () if output_hidden_states or return_all_heads else None
1644
+ all_self_attns = () if output_attentions else None
1645
+ all_router_logits = () if output_router_logits else None
1646
+ next_decoder_cache = None
1647
+
1648
+ # layers = self.layers if not return_all_heads else self.layers + self.extra_heads
1649
+ for decoder_layer in self.layers:
1650
+ if output_hidden_states:
1651
+ all_hidden_states += (hidden_states,)
1652
+
1653
+ layer_outputs = decoder_layer(
1654
+ hidden_states,
1655
+ attention_mask=attention_mask,
1656
+ position_ids=position_ids,
1657
+ past_key_value=past_key_values,
1658
+ output_attentions=output_attentions,
1659
+ output_router_logits=output_router_logits,
1660
+ use_cache=use_cache,
1661
+ )
1662
+
1663
+ hidden_states = layer_outputs[0]
1664
+
1665
+ if use_cache:
1666
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1667
+
1668
+ if output_attentions:
1669
+ all_self_attns += (layer_outputs[1],)
1670
+
1671
+ if output_router_logits and layer_outputs[-1] is not None:
1672
+ all_router_logits += (layer_outputs[-1],)
1673
+
1674
+ # Multi-token prediction
1675
+ if return_all_heads:
1676
+ first_token_hidden_state = self.norm(hidden_states) # first next token prediction
1677
+
1678
+ all_hidden_states += (first_token_hidden_state,)
1679
+
1680
+ for extra_head_idx in range(len(self.extra_heads)):
1681
+ hidden_states = torch.cat(
1682
+ (self.extra_heads_input_norms[extra_head_idx](inputs_embeds),
1683
+ self.extra_heads_hidden_norms[extra_head_idx](hidden_states)),
1684
+ dim=-1
1685
+ ) # (bsz, seq_len, dim*2)
1686
+
1687
+ hidden_states = self.extra_heads_projections[extra_head_idx](hidden_states)
1688
+ # (bsz, seq_len, dim)
1689
+
1690
+ layer_outputs = self.extra_heads[extra_head_idx](
1691
+ hidden_states,
1692
+ attention_mask=attention_mask,
1693
+ position_ids=position_ids,
1694
+ past_key_value=past_key_values,
1695
+ output_attentions=output_attentions,
1696
+ use_cache=use_cache,
1697
+ )
1698
+
1699
+ hidden_states = layer_outputs[0]
1700
+
1701
+ if use_cache:
1702
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1703
+
1704
+ if output_attentions:
1705
+ all_self_attns += (layer_outputs[1],)
1706
+
1707
+ # always return extra_head hidden_states with norm
1708
+ all_hidden_states += (self.norm(hidden_states),)
1709
+
1710
+ hidden_states = first_token_hidden_state
1711
+
1712
+ else:
1713
+ hidden_states = self.norm(hidden_states)
1714
+
1715
+ # add hidden states from the last decoder layer
1716
+ if output_hidden_states:
1717
+ all_hidden_states += (hidden_states,)
1718
+
1719
+ next_cache = None
1720
+ if use_cache:
1721
+ next_cache = (
1722
+ next_decoder_cache.to_legacy_cache()
1723
+ if use_legacy_cache
1724
+ else next_decoder_cache
1725
+ )
1726
+ if not return_dict:
1727
+ return tuple(
1728
+ v
1729
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1730
+ if v is not None
1731
+ )
1732
+ return MoeModelOutputWithPast(
1733
+ last_hidden_state=hidden_states,
1734
+ past_key_values=next_cache,
1735
+ hidden_states=all_hidden_states,
1736
+ attentions=all_self_attns,
1737
+ router_logits=all_router_logits
1738
+ )
1739
+
1740
+
1741
+ class TinyDeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1742
+ _tied_weights_keys = ["lm_head.weight"]
1743
+
1744
+ def __init__(self, config):
1745
+ super().__init__(config)
1746
+ self.model = TinyDeepseekV3Model(config)
1747
+ self.vocab_size = config.vocab_size
1748
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1749
+ self.n_future_tokens = config.n_future_tokens
1750
+ self.mtp_loss_lambda = config.mtp_loss_lambda
1751
+
1752
+ self.seq_aux = config.seq_aux
1753
+ self.aux_loss_alpha = config.aux_loss_alpha
1754
+ self.n_routed_experts = config.n_routed_experts
1755
+ self.num_experts_per_tok = config.num_experts_per_tok
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ output_router_logits: Optional[bool] = None,
1794
+ return_dict: Optional[bool] = None,
1795
+ return_all_heads: Optional[bool] = False,
1796
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1797
+ r"""
1798
+ Args:
1799
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1800
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1801
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1802
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1803
+
1804
+ Returns:
1805
+
1806
+ Example:
1807
+
1808
+ ```python
1809
+ >>> from transformers import AutoTokenizer, TinyDeepseekV3ForCausalLM
1810
+
1811
+ >>> model = TinyDeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1812
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1813
+
1814
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1815
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1816
+
1817
+ >>> # Generate
1818
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1819
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1820
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1821
+ ```"""
1822
+ output_attentions = (
1823
+ output_attentions
1824
+ if output_attentions is not None
1825
+ else self.config.output_attentions
1826
+ )
1827
+ output_router_logits = (
1828
+ output_router_logits
1829
+ if output_router_logits is not None
1830
+ else self.config.output_router_logits
1831
+ )
1832
+ output_hidden_states = (
1833
+ output_hidden_states
1834
+ if output_hidden_states is not None
1835
+ else self.config.output_hidden_states
1836
+ )
1837
+ return_dict = (
1838
+ return_dict if return_dict is not None else self.config.use_return_dict
1839
+ )
1840
+
1841
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1842
+ outputs = self.model(
1843
+ input_ids=input_ids,
1844
+ attention_mask=attention_mask,
1845
+ position_ids=position_ids,
1846
+ past_key_values=past_key_values,
1847
+ inputs_embeds=inputs_embeds,
1848
+ use_cache=use_cache,
1849
+ output_attentions=output_attentions,
1850
+ output_hidden_states=output_hidden_states,
1851
+ output_router_logits=output_router_logits or self.seq_aux,
1852
+ return_dict=return_dict,
1853
+ return_all_heads=return_all_heads,
1854
+ )
1855
+
1856
+ if not return_all_heads:
1857
+ hidden_states = outputs[0]
1858
+ logits = self.lm_head(hidden_states)
1859
+ logits = logits.float()
1860
+
1861
+ loss = None
1862
+ if labels is not None:
1863
+ # Shift so that tokens < n predict n
1864
+ shift_logits = logits[..., :-1, :].contiguous()
1865
+ shift_labels = labels[..., 1:].contiguous()
1866
+ # Flatten the tokens
1867
+ loss_fct = CrossEntropyLoss()
1868
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1869
+ shift_labels = shift_labels.view(-1)
1870
+ # Enable model parallelism
1871
+ shift_labels = shift_labels.to(shift_logits.device)
1872
+ loss = loss_fct(shift_logits, shift_labels)
1873
+ else:
1874
+ # Multi-token prediction
1875
+ mtp_hidden_states = outputs[2][-self.n_future_tokens:]
1876
+ first_token_loss = None
1877
+ mtp_loss = None
1878
+ loss = None
1879
+
1880
+ add_loss = lambda x, y: y if x is None else x+y
1881
+
1882
+ for token_idx in range(self.n_future_tokens):
1883
+ logits = self.lm_head(mtp_hidden_states[token_idx])
1884
+ logits = logits.float()
1885
+
1886
+ if labels is not None:
1887
+ n_shift = token_idx + 1
1888
+ if n_shift > (logits.shape[1]-1):
1889
+ continue
1890
+
1891
+ # Shift so that tokens < n predict n
1892
+ shift_logits = logits[..., :-n_shift, :].contiguous()
1893
+ shift_labels = labels[..., n_shift:].contiguous()
1894
+ # Flatten the tokens
1895
+ loss_fct = CrossEntropyLoss()
1896
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1897
+ shift_labels = shift_labels.view(-1)
1898
+ # Enable model parallelism
1899
+ shift_labels = shift_labels.to(shift_logits.device)
1900
+
1901
+ loss = add_loss(loss, loss_fct(shift_logits, shift_labels))
1902
+
1903
+ if token_idx == 0:
1904
+ first_token_loss = add_loss(first_token_loss, loss)
1905
+ else:
1906
+ mtp_loss = add_loss(mtp_loss, loss)
1907
+
1908
+ if labels is not None:
1909
+ loss = first_token_loss + self.mtp_loss_lambda * mtp_loss / (self.n_future_tokens - 1)
1910
+ # ljh Loss debug
1911
+ # print(f"loss: {loss} first_token_loss: {first_token_loss}, mtp_loss: {mtp_loss} with n_future_tokens {self.n_future_tokens} and mtp_loss_lambda {self.mtp_loss_lambda}")
1912
+
1913
+
1914
+ # balancing loss
1915
+ aux_loss = None
1916
+ if self.seq_aux:
1917
+ aux_loss = load_balancing_loss_func(
1918
+ gate_logits=outputs.router_logits if return_dict else outputs[-1],
1919
+ num_experts=self.n_routed_experts,
1920
+ top_k=self.num_experts_per_tok,
1921
+ attention_mask=attention_mask,
1922
+ )
1923
+ aux_loss = self.aux_loss_alpha * aux_loss
1924
+ # ljh Loss debug
1925
+ # print(f"loss: {loss}, aux_loss: {aux_loss}")
1926
+ if labels is not None:
1927
+ loss += aux_loss.to(loss.device) # make sure to reside in the same device
1928
+
1929
+ if not return_dict:
1930
+ output = (logits,) + outputs[1:]
1931
+ if output_router_logits:
1932
+ output = (aux_loss,) + output
1933
+ return (loss,) + output if loss is not None else output
1934
+
1935
+ return MoeCausalLMOutputWithPast(
1936
+ loss=loss,
1937
+ logits=logits,
1938
+ past_key_values=outputs.past_key_values,
1939
+ hidden_states=outputs.hidden_states,
1940
+ attentions=outputs.attentions,
1941
+ router_logits=outputs.router_logits
1942
+ )
1943
+
1944
+ def prepare_inputs_for_generation(
1945
+ self,
1946
+ input_ids,
1947
+ past_key_values=None,
1948
+ attention_mask=None,
1949
+ inputs_embeds=None,
1950
+ **kwargs,
1951
+ ):
1952
+ if past_key_values is not None:
1953
+ if isinstance(past_key_values, Cache):
1954
+ cache_length = past_key_values.get_seq_length()
1955
+ past_length = past_key_values.seen_tokens
1956
+ max_cache_length = past_key_values.get_max_length()
1957
+ else:
1958
+ cache_length = past_length = past_key_values[0][0].shape[2]
1959
+ max_cache_length = None
1960
+
1961
+ # Keep only the unprocessed tokens:
1962
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1963
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1964
+ # input)
1965
+ if (
1966
+ attention_mask is not None
1967
+ and attention_mask.shape[1] > input_ids.shape[1]
1968
+ ):
1969
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1970
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1971
+ # input_ids based on the past_length.
1972
+ elif past_length < input_ids.shape[1]:
1973
+ input_ids = input_ids[:, past_length:]
1974
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1975
+
1976
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1977
+ if (
1978
+ max_cache_length is not None
1979
+ and attention_mask is not None
1980
+ and cache_length + input_ids.shape[1] > max_cache_length
1981
+ ):
1982
+ attention_mask = attention_mask[:, -max_cache_length:]
1983
+
1984
+ position_ids = kwargs.get("position_ids", None)
1985
+ if attention_mask is not None and position_ids is None:
1986
+ # create position_ids on the fly for batch generation
1987
+ position_ids = attention_mask.long().cumsum(-1) - 1
1988
+ position_ids.masked_fill_(attention_mask == 0, 1)
1989
+ if past_key_values:
1990
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1991
+
1992
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1993
+ if inputs_embeds is not None and past_key_values is None:
1994
+ model_inputs = {"inputs_embeds": inputs_embeds}
1995
+ else:
1996
+ model_inputs = {"input_ids": input_ids}
1997
+
1998
+ model_inputs.update(
1999
+ {
2000
+ "position_ids": position_ids,
2001
+ "past_key_values": past_key_values,
2002
+ "use_cache": kwargs.get("use_cache"),
2003
+ "attention_mask": attention_mask,
2004
+ }
2005
+ )
2006
+ return model_inputs
2007
+
2008
+ @staticmethod
2009
+ def _reorder_cache(past_key_values, beam_idx):
2010
+ reordered_past = ()
2011
+ for layer_past in past_key_values:
2012
+ reordered_past += (
2013
+ tuple(
2014
+ past_state.index_select(0, beam_idx.to(past_state.device))
2015
+ for past_state in layer_past
2016
+ ),
2017
+ )
2018
+ return reordered_past
2019
+
2020
+
2021
+ @add_start_docstrings(
2022
+ """
2023
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
2024
+
2025
+ [`TinyDeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2026
+ (e.g. GPT-2) do.
2027
+
2028
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2029
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2030
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2031
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2032
+ each row of the batch).
2033
+ """,
2034
+ DeepseekV3_START_DOCSTRING,
2035
+ )
2036
+ class TinyDeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
2037
+ def __init__(self, config):
2038
+ super().__init__(config)
2039
+ self.num_labels = config.num_labels
2040
+ self.model = TinyDeepseekV3Model(config)
2041
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2042
+
2043
+ # Initialize weights and apply final processing
2044
+ self.post_init()
2045
+
2046
+ def get_input_embeddings(self):
2047
+ return self.model.embed_tokens
2048
+
2049
+ def set_input_embeddings(self, value):
2050
+ self.model.embed_tokens = value
2051
+
2052
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
2053
+ def forward(
2054
+ self,
2055
+ input_ids: torch.LongTensor = None,
2056
+ attention_mask: Optional[torch.Tensor] = None,
2057
+ position_ids: Optional[torch.LongTensor] = None,
2058
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2059
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2060
+ labels: Optional[torch.LongTensor] = None,
2061
+ use_cache: Optional[bool] = None,
2062
+ output_attentions: Optional[bool] = None,
2063
+ output_hidden_states: Optional[bool] = None,
2064
+ return_dict: Optional[bool] = None,
2065
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2066
+ r"""
2067
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2068
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2069
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2070
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2071
+ """
2072
+ return_dict = (
2073
+ return_dict if return_dict is not None else self.config.use_return_dict
2074
+ )
2075
+
2076
+ transformer_outputs = self.model(
2077
+ input_ids,
2078
+ attention_mask=attention_mask,
2079
+ position_ids=position_ids,
2080
+ past_key_values=past_key_values,
2081
+ inputs_embeds=inputs_embeds,
2082
+ use_cache=use_cache,
2083
+ output_attentions=output_attentions,
2084
+ output_hidden_states=output_hidden_states,
2085
+ return_dict=return_dict,
2086
+ )
2087
+ hidden_states = transformer_outputs[0]
2088
+ logits = self.score(hidden_states)
2089
+
2090
+ if input_ids is not None:
2091
+ batch_size = input_ids.shape[0]
2092
+ else:
2093
+ batch_size = inputs_embeds.shape[0]
2094
+
2095
+ if self.config.pad_token_id is None and batch_size != 1:
2096
+ raise ValueError(
2097
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2098
+ )
2099
+ if self.config.pad_token_id is None:
2100
+ sequence_lengths = -1
2101
+ else:
2102
+ if input_ids is not None:
2103
+ sequence_lengths = (
2104
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2105
+ ).to(logits.device)
2106
+ else:
2107
+ sequence_lengths = -1
2108
+
2109
+ pooled_logits = logits[
2110
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2111
+ ]
2112
+
2113
+ loss = None
2114
+ if labels is not None:
2115
+ labels = labels.to(logits.device)
2116
+ if self.config.problem_type is None:
2117
+ if self.num_labels == 1:
2118
+ self.config.problem_type = "regression"
2119
+ elif self.num_labels > 1 and (
2120
+ labels.dtype == torch.long or labels.dtype == torch.int
2121
+ ):
2122
+ self.config.problem_type = "single_label_classification"
2123
+ else:
2124
+ self.config.problem_type = "multi_label_classification"
2125
+
2126
+ if self.config.problem_type == "regression":
2127
+ loss_fct = MSELoss()
2128
+ if self.num_labels == 1:
2129
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2130
+ else:
2131
+ loss = loss_fct(pooled_logits, labels)
2132
+ elif self.config.problem_type == "single_label_classification":
2133
+ loss_fct = CrossEntropyLoss()
2134
+ loss = loss_fct(
2135
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2136
+ )
2137
+ elif self.config.problem_type == "multi_label_classification":
2138
+ loss_fct = BCEWithLogitsLoss()
2139
+ loss = loss_fct(pooled_logits, labels)
2140
+ if not return_dict:
2141
+ output = (pooled_logits,) + transformer_outputs[1:]
2142
+ return ((loss,) + output) if loss is not None else output
2143
+
2144
+ return SequenceClassifierOutputWithPast(
2145
+ loss=loss,
2146
+ logits=pooled_logits,
2147
+ past_key_values=transformer_outputs.past_key_values,
2148
+ hidden_states=transformer_outputs.hidden_states,
2149
+ attentions=transformer_outputs.attentions,
2150
+ )
checkpoint-13000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-13000/tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 131072,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{{'<|Assistant|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}"
35
+ }
checkpoint-14000/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyDeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tinydeepseek.TinyDeepseekV3Config",
9
+ "AutoModel": "modeling_tinydeepseek.TinyDeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_tinydeepseek.TinyDeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.0001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4864,
21
+ "kv_lora_rank": 128,
22
+ "lossfreebalance_update_rate": 0.001,
23
+ "max_position_embeddings": 163840,
24
+ "model_type": "tinydeepseek_v3",
25
+ "moe_intermediate_size": 608,
26
+ "moe_layer_freq": 1,
27
+ "mtp_loss_lambda": 0.1,
28
+ "n_future_tokens": 2,
29
+ "n_group": 8,
30
+ "n_routed_experts": 64,
31
+ "n_shared_experts": 2,
32
+ "norm_topk_prob": true,
33
+ "num_attention_heads": 8,
34
+ "num_experts_per_tok": 6,
35
+ "num_hidden_layers": 27,
36
+ "num_key_value_heads": 8,
37
+ "num_nextn_predict_layers": 1,
38
+ "output_router_logits": false,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": null,
41
+ "qk_nope_head_dim": 32,
42
+ "qk_rope_head_dim": 16,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 0.707,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 1.0,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": false,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.48.3",
62
+ "use_cache": true,
63
+ "use_lossfreebalance": false,
64
+ "v_head_dim": 32,
65
+ "vocab_size": 129280
66
+ }
checkpoint-14000/configuration_tinydeepseek.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TinyDeepseekV3Config(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
+ n_future_tokens (int):
104
+ Number of prediction heads in the model (= 1 + `len(extra_heads)`).
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "tinydeepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'aux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.0001,
147
+ seq_aux=True,
148
+ output_router_logits=False,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ n_future_tokens=1,
164
+ mtp_loss_lambda=0.1,
165
+ use_lossfreebalance=True,
166
+ lossfreebalance_update_rate=0.001,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.moe_intermediate_size = moe_intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_nextn_predict_layers = num_nextn_predict_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.n_shared_experts = n_shared_experts
178
+ self.n_routed_experts = n_routed_experts
179
+ self.ep_size = ep_size
180
+ self.routed_scaling_factor = routed_scaling_factor
181
+ self.kv_lora_rank = kv_lora_rank
182
+ self.q_lora_rank = q_lora_rank if q_lora_rank else None
183
+ self.qk_rope_head_dim = qk_rope_head_dim
184
+ self.v_head_dim = v_head_dim
185
+ self.qk_nope_head_dim = qk_nope_head_dim
186
+ self.topk_method = topk_method
187
+ self.n_group = n_group
188
+ self.topk_group = topk_group
189
+ self.num_experts_per_tok = num_experts_per_tok
190
+ self.moe_layer_freq = moe_layer_freq
191
+ self.first_k_dense_replace = first_k_dense_replace
192
+ self.norm_topk_prob = norm_topk_prob
193
+ self.scoring_func = scoring_func
194
+ self.aux_loss_alpha = aux_loss_alpha
195
+ self.seq_aux = seq_aux
196
+ self.output_router_logits = output_router_logits
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.hidden_act = hidden_act
203
+ self.initializer_range = initializer_range
204
+ self.rms_norm_eps = rms_norm_eps
205
+ self.pretraining_tp = pretraining_tp
206
+ self.use_cache = use_cache
207
+ self.rope_theta = rope_theta
208
+ self.rope_scaling = rope_scaling
209
+ self.attention_bias = attention_bias
210
+ self.attention_dropout = attention_dropout
211
+ self.n_future_tokens = n_future_tokens
212
+ self.mtp_loss_lambda = mtp_loss_lambda
213
+ self.use_lossfreebalance = use_lossfreebalance
214
+ self.lossfreebalance_update_rate = lossfreebalance_update_rate
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
checkpoint-14000/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.48.3",
6
+ "use_cache": false
7
+ }
checkpoint-14000/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c1ca0202ad02951f9453f0381670af6766338a2aee6adc9bc057307e781a98f
3
+ size 5000243440
checkpoint-14000/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:169829e03768fa144608145647ec4046c4be45c6fd51c31e1b2ef70dc3a29a4e
3
+ size 1591021104