dsikka commited on
Commit
6e35316
1 Parent(s): a2f1cb5

Upload folder using huggingface_hub

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