tonyshark commited on
Commit
4d55204
·
verified ·
1 Parent(s): e641dc9

Upload 9 files

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