electric-otter commited on
Commit
378f749
·
verified ·
1 Parent(s): 536e3f3

Create main.py

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