zjiayu064 nielsr HF Staff commited on
Commit
1735d44
·
0 Parent(s):

BitsMoE model release

Browse files

Co-authored-by: nielsr <nielsr@users.noreply.huggingface.co>

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