lockon commited on
Commit
4c21016
·
verified ·
1 Parent(s): ab00e0d

Initial commit

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