v2ray commited on
Commit
8db1ef8
·
verified ·
1 Parent(s): 987ccc1

Add files using upload-large-folder tool

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