liushaowei commited on
Commit
2a9a177
·
1 Parent(s): a717331

first commit

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