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