dsdsdsdfffff commited on
Commit
f4238e3
·
verified ·
1 Parent(s): 438b3c0

Upload DeepseekV2ForCausalLM

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