Fizzarolli commited on
Commit
6225c28
·
verified ·
1 Parent(s): a5e87cb

Upload folder using huggingface_hub

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