Upload folder using huggingface_hub
Browse files- README.md +44 -0
- added_tokens.json +5 -0
- config.json +224 -0
- configuration_dbrx.py +264 -0
- model-00001-of-00014.safetensors +3 -0
- model-00002-of-00014.safetensors +3 -0
- model-00003-of-00014.safetensors +3 -0
- model-00004-of-00014.safetensors +3 -0
- model-00005-of-00014.safetensors +3 -0
- model-00006-of-00014.safetensors +3 -0
- model-00007-of-00014.safetensors +3 -0
- model-00008-of-00014.safetensors +3 -0
- model-00009-of-00014.safetensors +3 -0
- model-00010-of-00014.safetensors +3 -0
- model-00011-of-00014.safetensors +3 -0
- model-00012-of-00014.safetensors +3 -0
- model-00013-of-00014.safetensors +3 -0
- model-00014-of-00014.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_dbrx.py +1482 -0
- special_tokens_map.json +34 -0
- tiktoken.py +374 -0
- tokenizer_config.json +60 -0
README.md
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: other
|
3 |
+
tags:
|
4 |
+
- mlx
|
5 |
+
extra_gated_heading: You need to share contact information with Databricks to access
|
6 |
+
this model
|
7 |
+
extra_gated_prompt: '
|
8 |
+
|
9 |
+
### DBRX Terms of Use
|
10 |
+
|
11 |
+
Use of DBRX is governed by the [Databricks Open Model License](https://www.databricks.com/legal/open-model-license)
|
12 |
+
and the [Databricks Open Model Acceptable Use Policy](https://www.databricks.com/legal/acceptable-use-policy-open-model).'
|
13 |
+
extra_gated_fields:
|
14 |
+
First Name: text
|
15 |
+
Last Name: text
|
16 |
+
Organization: text
|
17 |
+
? By clicking 'Submit' below, I accept the terms of the license and acknowledge
|
18 |
+
that the information I provide will be collected, stored, processed, and shared
|
19 |
+
in accordance with Databricks' Privacy Notice and I understand I can update my
|
20 |
+
preferences at any time
|
21 |
+
: checkbox
|
22 |
+
extra_gated_description: The information you provide will be collected, stored, processed,
|
23 |
+
and shared in accordance with Databricks [Privacy Notice](https://www.databricks.com/legal/privacynotice).
|
24 |
+
extra_gated_button_content: Submit
|
25 |
+
inference: false
|
26 |
+
license_name: databricks-open-model-license
|
27 |
+
license_link: https://www.databricks.com/legal/open-model-license
|
28 |
+
---
|
29 |
+
|
30 |
+
# mlx-community/dbrx-instruct-4bit
|
31 |
+
This model was converted to MLX format from [`databricks/dbrx-instruct`]() using mlx-lm version **0.4.0**.
|
32 |
+
Refer to the [original model card](https://huggingface.co/databricks/dbrx-instruct) for more details on the model.
|
33 |
+
## Use with mlx
|
34 |
+
|
35 |
+
```bash
|
36 |
+
pip install mlx-lm
|
37 |
+
```
|
38 |
+
|
39 |
+
```python
|
40 |
+
from mlx_lm import load, generate
|
41 |
+
|
42 |
+
model, tokenizer = load("mlx-community/dbrx-instruct-4bit")
|
43 |
+
response = generate(model, tokenizer, prompt="hello", verbose=True)
|
44 |
+
```
|
added_tokens.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<|im_end|>": 100279,
|
3 |
+
"<|im_start|>": 100278,
|
4 |
+
"<|pad|>": 100277
|
5 |
+
}
|
config.json
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_cross_attention": false,
|
3 |
+
"architectures": [
|
4 |
+
"DbrxForCausalLM"
|
5 |
+
],
|
6 |
+
"attn_config": {
|
7 |
+
"return_dict": true,
|
8 |
+
"output_hidden_states": false,
|
9 |
+
"output_attentions": false,
|
10 |
+
"torchscript": false,
|
11 |
+
"torch_dtype": null,
|
12 |
+
"use_bfloat16": false,
|
13 |
+
"tf_legacy_loss": false,
|
14 |
+
"pruned_heads": {},
|
15 |
+
"tie_word_embeddings": true,
|
16 |
+
"chunk_size_feed_forward": 0,
|
17 |
+
"is_encoder_decoder": false,
|
18 |
+
"is_decoder": false,
|
19 |
+
"cross_attention_hidden_size": null,
|
20 |
+
"add_cross_attention": false,
|
21 |
+
"tie_encoder_decoder": false,
|
22 |
+
"max_length": 20,
|
23 |
+
"min_length": 0,
|
24 |
+
"do_sample": false,
|
25 |
+
"early_stopping": false,
|
26 |
+
"num_beams": 1,
|
27 |
+
"num_beam_groups": 1,
|
28 |
+
"diversity_penalty": 0.0,
|
29 |
+
"temperature": 1.0,
|
30 |
+
"top_k": 50,
|
31 |
+
"top_p": 1.0,
|
32 |
+
"typical_p": 1.0,
|
33 |
+
"repetition_penalty": 1.0,
|
34 |
+
"length_penalty": 1.0,
|
35 |
+
"no_repeat_ngram_size": 0,
|
36 |
+
"encoder_no_repeat_ngram_size": 0,
|
37 |
+
"bad_words_ids": null,
|
38 |
+
"num_return_sequences": 1,
|
39 |
+
"output_scores": false,
|
40 |
+
"return_dict_in_generate": false,
|
41 |
+
"forced_bos_token_id": null,
|
42 |
+
"forced_eos_token_id": null,
|
43 |
+
"remove_invalid_values": false,
|
44 |
+
"exponential_decay_length_penalty": null,
|
45 |
+
"suppress_tokens": null,
|
46 |
+
"begin_suppress_tokens": null,
|
47 |
+
"architectures": null,
|
48 |
+
"finetuning_task": null,
|
49 |
+
"id2label": {
|
50 |
+
"0": "LABEL_0",
|
51 |
+
"1": "LABEL_1"
|
52 |
+
},
|
53 |
+
"label2id": {
|
54 |
+
"LABEL_0": 0,
|
55 |
+
"LABEL_1": 1
|
56 |
+
},
|
57 |
+
"tokenizer_class": null,
|
58 |
+
"prefix": null,
|
59 |
+
"bos_token_id": null,
|
60 |
+
"pad_token_id": null,
|
61 |
+
"eos_token_id": null,
|
62 |
+
"sep_token_id": null,
|
63 |
+
"decoder_start_token_id": null,
|
64 |
+
"task_specific_params": null,
|
65 |
+
"problem_type": null,
|
66 |
+
"_name_or_path": "",
|
67 |
+
"model_type": "",
|
68 |
+
"attn_pdrop": 0,
|
69 |
+
"clip_qkv": 8,
|
70 |
+
"kv_n_heads": 8,
|
71 |
+
"rope_theta": 500000
|
72 |
+
},
|
73 |
+
"auto_map": {
|
74 |
+
"AutoConfig": "configuration_dbrx.DbrxConfig",
|
75 |
+
"AutoModelForCausalLM": "modeling_dbrx.DbrxForCausalLM"
|
76 |
+
},
|
77 |
+
"bad_words_ids": null,
|
78 |
+
"begin_suppress_tokens": null,
|
79 |
+
"bos_token_id": null,
|
80 |
+
"chunk_size_feed_forward": 0,
|
81 |
+
"cross_attention_hidden_size": null,
|
82 |
+
"d_model": 6144,
|
83 |
+
"decoder_start_token_id": null,
|
84 |
+
"diversity_penalty": 0.0,
|
85 |
+
"do_sample": false,
|
86 |
+
"early_stopping": false,
|
87 |
+
"emb_pdrop": 0.0,
|
88 |
+
"encoder_no_repeat_ngram_size": 0,
|
89 |
+
"eos_token_id": null,
|
90 |
+
"exponential_decay_length_penalty": null,
|
91 |
+
"ffn_config": {
|
92 |
+
"return_dict": true,
|
93 |
+
"output_hidden_states": false,
|
94 |
+
"output_attentions": false,
|
95 |
+
"torchscript": false,
|
96 |
+
"torch_dtype": null,
|
97 |
+
"use_bfloat16": false,
|
98 |
+
"tf_legacy_loss": false,
|
99 |
+
"pruned_heads": {},
|
100 |
+
"tie_word_embeddings": true,
|
101 |
+
"chunk_size_feed_forward": 0,
|
102 |
+
"is_encoder_decoder": false,
|
103 |
+
"is_decoder": false,
|
104 |
+
"cross_attention_hidden_size": null,
|
105 |
+
"add_cross_attention": false,
|
106 |
+
"tie_encoder_decoder": false,
|
107 |
+
"max_length": 20,
|
108 |
+
"min_length": 0,
|
109 |
+
"do_sample": false,
|
110 |
+
"early_stopping": false,
|
111 |
+
"num_beams": 1,
|
112 |
+
"num_beam_groups": 1,
|
113 |
+
"diversity_penalty": 0.0,
|
114 |
+
"temperature": 1.0,
|
115 |
+
"top_k": 50,
|
116 |
+
"top_p": 1.0,
|
117 |
+
"typical_p": 1.0,
|
118 |
+
"repetition_penalty": 1.0,
|
119 |
+
"length_penalty": 1.0,
|
120 |
+
"no_repeat_ngram_size": 0,
|
121 |
+
"encoder_no_repeat_ngram_size": 0,
|
122 |
+
"bad_words_ids": null,
|
123 |
+
"num_return_sequences": 1,
|
124 |
+
"output_scores": false,
|
125 |
+
"return_dict_in_generate": false,
|
126 |
+
"forced_bos_token_id": null,
|
127 |
+
"forced_eos_token_id": null,
|
128 |
+
"remove_invalid_values": false,
|
129 |
+
"exponential_decay_length_penalty": null,
|
130 |
+
"suppress_tokens": null,
|
131 |
+
"begin_suppress_tokens": null,
|
132 |
+
"architectures": null,
|
133 |
+
"finetuning_task": null,
|
134 |
+
"id2label": {
|
135 |
+
"0": "LABEL_0",
|
136 |
+
"1": "LABEL_1"
|
137 |
+
},
|
138 |
+
"label2id": {
|
139 |
+
"LABEL_0": 0,
|
140 |
+
"LABEL_1": 1
|
141 |
+
},
|
142 |
+
"tokenizer_class": null,
|
143 |
+
"prefix": null,
|
144 |
+
"bos_token_id": null,
|
145 |
+
"pad_token_id": null,
|
146 |
+
"eos_token_id": null,
|
147 |
+
"sep_token_id": null,
|
148 |
+
"decoder_start_token_id": null,
|
149 |
+
"task_specific_params": null,
|
150 |
+
"problem_type": null,
|
151 |
+
"_name_or_path": "",
|
152 |
+
"ffn_act_fn": {
|
153 |
+
"name": "silu"
|
154 |
+
},
|
155 |
+
"ffn_hidden_size": 10752,
|
156 |
+
"moe_num_experts": 16,
|
157 |
+
"moe_top_k": 4,
|
158 |
+
"moe_jitter_eps": 0,
|
159 |
+
"moe_loss_weight": 0.05,
|
160 |
+
"moe_normalize_expert_weights": 1,
|
161 |
+
"uniform_expert_assignment": false,
|
162 |
+
"model_type": ""
|
163 |
+
},
|
164 |
+
"finetuning_task": null,
|
165 |
+
"forced_bos_token_id": null,
|
166 |
+
"forced_eos_token_id": null,
|
167 |
+
"id2label": {
|
168 |
+
"0": "LABEL_0",
|
169 |
+
"1": "LABEL_1"
|
170 |
+
},
|
171 |
+
"initializer_range": 0.02,
|
172 |
+
"is_decoder": false,
|
173 |
+
"is_encoder_decoder": false,
|
174 |
+
"label2id": {
|
175 |
+
"LABEL_0": 0,
|
176 |
+
"LABEL_1": 1
|
177 |
+
},
|
178 |
+
"length_penalty": 1.0,
|
179 |
+
"max_length": 20,
|
180 |
+
"max_seq_len": 32768,
|
181 |
+
"min_length": 0,
|
182 |
+
"model_type": "dbrx",
|
183 |
+
"n_heads": 48,
|
184 |
+
"n_layers": 40,
|
185 |
+
"no_repeat_ngram_size": 0,
|
186 |
+
"num_beam_groups": 1,
|
187 |
+
"num_beams": 1,
|
188 |
+
"num_return_sequences": 1,
|
189 |
+
"output_attentions": false,
|
190 |
+
"output_hidden_states": false,
|
191 |
+
"output_router_logits": false,
|
192 |
+
"output_scores": false,
|
193 |
+
"pad_token_id": null,
|
194 |
+
"prefix": null,
|
195 |
+
"problem_type": null,
|
196 |
+
"pruned_heads": {},
|
197 |
+
"quantization": {
|
198 |
+
"group_size": 64,
|
199 |
+
"bits": 4
|
200 |
+
},
|
201 |
+
"remove_invalid_values": false,
|
202 |
+
"repetition_penalty": 1.0,
|
203 |
+
"resid_pdrop": 0.0,
|
204 |
+
"return_dict": true,
|
205 |
+
"return_dict_in_generate": false,
|
206 |
+
"router_aux_loss_coef": 0.05,
|
207 |
+
"sep_token_id": null,
|
208 |
+
"suppress_tokens": null,
|
209 |
+
"task_specific_params": null,
|
210 |
+
"temperature": 1.0,
|
211 |
+
"tf_legacy_loss": false,
|
212 |
+
"tie_encoder_decoder": false,
|
213 |
+
"tie_word_embeddings": false,
|
214 |
+
"tokenizer_class": null,
|
215 |
+
"top_k": 50,
|
216 |
+
"top_p": 1.0,
|
217 |
+
"torch_dtype": "bfloat16",
|
218 |
+
"torchscript": false,
|
219 |
+
"transformers_version": "4.39.2",
|
220 |
+
"typical_p": 1.0,
|
221 |
+
"use_bfloat16": false,
|
222 |
+
"use_cache": true,
|
223 |
+
"vocab_size": 100352
|
224 |
+
}
|
configuration_dbrx.py
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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configuration_utils import PretrainedConfig
|
5 |
+
from transformers.utils import logging
|
6 |
+
|
7 |
+
logger = logging.get_logger(__name__)
|
8 |
+
|
9 |
+
DBRX_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
10 |
+
|
11 |
+
|
12 |
+
class DbrxAttentionConfig(PretrainedConfig):
|
13 |
+
"""Configuration class for Dbrx Attention.
|
14 |
+
|
15 |
+
[`DbrxAttention`] class. It is used to instantiate attention layers
|
16 |
+
according to the specified arguments, defining the layers architecture.
|
17 |
+
|
18 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
19 |
+
documentation from [`PretrainedConfig`] for more information.
|
20 |
+
|
21 |
+
Args:
|
22 |
+
attn_pdrop (`float`, *optional*, defaults to 0.0):
|
23 |
+
The dropout probability for the attention layers.
|
24 |
+
clip_qkv (`float`, *optional*, defualts to None):
|
25 |
+
If not `None`, clip the queries, keys, and values in the attention layer to this value.
|
26 |
+
kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
|
27 |
+
rope_theta (float): The base frequency for rope.
|
28 |
+
"""
|
29 |
+
|
30 |
+
def __init__(
|
31 |
+
self,
|
32 |
+
attn_pdrop: float = 0,
|
33 |
+
clip_qkv: Optional[float] = None,
|
34 |
+
kv_n_heads: int = 1,
|
35 |
+
rope_theta: float = 10000.0,
|
36 |
+
**kwargs: Any,
|
37 |
+
):
|
38 |
+
super().__init__(**kwargs)
|
39 |
+
self.attn_pdrop = attn_pdrop
|
40 |
+
self.clip_qkv = clip_qkv
|
41 |
+
self.kv_n_heads = kv_n_heads
|
42 |
+
self.rope_theta = rope_theta
|
43 |
+
|
44 |
+
for k in ['model_type']:
|
45 |
+
if k in kwargs:
|
46 |
+
kwargs.pop(k)
|
47 |
+
if len(kwargs) != 0:
|
48 |
+
raise ValueError(f'Found unknown {kwargs=}')
|
49 |
+
|
50 |
+
@classmethod
|
51 |
+
def from_pretrained(cls, pretrained_model_name_or_path: str,
|
52 |
+
**kwargs: Any) -> 'PretrainedConfig':
|
53 |
+
cls._set_token_in_kwargs(kwargs)
|
54 |
+
|
55 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path,
|
56 |
+
**kwargs)
|
57 |
+
|
58 |
+
if config_dict.get('model_type') == 'dbrx':
|
59 |
+
config_dict = config_dict['attn_config']
|
60 |
+
|
61 |
+
if 'model_type' in config_dict and hasattr(
|
62 |
+
cls,
|
63 |
+
'model_type') and config_dict['model_type'] != cls.model_type:
|
64 |
+
logger.warning(
|
65 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
66 |
+
+
|
67 |
+
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
|
68 |
+
)
|
69 |
+
|
70 |
+
return cls.from_dict(config_dict, **kwargs)
|
71 |
+
|
72 |
+
|
73 |
+
class DbrxFFNConfig(PretrainedConfig):
|
74 |
+
"""Configuration class for Dbrx FFN.
|
75 |
+
|
76 |
+
[`DbrxFFN`] class. It is used to instantiate feedforward layers according to
|
77 |
+
the specified arguments, defining the layers architecture.
|
78 |
+
|
79 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
80 |
+
documentation from [`PretrainedConfig`] for more information.
|
81 |
+
|
82 |
+
Args:
|
83 |
+
ffn_act_fn (dict, optional): A dict specifying activation function for the FFN.
|
84 |
+
The dict should have a key 'name' with the value being the name of
|
85 |
+
the activation function along with any additional keyword arguments.
|
86 |
+
ffn_hidden_size (int, optional): The hidden size of the feedforward network.
|
87 |
+
moe_num_experts (int, optional): The number of experts in the mixture of experts layer.
|
88 |
+
moe_top_k (int, optional): The number of experts to use in the mixture of experts layer.
|
89 |
+
moe_jitter_eps (float, optional): The jitter epsilon for the mixture of experts layer.
|
90 |
+
moe_loss_weight (float, optional): The loss weight for the mixture of experts layer.
|
91 |
+
moe_normalize_expert_weights (float, optional): The normalization factor for the expert weights.
|
92 |
+
uniform_expert_assignment (bool, optional): Whether to use uniform expert assignment.
|
93 |
+
This should only be used for benchmarking purposes.
|
94 |
+
"""
|
95 |
+
|
96 |
+
def __init__(
|
97 |
+
self,
|
98 |
+
ffn_act_fn: Optional[dict] = None,
|
99 |
+
ffn_hidden_size: int = 3584,
|
100 |
+
moe_num_experts: int = 4,
|
101 |
+
moe_top_k: int = 1,
|
102 |
+
moe_jitter_eps: Optional[float] = None,
|
103 |
+
moe_loss_weight: float = 0.01,
|
104 |
+
moe_normalize_expert_weights: Optional[float] = 1,
|
105 |
+
uniform_expert_assignment: bool = False,
|
106 |
+
**kwargs: Any,
|
107 |
+
):
|
108 |
+
super().__init__()
|
109 |
+
if ffn_act_fn is None:
|
110 |
+
ffn_act_fn = {'name': 'silu'}
|
111 |
+
self.ffn_act_fn = ffn_act_fn
|
112 |
+
self.ffn_hidden_size = ffn_hidden_size
|
113 |
+
self.moe_num_experts = moe_num_experts
|
114 |
+
self.moe_top_k = moe_top_k
|
115 |
+
self.moe_jitter_eps = moe_jitter_eps
|
116 |
+
self.moe_loss_weight = moe_loss_weight
|
117 |
+
self.moe_normalize_expert_weights = moe_normalize_expert_weights
|
118 |
+
self.uniform_expert_assignment = uniform_expert_assignment
|
119 |
+
|
120 |
+
for k in ['model_type']:
|
121 |
+
if k in kwargs:
|
122 |
+
kwargs.pop(k)
|
123 |
+
if len(kwargs) != 0:
|
124 |
+
raise ValueError(f'Found unknown {kwargs=}')
|
125 |
+
|
126 |
+
@classmethod
|
127 |
+
def from_pretrained(cls, pretrained_model_name_or_path: str,
|
128 |
+
**kwargs: Any) -> 'PretrainedConfig':
|
129 |
+
cls._set_token_in_kwargs(kwargs)
|
130 |
+
|
131 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path,
|
132 |
+
**kwargs)
|
133 |
+
|
134 |
+
if config_dict.get('model_type') == 'dbrx':
|
135 |
+
config_dict = config_dict['ffn_config']
|
136 |
+
|
137 |
+
if 'model_type' in config_dict and hasattr(
|
138 |
+
cls,
|
139 |
+
'model_type') and config_dict['model_type'] != cls.model_type:
|
140 |
+
logger.warning(
|
141 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
142 |
+
+
|
143 |
+
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
|
144 |
+
)
|
145 |
+
|
146 |
+
return cls.from_dict(config_dict, **kwargs)
|
147 |
+
|
148 |
+
|
149 |
+
class DbrxConfig(PretrainedConfig):
|
150 |
+
"""Configuration class for Dbrx.
|
151 |
+
|
152 |
+
[`DbrxModel`]. It is used to instantiate a Dbrx model according to the
|
153 |
+
specified arguments, defining the model architecture.
|
154 |
+
|
155 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
156 |
+
documentation from [`PretrainedConfig`] for more information.
|
157 |
+
|
158 |
+
|
159 |
+
Args:
|
160 |
+
d_model (`int`, *optional*, defaults to 6144):
|
161 |
+
Dimensionality of the embeddings and hidden states.
|
162 |
+
n_heads (`int`, *optional*, defaults to 48):
|
163 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
164 |
+
n_layers (`int`, *optional*, defaults to 40):
|
165 |
+
Number of hidden layers in the Transformer encoder.
|
166 |
+
max_seq_len (`int`, *optional*, defaults to 32768):
|
167 |
+
The maximum sequence length of the model.
|
168 |
+
vocab_size (`int`, *optional*, defaults to 100352):
|
169 |
+
Vocabulary size of the Dbrx model. Defines the maximum number of different tokens that can be represented by
|
170 |
+
the `inputs_ids` passed when calling [`DbrxModel`].
|
171 |
+
resid_pdrop (`float`, *optional*, defaults to 0.0):
|
172 |
+
The dropout probability applied to the attention output before combining with residual.
|
173 |
+
emb_pdrop (`float`, *optional*, defaults to 0.0):
|
174 |
+
The dropout probability for the embedding layer.
|
175 |
+
attn_config (`dict`, *optional*):
|
176 |
+
A dictionary used to configure the model's attention module.
|
177 |
+
ffn_config (`dict`, *optional*):
|
178 |
+
A dictionary used to configure the model's FFN module.
|
179 |
+
use_cache (`bool`, *optional*, defaults to `False`):
|
180 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
181 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
182 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
183 |
+
output_router_logits (`bool`, *optional*, defaults to `False`):
|
184 |
+
Whether or not the router logits should be returned by the model. Enabling this will also
|
185 |
+
allow the model to output the auxiliary loss. See [here]() for more details
|
186 |
+
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
|
187 |
+
The aux loss factor for the total loss.
|
188 |
+
|
189 |
+
|
190 |
+
Example:
|
191 |
+
```python
|
192 |
+
>>> from transformers import DbrxConfig, DbrxModel
|
193 |
+
|
194 |
+
>>> # Initializing a Dbrx configuration
|
195 |
+
>>> configuration = DbrxConfig()
|
196 |
+
|
197 |
+
>>> # Initializing a model (with random weights) from the configuration
|
198 |
+
>>> model = DbrxModel(configuration)
|
199 |
+
|
200 |
+
>>> # Accessing the model configuration
|
201 |
+
>>> configuration = model.config
|
202 |
+
```
|
203 |
+
"""
|
204 |
+
|
205 |
+
model_type = 'dbrx'
|
206 |
+
attribute_map = {
|
207 |
+
'num_attention_heads': 'n_heads',
|
208 |
+
'hidden_size': 'd_model',
|
209 |
+
'num_hidden_layers': 'n_layers',
|
210 |
+
'max_position_embeddings': 'max_seq_len'
|
211 |
+
}
|
212 |
+
|
213 |
+
def __init__(
|
214 |
+
self,
|
215 |
+
d_model: int = 2048,
|
216 |
+
n_heads: int = 16,
|
217 |
+
n_layers: int = 24,
|
218 |
+
max_seq_len: int = 2048,
|
219 |
+
vocab_size: int = 32000,
|
220 |
+
resid_pdrop: float = 0.0,
|
221 |
+
emb_pdrop: float = 0.0,
|
222 |
+
attn_config: Optional[DbrxAttentionConfig] = None,
|
223 |
+
ffn_config: Optional[DbrxFFNConfig] = None,
|
224 |
+
use_cache: bool = True,
|
225 |
+
initializer_range: float = 0.02,
|
226 |
+
output_router_logits: bool = False,
|
227 |
+
router_aux_loss_coef: float = 0.05,
|
228 |
+
**kwargs: Any,
|
229 |
+
):
|
230 |
+
if attn_config is None:
|
231 |
+
self.attn_config = DbrxAttentionConfig()
|
232 |
+
elif isinstance(attn_config, dict):
|
233 |
+
self.attn_config = DbrxAttentionConfig(**attn_config)
|
234 |
+
else:
|
235 |
+
self.attn_config = attn_config
|
236 |
+
|
237 |
+
if ffn_config is None:
|
238 |
+
self.ffn_config = DbrxFFNConfig()
|
239 |
+
elif isinstance(ffn_config, dict):
|
240 |
+
self.ffn_config = DbrxFFNConfig(**ffn_config)
|
241 |
+
else:
|
242 |
+
self.ffn_config = ffn_config
|
243 |
+
|
244 |
+
self.d_model = d_model
|
245 |
+
self.n_heads = n_heads
|
246 |
+
self.n_layers = n_layers
|
247 |
+
self.max_seq_len = max_seq_len
|
248 |
+
self.vocab_size = vocab_size
|
249 |
+
self.resid_pdrop = resid_pdrop
|
250 |
+
self.emb_pdrop = emb_pdrop
|
251 |
+
self.use_cache = use_cache
|
252 |
+
self.initializer_range = initializer_range
|
253 |
+
self.output_router_logits = output_router_logits
|
254 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
255 |
+
|
256 |
+
tie_word_embeddings = kwargs.pop('tie_word_embeddings', False)
|
257 |
+
if tie_word_embeddings:
|
258 |
+
raise ValueError(
|
259 |
+
'tie_word_embeddings is not supported for Dbrx models.')
|
260 |
+
|
261 |
+
super().__init__(
|
262 |
+
tie_word_embeddings=tie_word_embeddings,
|
263 |
+
**kwargs,
|
264 |
+
)
|
model-00001-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:74e3abba52e2cc3289d4472d61dd5c1c9132ab228ce7eb9c77b07d5cf6ae0e2d
|
3 |
+
size 5345635839
|
model-00002-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ffcfb2cd951eca6bc01f45d35fe8d487fb53b69b32bd06a53f4087581924055f
|
3 |
+
size 5351178047
|
model-00003-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e915b7448b15bd3710e2f649dc4a3974165ca19ad079c3ce8fd42e8d6e1c5396
|
3 |
+
size 5351178047
|
model-00004-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:24c956bdee13a34bcd8bb96b05589009770c01d99ffe439cf54868b1c9aa76ad
|
3 |
+
size 5351178161
|
model-00005-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df44c153174cd6c7a73d9f1cd75880b7dd565cacb0bcdb0466d31935a2ae245e
|
3 |
+
size 5338711276
|
model-00006-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b1a010fdbe7438a1158881013ec1df81b6be7972d7793fd86b93229d348f8a4f
|
3 |
+
size 5351178496
|
model-00007-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ad3430999aae9e75bbbc5212fbd977ffdcdf18e55936e3c9621b92331827d88e
|
3 |
+
size 5351178502
|
model-00008-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:03fb1abb1494acd9aa93ebd53d672d49b0a3dc949836d2ec30992320cd273934
|
3 |
+
size 5351178492
|
model-00009-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9232f1b76e13f2c4c8594d1ebd626ced719448c46bae752d331880ca712df6a7
|
3 |
+
size 5351178509
|
model-00010-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b8b5bda9fe37bb868c598b6801070efb56dac46896be7c54159e041a251a1e6f
|
3 |
+
size 5351178490
|
model-00011-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:954fbc55f8e457c7f30008575e7466ec4cfddf120b25cd6c2753e3fa37844e00
|
3 |
+
size 5351178506
|
model-00012-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7e9ebd95745e41a852ead8f39a3a31be615cd5e0e7886481fd4d6935ba42f8b4
|
3 |
+
size 5351178506
|
model-00013-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f977c7ebcb688e22fc73f260513a03a41c2642ef04d6f30edb155579999fecd4
|
3 |
+
size 5351178500
|
model-00014-of-00014.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f3f65032b1907188ee64d6e8e7e6b0031aef25751bfcdb614d61ba476c61e1fb
|
3 |
+
size 5363518534
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_dbrx.py
ADDED
@@ -0,0 +1,1482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""PyTorch Dbrx model."""
|
2 |
+
|
3 |
+
import math
|
4 |
+
import warnings
|
5 |
+
from copy import deepcopy
|
6 |
+
from functools import partial
|
7 |
+
from typing import Any, Callable, Dict, Optional, Tuple, Union
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn.functional as F
|
11 |
+
import torch.utils.checkpoint
|
12 |
+
from torch import nn
|
13 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
14 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
15 |
+
from transformers.modeling_outputs import (MoeCausalLMOutputWithPast,
|
16 |
+
MoeModelOutputWithPast)
|
17 |
+
from transformers.modeling_utils import PreTrainedModel
|
18 |
+
from transformers.utils import is_flash_attn_2_available, logging
|
19 |
+
|
20 |
+
from .configuration_dbrx import DbrxAttentionConfig, DbrxConfig, DbrxFFNConfig
|
21 |
+
|
22 |
+
if is_flash_attn_2_available():
|
23 |
+
try:
|
24 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
25 |
+
from flash_attn.bert_padding import pad_input # noqa
|
26 |
+
from flash_attn.bert_padding import index_first_axis, unpad_input
|
27 |
+
except:
|
28 |
+
pass
|
29 |
+
|
30 |
+
logger = logging.get_logger(__name__)
|
31 |
+
|
32 |
+
_CONFIG_FOR_DOC = 'DbrxConfig'
|
33 |
+
|
34 |
+
#############################################################################
|
35 |
+
# Copied from LLaMaRotaryEmbedding
|
36 |
+
#############################################################################
|
37 |
+
|
38 |
+
|
39 |
+
class DbrxRotaryEmbedding(nn.Module):
|
40 |
+
|
41 |
+
def __init__(self,
|
42 |
+
dim: int,
|
43 |
+
max_position_embeddings: int = 2048,
|
44 |
+
base: float = 10000.0,
|
45 |
+
scaling_factor: float = 1.0):
|
46 |
+
super().__init__()
|
47 |
+
self.scaling_factor = scaling_factor
|
48 |
+
self.dim = dim
|
49 |
+
self.max_position_embeddings = max_position_embeddings
|
50 |
+
self.base = base
|
51 |
+
inv_freq = 1.0 / (self.base**(
|
52 |
+
torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
|
53 |
+
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
54 |
+
# For BC we register cos and sin cached
|
55 |
+
self.max_seq_len_cached = max_position_embeddings
|
56 |
+
|
57 |
+
@torch.no_grad()
|
58 |
+
def forward(
|
59 |
+
self, x: torch.Tensor, position_ids: torch.LongTensor
|
60 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
61 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
62 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(
|
63 |
+
position_ids.shape[0], -1, 1)
|
64 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
65 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
66 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
67 |
+
device_type = x.device.type
|
68 |
+
device_type = device_type if isinstance(
|
69 |
+
device_type, str) and device_type != 'mps' else 'cpu'
|
70 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
71 |
+
freqs = (inv_freq_expanded.float()
|
72 |
+
@ position_ids_expanded.float()).transpose(1, 2)
|
73 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
74 |
+
cos = emb.cos()
|
75 |
+
sin = emb.sin()
|
76 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
77 |
+
|
78 |
+
|
79 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
80 |
+
"""Rotates half the hidden dims of the input."""
|
81 |
+
x1 = x[..., :x.shape[-1] // 2]
|
82 |
+
x2 = x[..., x.shape[-1] // 2:]
|
83 |
+
return torch.cat((-x2, x1), dim=-1)
|
84 |
+
|
85 |
+
|
86 |
+
def apply_rotary_pos_emb(
|
87 |
+
q: torch.Tensor,
|
88 |
+
k: torch.Tensor,
|
89 |
+
cos: torch.Tensor,
|
90 |
+
sin: torch.Tensor,
|
91 |
+
unsqueeze_dim: int = 1) -> Tuple[torch.Tensor, torch.Tensor]:
|
92 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
93 |
+
|
94 |
+
Args:
|
95 |
+
q (`torch.Tensor`): The query tensor.
|
96 |
+
k (`torch.Tensor`): The key tensor.
|
97 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
98 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
99 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
100 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos and
|
101 |
+
sin so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
102 |
+
that cos and sin have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
103 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
104 |
+
cos and sin broadcastable to the shapes of q and k. Similarly, if q and k have
|
105 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
106 |
+
|
107 |
+
Returns:
|
108 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
109 |
+
"""
|
110 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
111 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
112 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
113 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
114 |
+
return q_embed, k_embed
|
115 |
+
|
116 |
+
|
117 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
118 |
+
"""Equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep).
|
119 |
+
|
120 |
+
The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to
|
121 |
+
(batch, num_attention_heads, seqlen, head_dim)
|
122 |
+
"""
|
123 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
124 |
+
if n_rep == 1:
|
125 |
+
return hidden_states
|
126 |
+
hidden_states = hidden_states[:, :,
|
127 |
+
None, :, :].expand(batch, num_key_value_heads,
|
128 |
+
n_rep, slen, head_dim)
|
129 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,
|
130 |
+
head_dim)
|
131 |
+
|
132 |
+
|
133 |
+
#############################################################################
|
134 |
+
|
135 |
+
#############################################################################
|
136 |
+
# Modified from modeling_mixtral
|
137 |
+
#############################################################################
|
138 |
+
|
139 |
+
|
140 |
+
def load_balancing_loss_func(
|
141 |
+
gate_logits: torch.Tensor,
|
142 |
+
num_experts: int,
|
143 |
+
top_k: int,
|
144 |
+
attention_mask: Optional[torch.Tensor],
|
145 |
+
) -> torch.Tensor:
|
146 |
+
r"""Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
147 |
+
|
148 |
+
See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
|
149 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
150 |
+
experts is too unbalanced.
|
151 |
+
|
152 |
+
Args:
|
153 |
+
gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
|
154 |
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
155 |
+
shape [batch_size X sequence_length, num_experts].
|
156 |
+
num_experts (`int`):
|
157 |
+
Number of experts.
|
158 |
+
top_k (`int`):
|
159 |
+
The number of experts each token is routed to.
|
160 |
+
attention_mask (`torch.Tensor`, None):
|
161 |
+
The attention_mask used in forward function
|
162 |
+
shape [batch_size X sequence_length] if not None.
|
163 |
+
|
164 |
+
Returns:
|
165 |
+
The auxiliary loss.
|
166 |
+
"""
|
167 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
168 |
+
return torch.tensor(0.0)
|
169 |
+
|
170 |
+
if isinstance(gate_logits, tuple):
|
171 |
+
compute_device = gate_logits[0].device
|
172 |
+
concatenated_gate_logits = torch.cat(
|
173 |
+
[layer_gate.to(compute_device) for layer_gate in gate_logits],
|
174 |
+
dim=0)
|
175 |
+
|
176 |
+
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits,
|
177 |
+
dim=-1)
|
178 |
+
|
179 |
+
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
180 |
+
|
181 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
182 |
+
|
183 |
+
if attention_mask is None:
|
184 |
+
# Compute the percentage of tokens routed to each experts
|
185 |
+
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
186 |
+
|
187 |
+
# Compute the average probability of routing to these experts
|
188 |
+
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
189 |
+
else:
|
190 |
+
batch_size, sequence_length = attention_mask.shape
|
191 |
+
num_hidden_layers = concatenated_gate_logits.shape[0] // (
|
192 |
+
batch_size * sequence_length)
|
193 |
+
|
194 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
195 |
+
expert_attention_mask = (attention_mask[None, :, :, None, None].expand(
|
196 |
+
(num_hidden_layers, batch_size, sequence_length, top_k,
|
197 |
+
num_experts)).reshape(-1, top_k, num_experts).to(compute_device))
|
198 |
+
|
199 |
+
# Compute the percentage of tokens routed to each experts
|
200 |
+
tokens_per_expert = torch.sum(
|
201 |
+
expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
202 |
+
expert_attention_mask, dim=0)
|
203 |
+
|
204 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
205 |
+
router_per_expert_attention_mask = (
|
206 |
+
attention_mask[None, :, :, None].expand(
|
207 |
+
(num_hidden_layers, batch_size, sequence_length,
|
208 |
+
num_experts)).reshape(-1, num_experts).to(compute_device))
|
209 |
+
|
210 |
+
# Compute the average probability of routing to these experts
|
211 |
+
router_prob_per_expert = torch.sum(
|
212 |
+
routing_weights * router_per_expert_attention_mask,
|
213 |
+
dim=0) / torch.sum(router_per_expert_attention_mask, dim=0)
|
214 |
+
|
215 |
+
overall_loss = torch.sum(tokens_per_expert *
|
216 |
+
router_prob_per_expert.unsqueeze(0))
|
217 |
+
return overall_loss * num_experts
|
218 |
+
|
219 |
+
|
220 |
+
#############################################################################
|
221 |
+
|
222 |
+
|
223 |
+
def resolve_ffn_act_fn(
|
224 |
+
ffn_act_fn: dict) -> Callable[[torch.Tensor], torch.Tensor]:
|
225 |
+
"""Resolve the activation function for the feed-forward network.
|
226 |
+
|
227 |
+
Args:
|
228 |
+
ffn_act_fn (dict): The configuration dictionary for the activation function.
|
229 |
+
The dict config must specify the 'name' of a torch.nn.functional activation
|
230 |
+
function. All of other key values pairs are bound to the function as a partial.
|
231 |
+
|
232 |
+
Returns:
|
233 |
+
Callable[[torch.Tensor], torch.Tensor]: The activation function.
|
234 |
+
"""
|
235 |
+
config = deepcopy(ffn_act_fn)
|
236 |
+
name = config.pop('name')
|
237 |
+
if not hasattr(nn.functional, name):
|
238 |
+
raise ValueError(f'Unrecognised activation function name ({name}).')
|
239 |
+
act = getattr(nn.functional, name)
|
240 |
+
return partial(act, **config)
|
241 |
+
|
242 |
+
|
243 |
+
#############################################################################
|
244 |
+
# Copied from LLaMaAttention
|
245 |
+
#############################################################################
|
246 |
+
|
247 |
+
|
248 |
+
def _get_unpad_data(attention_mask: torch.Tensor):
|
249 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
250 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
251 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
252 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32),
|
253 |
+
(1, 0))
|
254 |
+
return (
|
255 |
+
indices,
|
256 |
+
cu_seqlens,
|
257 |
+
max_seqlen_in_batch,
|
258 |
+
)
|
259 |
+
|
260 |
+
|
261 |
+
class DbrxAttention(nn.Module):
|
262 |
+
"""Multi-head self attention."""
|
263 |
+
|
264 |
+
def __init__(self,
|
265 |
+
hidden_size: int,
|
266 |
+
num_heads: int,
|
267 |
+
max_position_embeddings: int,
|
268 |
+
attn_config: DbrxAttentionConfig,
|
269 |
+
block_idx: Optional[int] = None):
|
270 |
+
super().__init__()
|
271 |
+
self.hidden_size = hidden_size
|
272 |
+
self.num_heads = num_heads
|
273 |
+
self.head_dim = self.hidden_size // self.num_heads
|
274 |
+
self.max_position_embeddings = max_position_embeddings
|
275 |
+
self.block_idx = block_idx
|
276 |
+
self.config = attn_config
|
277 |
+
if block_idx is None:
|
278 |
+
logger.warning_once(
|
279 |
+
f'Instantiating {self.__class__.__name__} without passing a `block_idx` is not recommended and will '
|
280 |
+
+
|
281 |
+
'lead to errors during the forward call if caching is used. Please make sure to provide a `block_idx` '
|
282 |
+
+ 'when creating this class.')
|
283 |
+
|
284 |
+
self.attn_pdrop = attn_config.attn_pdrop
|
285 |
+
self.clip_qkv = attn_config.clip_qkv
|
286 |
+
self.num_key_value_heads = attn_config.kv_n_heads
|
287 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
288 |
+
self.rope_theta = attn_config.rope_theta
|
289 |
+
|
290 |
+
self.Wqkv = nn.Linear(self.hidden_size,
|
291 |
+
self.hidden_size +
|
292 |
+
2 * self.num_key_value_heads * self.head_dim,
|
293 |
+
bias=False)
|
294 |
+
self.out_proj = nn.Linear(self.hidden_size,
|
295 |
+
self.hidden_size,
|
296 |
+
bias=False)
|
297 |
+
self.rotary_emb = DbrxRotaryEmbedding(
|
298 |
+
self.head_dim,
|
299 |
+
max_position_embeddings=self.max_position_embeddings,
|
300 |
+
base=self.rope_theta,
|
301 |
+
)
|
302 |
+
|
303 |
+
def forward(
|
304 |
+
self,
|
305 |
+
hidden_states: torch.Tensor,
|
306 |
+
position_ids: torch.LongTensor,
|
307 |
+
attention_mask: Optional[torch.Tensor] = None,
|
308 |
+
past_key_value: Optional[Cache] = None,
|
309 |
+
output_attentions: bool = False,
|
310 |
+
use_cache: bool = False,
|
311 |
+
cache_position: Optional[torch.LongTensor] = None,
|
312 |
+
**kwargs: Any,
|
313 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
314 |
+
bsz, q_len, _ = hidden_states.size()
|
315 |
+
|
316 |
+
qkv_states = self.Wqkv(hidden_states)
|
317 |
+
if self.clip_qkv is not None:
|
318 |
+
qkv_states = qkv_states.clamp(min=-self.clip_qkv, max=self.clip_qkv)
|
319 |
+
|
320 |
+
query_states, key_states, value_states = qkv_states.split(
|
321 |
+
[
|
322 |
+
self.hidden_size,
|
323 |
+
self.num_key_value_heads * self.head_dim,
|
324 |
+
self.num_key_value_heads * self.head_dim,
|
325 |
+
],
|
326 |
+
dim=2,
|
327 |
+
)
|
328 |
+
|
329 |
+
query_states = query_states.view(bsz, q_len, self.num_heads,
|
330 |
+
self.head_dim).transpose(1, 2)
|
331 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads,
|
332 |
+
self.head_dim).transpose(1, 2)
|
333 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads,
|
334 |
+
self.head_dim).transpose(1, 2)
|
335 |
+
|
336 |
+
past_key_value = getattr(self, 'past_key_value', past_key_value)
|
337 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
338 |
+
query_states, key_states = apply_rotary_pos_emb(query_states,
|
339 |
+
key_states, cos, sin)
|
340 |
+
|
341 |
+
if past_key_value is not None:
|
342 |
+
# sin and cos are specific to RoPE models; position_ids needed for the static cache
|
343 |
+
cache_kwargs = {
|
344 |
+
'sin': sin,
|
345 |
+
'cos': cos,
|
346 |
+
'cache_position': cache_position
|
347 |
+
}
|
348 |
+
key_states, value_states = past_key_value.update(
|
349 |
+
key_states, value_states, self.block_idx, cache_kwargs)
|
350 |
+
|
351 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
352 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
353 |
+
|
354 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(
|
355 |
+
2, 3)) / math.sqrt(self.head_dim)
|
356 |
+
|
357 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
358 |
+
causal_mask = attention_mask[:, :, :, :key_states.shape[-2]]
|
359 |
+
attn_weights = attn_weights + causal_mask
|
360 |
+
|
361 |
+
# upcast attention to fp32
|
362 |
+
attn_weights = nn.functional.softmax(attn_weights,
|
363 |
+
dim=-1,
|
364 |
+
dtype=torch.float32).to(
|
365 |
+
query_states.dtype)
|
366 |
+
attn_weights = nn.functional.dropout(attn_weights,
|
367 |
+
p=self.attn_pdrop,
|
368 |
+
training=self.training)
|
369 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
370 |
+
|
371 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
372 |
+
raise ValueError(
|
373 |
+
f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
|
374 |
+
+ f' {attn_output.size()}')
|
375 |
+
|
376 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
377 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
378 |
+
attn_output = self.out_proj(attn_output)
|
379 |
+
|
380 |
+
if not output_attentions:
|
381 |
+
attn_weights = None
|
382 |
+
|
383 |
+
return attn_output, attn_weights, past_key_value
|
384 |
+
|
385 |
+
|
386 |
+
class DbrxFlashAttention2(DbrxAttention):
|
387 |
+
"""Dbrx flash attention module.
|
388 |
+
|
389 |
+
This module inherits from `DbrxAttention` as the weights of the module stays
|
390 |
+
untouched. The only required change would be on the forward pass where it
|
391 |
+
calls the public API of flash attention.
|
392 |
+
"""
|
393 |
+
|
394 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
395 |
+
if not is_flash_attn_2_available():
|
396 |
+
raise ImportError(
|
397 |
+
'Flash Attention 2 is not available. Please install it with `pip install flash-attn`.'
|
398 |
+
)
|
399 |
+
|
400 |
+
super().__init__(*args, **kwargs)
|
401 |
+
|
402 |
+
def forward(
|
403 |
+
self,
|
404 |
+
hidden_states: torch.Tensor,
|
405 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
406 |
+
position_ids: Optional[torch.LongTensor] = None,
|
407 |
+
past_key_value: Optional[Cache] = None,
|
408 |
+
output_attentions: bool = False,
|
409 |
+
use_cache: bool = False,
|
410 |
+
cache_position: Optional[torch.LongTensor] = None,
|
411 |
+
**kwargs: Any,
|
412 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor],
|
413 |
+
Optional[Tuple[torch.Tensor]]]:
|
414 |
+
logger.info(
|
415 |
+
'Implicitly setting `output_attentions` to False as it is not supported in Flash Attention.'
|
416 |
+
)
|
417 |
+
output_attentions = False
|
418 |
+
|
419 |
+
bsz, q_len, _ = hidden_states.size()
|
420 |
+
|
421 |
+
qkv_states = self.Wqkv(hidden_states)
|
422 |
+
if self.clip_qkv is not None:
|
423 |
+
qkv_states = qkv_states.clamp(min=-self.clip_qkv, max=self.clip_qkv)
|
424 |
+
|
425 |
+
query_states, key_states, value_states = qkv_states.split(
|
426 |
+
[
|
427 |
+
self.hidden_size,
|
428 |
+
self.num_key_value_heads * self.head_dim,
|
429 |
+
self.num_key_value_heads * self.head_dim,
|
430 |
+
],
|
431 |
+
dim=2,
|
432 |
+
)
|
433 |
+
|
434 |
+
# Flash attention requires the input to have the shape
|
435 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
436 |
+
# therefore we just need to keep the original shape
|
437 |
+
query_states = query_states.view(bsz, q_len, self.num_heads,
|
438 |
+
self.head_dim).transpose(1, 2)
|
439 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads,
|
440 |
+
self.head_dim).transpose(1, 2)
|
441 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads,
|
442 |
+
self.head_dim).transpose(1, 2)
|
443 |
+
|
444 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
445 |
+
query_states, key_states = apply_rotary_pos_emb(query_states,
|
446 |
+
key_states, cos, sin)
|
447 |
+
|
448 |
+
past_key_value = getattr(self, 'past_key_value', past_key_value)
|
449 |
+
|
450 |
+
if past_key_value is not None:
|
451 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
452 |
+
cache_kwargs = {
|
453 |
+
'sin': sin,
|
454 |
+
'cos': cos,
|
455 |
+
'cache_position': cache_position
|
456 |
+
}
|
457 |
+
key_states, value_states = past_key_value.update(
|
458 |
+
key_states, value_states, self.block_idx, cache_kwargs)
|
459 |
+
|
460 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout
|
461 |
+
# [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
462 |
+
# to be able to avoid many of these transpose/reshape/view.
|
463 |
+
query_states = query_states.transpose(1, 2)
|
464 |
+
key_states = key_states.transpose(1, 2)
|
465 |
+
value_states = value_states.transpose(1, 2)
|
466 |
+
|
467 |
+
dropout_rate = self.attn_pdrop if self.training else 0.0
|
468 |
+
|
469 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
470 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
471 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
472 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
473 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
474 |
+
input_dtype = query_states.dtype
|
475 |
+
if input_dtype == torch.float32:
|
476 |
+
if torch.is_autocast_enabled():
|
477 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
478 |
+
# Handle the case where the model is quantized
|
479 |
+
elif hasattr(self.config, '_pre_quantization_dtype'):
|
480 |
+
target_dtype = self.config._pre_quantization_dtype
|
481 |
+
else:
|
482 |
+
target_dtype = query_states.dtype
|
483 |
+
|
484 |
+
logger.warning_once(
|
485 |
+
f'The input hidden states seems to be silently casted in float32, this might be '
|
486 |
+
+
|
487 |
+
f'related to the fact you have upcasted embedding or layer norm layers in '
|
488 |
+
+ f'float32. We will cast back the input in {target_dtype}.')
|
489 |
+
|
490 |
+
query_states = query_states.to(target_dtype)
|
491 |
+
key_states = key_states.to(target_dtype)
|
492 |
+
value_states = value_states.to(target_dtype)
|
493 |
+
|
494 |
+
attn_output = self._flash_attention_forward(
|
495 |
+
query_states,
|
496 |
+
key_states,
|
497 |
+
value_states,
|
498 |
+
attention_mask,
|
499 |
+
q_len,
|
500 |
+
dropout=dropout_rate,
|
501 |
+
)
|
502 |
+
|
503 |
+
attn_output = attn_output.reshape(bsz, q_len,
|
504 |
+
self.hidden_size).contiguous()
|
505 |
+
attn_output = self.out_proj(attn_output)
|
506 |
+
|
507 |
+
if not output_attentions:
|
508 |
+
attn_weights = None
|
509 |
+
|
510 |
+
return attn_output, attn_weights, past_key_value # type: ignore
|
511 |
+
|
512 |
+
def _flash_attention_forward(
|
513 |
+
self,
|
514 |
+
query_states: torch.Tensor,
|
515 |
+
key_states: torch.Tensor,
|
516 |
+
value_states: torch.Tensor,
|
517 |
+
attention_mask: Union[torch.LongTensor, None],
|
518 |
+
query_length: int,
|
519 |
+
dropout: float = 0.0,
|
520 |
+
softmax_scale: Optional[float] = None,
|
521 |
+
):
|
522 |
+
"""Use FlashAttention, stripping padding tokens if necessary.
|
523 |
+
|
524 |
+
Args:
|
525 |
+
query_states (torch.Tensor): Input query states to be passed to Flash Attention API
|
526 |
+
key_states (torch.Tensor): Input key states to be passed to Flash Attention API
|
527 |
+
value_states (torch.Tensor): Input value states to be passed to Flash Attention API
|
528 |
+
attention_mask (torch.LongTensor | None): The padding mask - corresponds to a tensor of size
|
529 |
+
(batch_size, seq_len) where 0 stands for the position of padding tokens and 1
|
530 |
+
for the position of non-padding tokens.
|
531 |
+
query_length (int): The length of the query sequence
|
532 |
+
dropout (float): Attention dropout
|
533 |
+
softmax_scale (float, optional): The scaling of QK^T before applying softmax.
|
534 |
+
Defaults to 1 / sqrt(head_dim)
|
535 |
+
"""
|
536 |
+
causal = True
|
537 |
+
# Contains at least one padding token in the sequence
|
538 |
+
if attention_mask is not None:
|
539 |
+
batch_size = query_states.shape[0]
|
540 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
541 |
+
query_states, key_states, value_states, attention_mask,
|
542 |
+
query_length)
|
543 |
+
|
544 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
545 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
546 |
+
|
547 |
+
attn_output_unpad = flash_attn_varlen_func(
|
548 |
+
query_states,
|
549 |
+
key_states,
|
550 |
+
value_states,
|
551 |
+
cu_seqlens_q=cu_seqlens_q,
|
552 |
+
cu_seqlens_k=cu_seqlens_k,
|
553 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
554 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
555 |
+
dropout_p=dropout,
|
556 |
+
softmax_scale=softmax_scale,
|
557 |
+
causal=causal,
|
558 |
+
)
|
559 |
+
|
560 |
+
attn_output = pad_input(
|
561 |
+
attn_output_unpad,
|
562 |
+
indices_q,
|
563 |
+
batch_size,
|
564 |
+
query_length,
|
565 |
+
)
|
566 |
+
else:
|
567 |
+
attn_output = flash_attn_func(
|
568 |
+
query_states,
|
569 |
+
key_states,
|
570 |
+
value_states,
|
571 |
+
dropout,
|
572 |
+
softmax_scale=softmax_scale,
|
573 |
+
causal=causal,
|
574 |
+
)
|
575 |
+
|
576 |
+
return attn_output
|
577 |
+
|
578 |
+
def _upad_input(self, query_layer: torch.Tensor, key_layer: torch.Tensor,
|
579 |
+
value_layer: torch.Tensor, attention_mask: torch.Tensor,
|
580 |
+
query_length: int):
|
581 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(
|
582 |
+
attention_mask)
|
583 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
584 |
+
|
585 |
+
key_layer = index_first_axis(
|
586 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads,
|
587 |
+
head_dim), indices_k)
|
588 |
+
value_layer = index_first_axis(
|
589 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads,
|
590 |
+
head_dim), indices_k)
|
591 |
+
if query_length == kv_seq_len:
|
592 |
+
query_layer = index_first_axis(
|
593 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads,
|
594 |
+
head_dim), indices_k)
|
595 |
+
cu_seqlens_q = cu_seqlens_k
|
596 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
597 |
+
indices_q = indices_k
|
598 |
+
elif query_length == 1:
|
599 |
+
max_seqlen_in_batch_q = 1
|
600 |
+
cu_seqlens_q = torch.arange(
|
601 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
602 |
+
) # There is a memcpy here, that is very bad.
|
603 |
+
indices_q = cu_seqlens_q[:-1]
|
604 |
+
query_layer = query_layer.squeeze(1)
|
605 |
+
else:
|
606 |
+
# The -q_len: slice assumes left padding.
|
607 |
+
attention_mask = attention_mask[:, -query_length:]
|
608 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
609 |
+
query_layer, attention_mask)
|
610 |
+
|
611 |
+
return (
|
612 |
+
query_layer,
|
613 |
+
key_layer,
|
614 |
+
value_layer,
|
615 |
+
indices_q,
|
616 |
+
(cu_seqlens_q, cu_seqlens_k),
|
617 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
618 |
+
)
|
619 |
+
|
620 |
+
|
621 |
+
DBRX_ATTENTION_CLASSES = {
|
622 |
+
'eager': DbrxAttention,
|
623 |
+
'flash_attention_2': DbrxFlashAttention2,
|
624 |
+
}
|
625 |
+
|
626 |
+
|
627 |
+
class DbrxNormAttentionNorm(nn.Module):
|
628 |
+
|
629 |
+
def __init__(
|
630 |
+
self,
|
631 |
+
hidden_size: int,
|
632 |
+
num_heads: int,
|
633 |
+
max_position_embeddings: int,
|
634 |
+
resid_pdrop: float,
|
635 |
+
attn_implementation: str,
|
636 |
+
attn_config: DbrxAttentionConfig,
|
637 |
+
block_idx: Optional[int] = None,
|
638 |
+
):
|
639 |
+
super().__init__()
|
640 |
+
self.block_idx = block_idx
|
641 |
+
self.resid_pdrop = resid_pdrop
|
642 |
+
self.norm_1 = nn.LayerNorm(hidden_size, bias=False)
|
643 |
+
self.attn = DBRX_ATTENTION_CLASSES[attn_implementation](
|
644 |
+
hidden_size=hidden_size,
|
645 |
+
num_heads=num_heads,
|
646 |
+
max_position_embeddings=max_position_embeddings,
|
647 |
+
attn_config=attn_config,
|
648 |
+
block_idx=block_idx,
|
649 |
+
)
|
650 |
+
self.norm_2 = nn.LayerNorm(hidden_size, bias=False)
|
651 |
+
|
652 |
+
def forward(
|
653 |
+
self,
|
654 |
+
hidden_states: torch.Tensor,
|
655 |
+
position_ids: torch.LongTensor,
|
656 |
+
attention_mask: Optional[torch.Tensor] = None,
|
657 |
+
past_key_value: Optional[Cache] = None,
|
658 |
+
output_attentions: bool = False,
|
659 |
+
use_cache: bool = False,
|
660 |
+
cache_position: Optional[torch.LongTensor] = None,
|
661 |
+
**kwargs: Any,
|
662 |
+
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor],
|
663 |
+
Optional[Cache]]:
|
664 |
+
|
665 |
+
residual_states = hidden_states
|
666 |
+
hidden_states = self.norm_1(hidden_states).to(hidden_states.dtype)
|
667 |
+
|
668 |
+
hidden_states, attn_weights, past_key_value = self.attn(
|
669 |
+
hidden_states=hidden_states,
|
670 |
+
attention_mask=attention_mask,
|
671 |
+
position_ids=position_ids,
|
672 |
+
past_key_value=past_key_value,
|
673 |
+
output_attentions=output_attentions,
|
674 |
+
use_cache=use_cache,
|
675 |
+
cache_position=cache_position,
|
676 |
+
**kwargs,
|
677 |
+
)
|
678 |
+
|
679 |
+
hidden_states = nn.functional.dropout(hidden_states,
|
680 |
+
p=self.resid_pdrop,
|
681 |
+
training=self.training)
|
682 |
+
hidden_states = hidden_states + residual_states
|
683 |
+
|
684 |
+
residual_states = hidden_states
|
685 |
+
hidden_states = self.norm_2(hidden_states).to(hidden_states.dtype)
|
686 |
+
|
687 |
+
return residual_states, hidden_states, attn_weights, past_key_value
|
688 |
+
|
689 |
+
|
690 |
+
class DbrxRouter(nn.Module):
|
691 |
+
|
692 |
+
def __init__(self, hidden_size: int, moe_num_experts: int, moe_top_k: int,
|
693 |
+
moe_jitter_eps: Optional[float],
|
694 |
+
moe_normalize_expert_weights: Optional[float],
|
695 |
+
uniform_expert_assignment: bool):
|
696 |
+
super().__init__()
|
697 |
+
self.hidden_size = hidden_size
|
698 |
+
self.moe_num_experts = moe_num_experts
|
699 |
+
self.moe_top_k = moe_top_k
|
700 |
+
self.moe_jitter_eps = moe_jitter_eps
|
701 |
+
self.moe_normalize_expert_weights = moe_normalize_expert_weights
|
702 |
+
self.uniform_expert_assignment = uniform_expert_assignment
|
703 |
+
|
704 |
+
self.layer = nn.Linear(self.hidden_size,
|
705 |
+
self.moe_num_experts,
|
706 |
+
bias=False)
|
707 |
+
|
708 |
+
def jitter(self, x: torch.Tensor) -> torch.Tensor:
|
709 |
+
if self.moe_jitter_eps is None:
|
710 |
+
raise RuntimeError('The router does not have moe_jitter_eps set.')
|
711 |
+
low = 1.0 - self.moe_jitter_eps
|
712 |
+
high = 1.0 + self.moe_jitter_eps
|
713 |
+
noise = torch.rand(x.size(), dtype=x.dtype, device=x.device)
|
714 |
+
return low + noise * (high - low)
|
715 |
+
|
716 |
+
def forward(
|
717 |
+
self, x: torch.Tensor
|
718 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.LongTensor]:
|
719 |
+
if self.training and self.moe_jitter_eps is not None:
|
720 |
+
x = x * self.jitter(x)
|
721 |
+
|
722 |
+
weights = self.layer(x.view(-1,
|
723 |
+
x.shape[-1])).softmax(dim=-1,
|
724 |
+
dtype=torch.float32)
|
725 |
+
top_weights, top_experts = torch.topk(weights, self.moe_top_k, dim=-1)
|
726 |
+
|
727 |
+
if self.moe_normalize_expert_weights:
|
728 |
+
top_weights = top_weights / torch.norm(
|
729 |
+
top_weights,
|
730 |
+
p=self.moe_normalize_expert_weights,
|
731 |
+
dim=-1,
|
732 |
+
keepdim=True)
|
733 |
+
|
734 |
+
if self.uniform_expert_assignment:
|
735 |
+
with torch.no_grad():
|
736 |
+
uniform_tensor = torch.arange(
|
737 |
+
0,
|
738 |
+
top_experts.numel(),
|
739 |
+
device=top_experts.device,
|
740 |
+
dtype=top_experts.dtype) % self.moe_num_experts
|
741 |
+
top_experts = uniform_tensor.reshape(top_experts.shape)
|
742 |
+
# Note, weights and top_weights are not changed
|
743 |
+
|
744 |
+
weights = weights.to(x.dtype)
|
745 |
+
top_weights = top_weights.to(x.dtype)
|
746 |
+
return weights, top_weights, top_experts # type: ignore
|
747 |
+
|
748 |
+
|
749 |
+
class DbrxExpertGLU(nn.Module):
|
750 |
+
|
751 |
+
def __init__(self, hidden_size: int, ffn_hidden_size: int,
|
752 |
+
moe_num_experts: int, ffn_act_fn: dict):
|
753 |
+
super().__init__()
|
754 |
+
self.hidden_size = hidden_size
|
755 |
+
self.ffn_hidden_size = ffn_hidden_size
|
756 |
+
self.moe_num_experts = moe_num_experts
|
757 |
+
|
758 |
+
self.w1 = nn.Parameter(
|
759 |
+
torch.empty(moe_num_experts * ffn_hidden_size, hidden_size))
|
760 |
+
self.v1 = nn.Parameter(
|
761 |
+
torch.empty(moe_num_experts * ffn_hidden_size, hidden_size))
|
762 |
+
self.w2 = nn.Parameter(
|
763 |
+
torch.empty(moe_num_experts * ffn_hidden_size, hidden_size))
|
764 |
+
self.activation_fn = resolve_ffn_act_fn(ffn_act_fn)
|
765 |
+
|
766 |
+
def forward(self, x: torch.Tensor, expert_idx: int) -> torch.Tensor:
|
767 |
+
expert_w1 = self.w1.view(self.moe_num_experts, self.ffn_hidden_size,
|
768 |
+
self.hidden_size)[expert_idx]
|
769 |
+
expert_v1 = self.v1.view(self.moe_num_experts, self.ffn_hidden_size,
|
770 |
+
self.hidden_size)[expert_idx]
|
771 |
+
expert_w2 = self.w2.view(self.moe_num_experts, self.ffn_hidden_size,
|
772 |
+
self.hidden_size)[expert_idx]
|
773 |
+
|
774 |
+
x1 = x.matmul(expert_w1.t())
|
775 |
+
x2 = x.matmul(expert_v1.t())
|
776 |
+
x1 = self.activation_fn(x1)
|
777 |
+
x1 = x1 * x2
|
778 |
+
x1 = x1.matmul(expert_w2)
|
779 |
+
return x1
|
780 |
+
|
781 |
+
|
782 |
+
class DbrxExperts(nn.Module):
|
783 |
+
|
784 |
+
def __init__(self, hidden_size: int, ffn_hidden_size: int,
|
785 |
+
moe_num_experts: int, ffn_act_fn: dict):
|
786 |
+
super().__init__()
|
787 |
+
self.moe_num_experts = moe_num_experts
|
788 |
+
self.mlp = DbrxExpertGLU(hidden_size=hidden_size,
|
789 |
+
ffn_hidden_size=ffn_hidden_size,
|
790 |
+
moe_num_experts=moe_num_experts,
|
791 |
+
ffn_act_fn=ffn_act_fn)
|
792 |
+
|
793 |
+
def forward(self, x: torch.Tensor, weights: torch.Tensor,
|
794 |
+
top_weights: torch.Tensor,
|
795 |
+
top_experts: torch.LongTensor) -> torch.Tensor:
|
796 |
+
bsz, q_len, hidden_size = x.shape
|
797 |
+
x = x.view(-1, hidden_size)
|
798 |
+
out = torch.zeros_like(x)
|
799 |
+
|
800 |
+
expert_mask = nn.functional.one_hot(
|
801 |
+
top_experts, num_classes=self.moe_num_experts).permute(2, 1, 0)
|
802 |
+
for expert_idx in range(0, self.moe_num_experts):
|
803 |
+
topk_idx, token_idx = torch.where(expert_mask[expert_idx])
|
804 |
+
if token_idx.shape[0] == 0:
|
805 |
+
continue
|
806 |
+
|
807 |
+
token_list = token_idx.tolist()
|
808 |
+
topk_list = topk_idx.tolist()
|
809 |
+
|
810 |
+
expert_tokens = x[None, token_list].reshape(-1, hidden_size)
|
811 |
+
expert_out = self.mlp(
|
812 |
+
expert_tokens, expert_idx) * top_weights[token_list, topk_list,
|
813 |
+
None]
|
814 |
+
|
815 |
+
out.index_add_(0, token_idx, expert_out)
|
816 |
+
|
817 |
+
out = out.reshape(bsz, q_len, hidden_size)
|
818 |
+
return out
|
819 |
+
|
820 |
+
|
821 |
+
class DbrxFFN(nn.Module):
|
822 |
+
|
823 |
+
def __init__(self, hidden_size: int, ffn_config: DbrxFFNConfig):
|
824 |
+
super().__init__()
|
825 |
+
|
826 |
+
self.router = DbrxRouter(
|
827 |
+
hidden_size,
|
828 |
+
moe_num_experts=ffn_config.moe_num_experts,
|
829 |
+
moe_top_k=ffn_config.moe_top_k,
|
830 |
+
moe_jitter_eps=ffn_config.moe_jitter_eps,
|
831 |
+
moe_normalize_expert_weights=ffn_config.
|
832 |
+
moe_normalize_expert_weights,
|
833 |
+
uniform_expert_assignment=ffn_config.uniform_expert_assignment,
|
834 |
+
)
|
835 |
+
|
836 |
+
self.experts = DbrxExperts(
|
837 |
+
hidden_size=hidden_size,
|
838 |
+
ffn_hidden_size=ffn_config.ffn_hidden_size,
|
839 |
+
moe_num_experts=ffn_config.moe_num_experts,
|
840 |
+
ffn_act_fn=ffn_config.ffn_act_fn,
|
841 |
+
)
|
842 |
+
|
843 |
+
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
844 |
+
weights, top_weights, top_experts = self.router(x)
|
845 |
+
out = self.experts(x, weights, top_weights, top_experts)
|
846 |
+
return out, weights
|
847 |
+
|
848 |
+
|
849 |
+
class DbrxBlock(nn.Module):
|
850 |
+
|
851 |
+
def __init__(self, config: DbrxConfig, block_idx: int):
|
852 |
+
super().__init__()
|
853 |
+
self.hidden_size = config.d_model
|
854 |
+
self.resid_pdrop = config.resid_pdrop
|
855 |
+
self.block_idx = block_idx
|
856 |
+
self.norm_attn_norm = DbrxNormAttentionNorm(
|
857 |
+
hidden_size=config.d_model,
|
858 |
+
num_heads=config.n_heads,
|
859 |
+
max_position_embeddings=config.max_seq_len,
|
860 |
+
resid_pdrop=config.resid_pdrop,
|
861 |
+
attn_implementation=config._attn_implementation,
|
862 |
+
attn_config=config.attn_config,
|
863 |
+
block_idx=block_idx,
|
864 |
+
)
|
865 |
+
self.ffn = DbrxFFN(hidden_size=config.d_model,
|
866 |
+
ffn_config=config.ffn_config)
|
867 |
+
|
868 |
+
def forward(
|
869 |
+
self,
|
870 |
+
hidden_states: torch.Tensor,
|
871 |
+
position_ids: torch.LongTensor,
|
872 |
+
attention_mask: Optional[torch.Tensor] = None,
|
873 |
+
past_key_value: Optional[Cache] = None,
|
874 |
+
output_attentions: Optional[bool] = False,
|
875 |
+
output_router_logits: Optional[bool] = False,
|
876 |
+
use_cache: Optional[bool] = False,
|
877 |
+
cache_position: Optional[torch.LongTensor] = None,
|
878 |
+
**kwargs: Any,
|
879 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, Optional[torch.Tensor]],
|
880 |
+
Tuple[torch.Tensor, Optional[Cache]], Tuple[
|
881 |
+
torch.Tensor, Optional[torch.Tensor], Optional[Cache]],
|
882 |
+
Tuple[torch.Tensor, Optional[torch.Tensor],
|
883 |
+
Optional[torch.Tensor]], Tuple[
|
884 |
+
torch.Tensor, Optional[Cache], Optional[torch.Tensor]],
|
885 |
+
Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache],
|
886 |
+
Optional[torch.Tensor]],]:
|
887 |
+
"""Forward function for DbrxBlock.
|
888 |
+
|
889 |
+
Args:
|
890 |
+
hidden_states (`torch.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
891 |
+
position_ids (`torch.LongTensor`): position ids of shape `(batch, seq_len)`
|
892 |
+
attention_mask (`torch.Tensor`, optional): attention mask of size (batch_size, sequence_length)
|
893 |
+
if flash attention is used or (batch_size, 1, query_sequence_length, key_sequence_length)
|
894 |
+
if default attention is used.
|
895 |
+
past_key_value (`Tuple(torch.Tensor)`, optional): cached past key and value projection states
|
896 |
+
output_attentions (`bool`, optional): Whether or not to return the attentions tensors of all
|
897 |
+
attention layers. See `attentions` under returned tensors for more detail.
|
898 |
+
output_router_logits (`bool`, optional): Whether or not to return the router logits.
|
899 |
+
use_cache (`bool`, optional): If set to `True`, `past_key_values` key value states are
|
900 |
+
returned and can be used to speed up decoding (see `past_key_values`).
|
901 |
+
cache_position (`torch.LongTensor`, optional): position ids of the cache
|
902 |
+
"""
|
903 |
+
if 'padding_mask' in kwargs:
|
904 |
+
warnings.warn(
|
905 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
|
906 |
+
)
|
907 |
+
|
908 |
+
# Norm + Attention + Norm
|
909 |
+
resid_states, hidden_states, self_attn_weights, present_key_value = self.norm_attn_norm(
|
910 |
+
hidden_states=hidden_states,
|
911 |
+
attention_mask=attention_mask,
|
912 |
+
position_ids=position_ids,
|
913 |
+
past_key_value=past_key_value,
|
914 |
+
output_attentions=output_attentions,
|
915 |
+
use_cache=use_cache,
|
916 |
+
cache_position=cache_position,
|
917 |
+
**kwargs,
|
918 |
+
)
|
919 |
+
|
920 |
+
# Fully Connected
|
921 |
+
hidden_states, router_logits = self.ffn(hidden_states)
|
922 |
+
hidden_states = nn.functional.dropout(hidden_states,
|
923 |
+
p=self.resid_pdrop,
|
924 |
+
training=self.training)
|
925 |
+
hidden_states = resid_states + hidden_states
|
926 |
+
|
927 |
+
outputs = (hidden_states,)
|
928 |
+
|
929 |
+
if output_attentions:
|
930 |
+
outputs += (self_attn_weights,)
|
931 |
+
|
932 |
+
if use_cache:
|
933 |
+
outputs += (present_key_value,)
|
934 |
+
|
935 |
+
if output_router_logits:
|
936 |
+
outputs += (router_logits,)
|
937 |
+
|
938 |
+
return outputs
|
939 |
+
|
940 |
+
|
941 |
+
class DbrxPreTrainedModel(PreTrainedModel):
|
942 |
+
config_class = DbrxConfig
|
943 |
+
base_model_prefix = 'transformer'
|
944 |
+
supports_gradient_checkpointing = True
|
945 |
+
_no_split_modules = ['DbrxBlock']
|
946 |
+
_skip_keys_device_placement = ['past_key_values']
|
947 |
+
_supports_flash_attn_2 = True
|
948 |
+
_supports_sdpa = False
|
949 |
+
_supports_cache_class = True
|
950 |
+
|
951 |
+
def _init_weights(self, module: nn.Module):
|
952 |
+
std = self.config.initializer_range
|
953 |
+
if isinstance(module, nn.Linear):
|
954 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
955 |
+
if module.bias is not None:
|
956 |
+
module.bias.data.zero_()
|
957 |
+
elif isinstance(module, nn.Embedding):
|
958 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
959 |
+
if module.padding_idx is not None:
|
960 |
+
module.weight.data[module.padding_idx].zero_()
|
961 |
+
elif isinstance(module, nn.LayerNorm):
|
962 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
963 |
+
if module.bias is not None:
|
964 |
+
module.bias.data.zero_()
|
965 |
+
elif isinstance(module, DbrxExpertGLU):
|
966 |
+
module.w1.data.normal_(mean=0.0, std=std)
|
967 |
+
module.v1.data.normal_(mean=0.0, std=std)
|
968 |
+
module.w2.data.normal_(mean=0.0, std=std)
|
969 |
+
|
970 |
+
def _setup_cache(self, cache_cls: Any, max_batch_size: int,
|
971 |
+
max_cache_len: int): # TODO: how to set var type of class?
|
972 |
+
if self.config._attn_implementation == 'flash_attention_2' and cache_cls == StaticCache:
|
973 |
+
raise ValueError(
|
974 |
+
'`static` cache implementation is not compatible with ' +
|
975 |
+
'`attn_implementation==flash_attention_2`. Make sure to use ' +
|
976 |
+
'`spda` in the mean time and open an issue at https://github.com/huggingface/transformers.'
|
977 |
+
)
|
978 |
+
|
979 |
+
for block in self.transformer.blocks:
|
980 |
+
device = block.norm_attn_norm.norm_1.weight.device
|
981 |
+
if hasattr(self.config, '_pre_quantization_dtype'):
|
982 |
+
dtype = self.config._pre_quantization_dtype
|
983 |
+
else:
|
984 |
+
dtype = block.norm_attn_norm.attn.out_proj.weight.dtype
|
985 |
+
block.norm_attn_norm.attn.past_key_value = cache_cls(self.config,
|
986 |
+
max_batch_size,
|
987 |
+
max_cache_len,
|
988 |
+
device=device,
|
989 |
+
dtype=dtype)
|
990 |
+
|
991 |
+
def _reset_cache(self):
|
992 |
+
for block in self.transformer.blocks:
|
993 |
+
block.norm_attn_norm.attn.past_key_value = None
|
994 |
+
|
995 |
+
|
996 |
+
class DbrxModel(DbrxPreTrainedModel):
|
997 |
+
"""Transformer decoder consisting of *config.num_hidden_layers*
|
998 |
+
|
999 |
+
[`DbrxBlock`] layers.
|
1000 |
+
|
1001 |
+
Args:
|
1002 |
+
config: DbrxConfig
|
1003 |
+
"""
|
1004 |
+
|
1005 |
+
def __init__(self, config: DbrxConfig):
|
1006 |
+
super().__init__(config)
|
1007 |
+
self.padding_idx = config.pad_token_id
|
1008 |
+
self.vocab_size = config.vocab_size
|
1009 |
+
self.emb_pdrop = config.emb_pdrop
|
1010 |
+
|
1011 |
+
self.wte = nn.Embedding(config.vocab_size, config.d_model,
|
1012 |
+
self.padding_idx)
|
1013 |
+
self.blocks = nn.ModuleList([
|
1014 |
+
DbrxBlock(config, block_idx) for block_idx in range(config.n_layers)
|
1015 |
+
])
|
1016 |
+
self.norm_f = nn.LayerNorm(config.d_model, bias=False)
|
1017 |
+
self.gradient_checkpointing = False
|
1018 |
+
|
1019 |
+
# Initialize weights and apply final processing
|
1020 |
+
self.post_init()
|
1021 |
+
|
1022 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
1023 |
+
return self.wte
|
1024 |
+
|
1025 |
+
def set_input_embeddings(self, value: nn.Embedding):
|
1026 |
+
self.wte = value
|
1027 |
+
|
1028 |
+
def _autocast_input_embeddings(self,
|
1029 |
+
inputs_embeds: torch.Tensor) -> torch.Tensor:
|
1030 |
+
if inputs_embeds.device.type == 'cuda' and torch.is_autocast_enabled():
|
1031 |
+
return inputs_embeds.to(dtype=torch.get_autocast_gpu_dtype())
|
1032 |
+
elif inputs_embeds.device.type == 'cpu' and torch.is_autocast_cpu_enabled(
|
1033 |
+
):
|
1034 |
+
return inputs_embeds.to(dtype=torch.get_autocast_cpu_dtype())
|
1035 |
+
else:
|
1036 |
+
return inputs_embeds
|
1037 |
+
|
1038 |
+
def forward(
|
1039 |
+
self,
|
1040 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1041 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1042 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1043 |
+
past_key_values: Optional[Cache] = None,
|
1044 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1045 |
+
use_cache: Optional[bool] = None,
|
1046 |
+
output_attentions: Optional[bool] = None,
|
1047 |
+
output_hidden_states: Optional[bool] = None,
|
1048 |
+
output_router_logits: Optional[bool] = None,
|
1049 |
+
return_dict: Optional[bool] = None,
|
1050 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1051 |
+
) -> Union[Tuple, MoeModelOutputWithPast]:
|
1052 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1053 |
+
output_hidden_states = (output_hidden_states
|
1054 |
+
if output_hidden_states is not None else
|
1055 |
+
self.config.output_hidden_states)
|
1056 |
+
output_router_logits = (output_router_logits
|
1057 |
+
if output_router_logits is not None else
|
1058 |
+
self.config.output_router_logits)
|
1059 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1060 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1061 |
+
|
1062 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
1063 |
+
raise ValueError(
|
1064 |
+
'You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one'
|
1065 |
+
)
|
1066 |
+
|
1067 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
1068 |
+
logger.warning_once(
|
1069 |
+
'`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.'
|
1070 |
+
)
|
1071 |
+
use_cache = False
|
1072 |
+
|
1073 |
+
if inputs_embeds is None:
|
1074 |
+
inputs_embeds = self.wte(input_ids)
|
1075 |
+
|
1076 |
+
inputs_embeds = self._autocast_input_embeddings(
|
1077 |
+
inputs_embeds) # type: ignore
|
1078 |
+
inputs_embeds = nn.functional.dropout(inputs_embeds,
|
1079 |
+
p=self.emb_pdrop,
|
1080 |
+
training=self.training)
|
1081 |
+
|
1082 |
+
past_seen_tokens = 0
|
1083 |
+
if use_cache: # kept for BC (cache positions)
|
1084 |
+
if not isinstance(past_key_values, StaticCache):
|
1085 |
+
past_key_values = DynamicCache.from_legacy_cache(
|
1086 |
+
past_key_values)
|
1087 |
+
past_seen_tokens = past_key_values.get_seq_length( # type: ignore
|
1088 |
+
)
|
1089 |
+
|
1090 |
+
if cache_position is None:
|
1091 |
+
if isinstance(past_key_values, StaticCache):
|
1092 |
+
raise ValueError(
|
1093 |
+
'cache_position is a required argument when using StaticCache.'
|
1094 |
+
)
|
1095 |
+
cache_position = torch.arange( # type: ignore
|
1096 |
+
past_seen_tokens,
|
1097 |
+
past_seen_tokens + inputs_embeds.shape[1],
|
1098 |
+
device=inputs_embeds.device)
|
1099 |
+
|
1100 |
+
if position_ids is None:
|
1101 |
+
position_ids = cache_position.unsqueeze(0) # type: ignore
|
1102 |
+
|
1103 |
+
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds,
|
1104 |
+
cache_position) # type: ignore
|
1105 |
+
|
1106 |
+
# embed positions
|
1107 |
+
hidden_states = inputs_embeds
|
1108 |
+
|
1109 |
+
# decoder layers
|
1110 |
+
all_hidden_states = () if output_hidden_states else None
|
1111 |
+
all_self_attns = () if output_attentions else None
|
1112 |
+
all_router_logits = () if output_router_logits else None
|
1113 |
+
next_decoder_cache = None
|
1114 |
+
|
1115 |
+
for block in self.blocks:
|
1116 |
+
if output_hidden_states:
|
1117 |
+
all_hidden_states += (hidden_states,) # type: ignore
|
1118 |
+
|
1119 |
+
if self.gradient_checkpointing and self.training:
|
1120 |
+
block_outputs = self._gradient_checkpointing_func(
|
1121 |
+
block.__call__,
|
1122 |
+
hidden_states,
|
1123 |
+
attention_mask=causal_mask,
|
1124 |
+
position_ids=position_ids,
|
1125 |
+
past_key_values=past_key_values,
|
1126 |
+
output_attentions=output_attentions,
|
1127 |
+
output_router_logits=output_router_logits,
|
1128 |
+
use_cache=use_cache,
|
1129 |
+
cache_position=cache_position,
|
1130 |
+
)
|
1131 |
+
else:
|
1132 |
+
block_outputs = block(
|
1133 |
+
hidden_states,
|
1134 |
+
attention_mask=causal_mask,
|
1135 |
+
position_ids=position_ids,
|
1136 |
+
past_key_value=past_key_values,
|
1137 |
+
output_attentions=output_attentions,
|
1138 |
+
output_router_logits=output_router_logits,
|
1139 |
+
use_cache=use_cache,
|
1140 |
+
cache_position=cache_position,
|
1141 |
+
)
|
1142 |
+
|
1143 |
+
hidden_states = block_outputs[0]
|
1144 |
+
|
1145 |
+
if use_cache:
|
1146 |
+
next_decoder_cache = block_outputs[
|
1147 |
+
2 if output_attentions else 1]
|
1148 |
+
|
1149 |
+
if output_attentions:
|
1150 |
+
all_self_attns += (block_outputs[1],) # type: ignore
|
1151 |
+
|
1152 |
+
if output_router_logits:
|
1153 |
+
all_router_logits += (block_outputs[-1],) # type: ignore
|
1154 |
+
|
1155 |
+
hidden_states = self.norm_f(hidden_states)
|
1156 |
+
|
1157 |
+
# add hidden states from the last decoder layer
|
1158 |
+
if output_hidden_states:
|
1159 |
+
all_hidden_states += (hidden_states,) # type: ignore
|
1160 |
+
|
1161 |
+
next_cache = None
|
1162 |
+
if use_cache:
|
1163 |
+
next_cache = (
|
1164 |
+
next_decoder_cache.to_legacy_cache() # type: ignore
|
1165 |
+
if isinstance(next_decoder_cache, Cache) else
|
1166 |
+
next_decoder_cache)
|
1167 |
+
if not return_dict:
|
1168 |
+
return tuple(v for v in [
|
1169 |
+
hidden_states, next_cache, all_hidden_states, all_self_attns,
|
1170 |
+
all_router_logits
|
1171 |
+
] if v is not None)
|
1172 |
+
return MoeModelOutputWithPast(
|
1173 |
+
last_hidden_state=hidden_states,
|
1174 |
+
past_key_values=next_cache,
|
1175 |
+
hidden_states=all_hidden_states,
|
1176 |
+
attentions=all_self_attns,
|
1177 |
+
router_logits=all_router_logits,
|
1178 |
+
)
|
1179 |
+
|
1180 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
1181 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
1182 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
1183 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
1184 |
+
def _update_causal_mask(
|
1185 |
+
self, attention_mask: Optional[torch.Tensor],
|
1186 |
+
input_tensor: torch.Tensor,
|
1187 |
+
cache_position: torch.Tensor) -> Optional[torch.Tensor]:
|
1188 |
+
if self.config._attn_implementation == 'flash_attention_2':
|
1189 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1190 |
+
return attention_mask
|
1191 |
+
return None
|
1192 |
+
|
1193 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1194 |
+
min_dtype = torch.finfo(dtype).min
|
1195 |
+
sequence_length = input_tensor.shape[1]
|
1196 |
+
if hasattr(self.blocks[0].norm_attn_norm.attn,
|
1197 |
+
'past_key_value'): # static cache
|
1198 |
+
target_length = self.config.max_position_embeddings
|
1199 |
+
else: # dynamic cache
|
1200 |
+
target_length = (attention_mask.shape[-1] if isinstance(
|
1201 |
+
attention_mask, torch.Tensor) else cache_position[-1] + 1)
|
1202 |
+
target_length = int(target_length)
|
1203 |
+
|
1204 |
+
causal_mask = torch.full((sequence_length, target_length),
|
1205 |
+
fill_value=min_dtype,
|
1206 |
+
dtype=dtype,
|
1207 |
+
device=device)
|
1208 |
+
if sequence_length != 1:
|
1209 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
1210 |
+
causal_mask *= torch.arange(
|
1211 |
+
target_length, device=device) > cache_position.reshape(-1, 1)
|
1212 |
+
causal_mask = causal_mask[None,
|
1213 |
+
None, :, :].expand(input_tensor.shape[0], 1,
|
1214 |
+
-1, -1)
|
1215 |
+
if attention_mask is not None:
|
1216 |
+
causal_mask = causal_mask.clone(
|
1217 |
+
) # copy to contiguous memory for in-place edit
|
1218 |
+
if attention_mask.dim() == 2:
|
1219 |
+
mask_length = attention_mask.shape[-1]
|
1220 |
+
padding_mask = causal_mask[..., :mask_length].eq(
|
1221 |
+
0.0) * attention_mask[:, None, None, :].eq(0.0)
|
1222 |
+
causal_mask[..., :mask_length] = causal_mask[
|
1223 |
+
..., :mask_length].masked_fill(padding_mask, min_dtype)
|
1224 |
+
elif attention_mask.dim() == 4:
|
1225 |
+
# backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
|
1226 |
+
# cache. In that case, the 4D attention mask attends to the newest tokens only.
|
1227 |
+
if attention_mask.shape[
|
1228 |
+
-2] < cache_position[0] + sequence_length:
|
1229 |
+
offset = cache_position[0]
|
1230 |
+
else:
|
1231 |
+
offset = 0
|
1232 |
+
mask_shape = attention_mask.shape
|
1233 |
+
mask_slice = (attention_mask.eq(0.0)).to(
|
1234 |
+
dtype=dtype) * min_dtype
|
1235 |
+
causal_mask[:mask_shape[0], :mask_shape[1],
|
1236 |
+
offset:mask_shape[2] +
|
1237 |
+
offset, :mask_shape[3]] = mask_slice
|
1238 |
+
|
1239 |
+
if (self.config._attn_implementation == 'sdpa' and
|
1240 |
+
attention_mask is not None and
|
1241 |
+
attention_mask.device.type == 'cuda'):
|
1242 |
+
# TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
|
1243 |
+
is_tracing = (
|
1244 |
+
torch.jit.is_tracing() or
|
1245 |
+
isinstance(input_tensor, torch.fx.Proxy) or # type: ignore
|
1246 |
+
(hasattr(torch, '_dynamo') and torch._dynamo.is_compiling()))
|
1247 |
+
if not is_tracing and torch.any(attention_mask != 1):
|
1248 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1249 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1250 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1251 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(
|
1252 |
+
causal_mask, min_dtype)
|
1253 |
+
|
1254 |
+
return causal_mask
|
1255 |
+
|
1256 |
+
|
1257 |
+
class DbrxForCausalLM(DbrxPreTrainedModel):
|
1258 |
+
|
1259 |
+
def __init__(self, config: DbrxConfig):
|
1260 |
+
super().__init__(config)
|
1261 |
+
self.transformer = DbrxModel(config)
|
1262 |
+
self.vocab_size = config.vocab_size
|
1263 |
+
self.lm_head = nn.Linear(config.hidden_size,
|
1264 |
+
config.vocab_size,
|
1265 |
+
bias=False)
|
1266 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
1267 |
+
self.num_experts = config.ffn_config.moe_num_experts
|
1268 |
+
self.num_experts_per_tok = config.ffn_config.moe_top_k
|
1269 |
+
|
1270 |
+
# Initialize weights and apply final processing
|
1271 |
+
self.post_init()
|
1272 |
+
|
1273 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
1274 |
+
return self.transformer.get_input_embeddings()
|
1275 |
+
|
1276 |
+
def set_input_embeddings(self, value: nn.Embedding):
|
1277 |
+
self.transformer.set_input_embeddings(value)
|
1278 |
+
|
1279 |
+
def get_output_embeddings(self) -> nn.Linear:
|
1280 |
+
return self.lm_head
|
1281 |
+
|
1282 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear):
|
1283 |
+
self.lm_head = new_embeddings
|
1284 |
+
|
1285 |
+
def set_decoder(self, decoder: DbrxModel):
|
1286 |
+
self.transformer = decoder
|
1287 |
+
|
1288 |
+
def get_decoder(self) -> DbrxModel:
|
1289 |
+
return self.transformer
|
1290 |
+
|
1291 |
+
def forward(
|
1292 |
+
self,
|
1293 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1294 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1295 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1296 |
+
past_key_values: Optional[Cache] = None,
|
1297 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1298 |
+
labels: Optional[torch.LongTensor] = None,
|
1299 |
+
use_cache: Optional[bool] = None,
|
1300 |
+
output_attentions: Optional[bool] = None,
|
1301 |
+
output_hidden_states: Optional[bool] = None,
|
1302 |
+
output_router_logits: Optional[bool] = None,
|
1303 |
+
return_dict: Optional[bool] = None,
|
1304 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1305 |
+
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
|
1306 |
+
r"""Forward function for causal language modeling.
|
1307 |
+
|
1308 |
+
Example:
|
1309 |
+
```python
|
1310 |
+
>>> from transformers import AutoTokenizer, DbrxForCausalLM
|
1311 |
+
|
1312 |
+
>>> model = DbrxForCausalLM.from_pretrained("databricks/dbrx")
|
1313 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("databricks/dbrx")
|
1314 |
+
|
1315 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1316 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1317 |
+
|
1318 |
+
>>> # Generate
|
1319 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1320 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1321 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1322 |
+
```
|
1323 |
+
"""
|
1324 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1325 |
+
output_hidden_states = (output_hidden_states
|
1326 |
+
if output_hidden_states is not None else
|
1327 |
+
self.config.output_hidden_states)
|
1328 |
+
output_router_logits = (output_router_logits
|
1329 |
+
if output_router_logits is not None else
|
1330 |
+
self.config.output_router_logits)
|
1331 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1332 |
+
|
1333 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1334 |
+
outputs = self.transformer(
|
1335 |
+
input_ids=input_ids,
|
1336 |
+
attention_mask=attention_mask,
|
1337 |
+
position_ids=position_ids,
|
1338 |
+
past_key_values=past_key_values,
|
1339 |
+
inputs_embeds=inputs_embeds,
|
1340 |
+
use_cache=use_cache,
|
1341 |
+
output_attentions=output_attentions,
|
1342 |
+
output_hidden_states=output_hidden_states,
|
1343 |
+
output_router_logits=output_router_logits,
|
1344 |
+
return_dict=return_dict,
|
1345 |
+
cache_position=cache_position,
|
1346 |
+
)
|
1347 |
+
|
1348 |
+
hidden_states = outputs[0]
|
1349 |
+
logits = self.lm_head(hidden_states)
|
1350 |
+
|
1351 |
+
loss = None
|
1352 |
+
if labels is not None:
|
1353 |
+
# Shift so that tokens < n predict n
|
1354 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1355 |
+
shift_labels = labels[..., 1:].contiguous()
|
1356 |
+
# Flatten the tokens
|
1357 |
+
loss_fct = nn.CrossEntropyLoss()
|
1358 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1359 |
+
shift_labels = shift_labels.view(-1)
|
1360 |
+
# Enable model parallelism
|
1361 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1362 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1363 |
+
|
1364 |
+
aux_loss = None
|
1365 |
+
if output_router_logits:
|
1366 |
+
aux_loss = load_balancing_loss_func(
|
1367 |
+
outputs.router_logits if return_dict else outputs[-1],
|
1368 |
+
self.num_experts,
|
1369 |
+
self.num_experts_per_tok,
|
1370 |
+
attention_mask,
|
1371 |
+
)
|
1372 |
+
if labels is not None and loss is not None:
|
1373 |
+
loss += self.router_aux_loss_coef * aux_loss.to(
|
1374 |
+
loss.device) # make sure to reside in the same device
|
1375 |
+
|
1376 |
+
if not return_dict:
|
1377 |
+
output = (logits,) + outputs[1:]
|
1378 |
+
return (loss,) + output if loss is not None else output
|
1379 |
+
|
1380 |
+
return MoeCausalLMOutputWithPast(
|
1381 |
+
loss=loss,
|
1382 |
+
aux_loss=aux_loss,
|
1383 |
+
logits=logits,
|
1384 |
+
past_key_values=outputs.past_key_values,
|
1385 |
+
hidden_states=outputs.hidden_states,
|
1386 |
+
attentions=outputs.attentions,
|
1387 |
+
router_logits=outputs.router_logits,
|
1388 |
+
)
|
1389 |
+
|
1390 |
+
def prepare_inputs_for_generation(
|
1391 |
+
self,
|
1392 |
+
input_ids: torch.Tensor,
|
1393 |
+
past_key_values: Optional[Cache] = None,
|
1394 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1395 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1396 |
+
**kwargs: Any) -> Dict[str, Any]:
|
1397 |
+
past_length = 0
|
1398 |
+
if past_key_values is not None:
|
1399 |
+
if isinstance(past_key_values, Cache):
|
1400 |
+
cache_length = past_key_values.get_seq_length()
|
1401 |
+
past_length = past_key_values.seen_tokens
|
1402 |
+
max_cache_length = past_key_values.get_max_length()
|
1403 |
+
else:
|
1404 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1405 |
+
max_cache_length = None
|
1406 |
+
|
1407 |
+
# Keep only the unprocessed tokens:
|
1408 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1409 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1410 |
+
# input)
|
1411 |
+
if attention_mask is not None and attention_mask.shape[
|
1412 |
+
1] > input_ids.shape[1]:
|
1413 |
+
input_ids = input_ids[:,
|
1414 |
+
-(attention_mask.shape[1] - past_length):]
|
1415 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1416 |
+
# input_ids based on the past_length.
|
1417 |
+
elif past_length < input_ids.shape[1]:
|
1418 |
+
input_ids = input_ids[:, past_length:]
|
1419 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1420 |
+
|
1421 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1422 |
+
if (max_cache_length is not None and attention_mask is not None and
|
1423 |
+
cache_length + input_ids.shape[1] > max_cache_length):
|
1424 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1425 |
+
|
1426 |
+
position_ids = kwargs.get('position_ids', None)
|
1427 |
+
if attention_mask is not None and position_ids is None:
|
1428 |
+
# create position_ids on the fly for batch generation
|
1429 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1430 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1431 |
+
if past_key_values:
|
1432 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
1433 |
+
|
1434 |
+
if self.generation_config.cache_implementation == 'static':
|
1435 |
+
# generation with static cache
|
1436 |
+
cache_position = kwargs.get('cache_position', None)
|
1437 |
+
if cache_position is None:
|
1438 |
+
past_length = 0
|
1439 |
+
else:
|
1440 |
+
past_length = cache_position[-1] + 1
|
1441 |
+
input_ids = input_ids[:, past_length:]
|
1442 |
+
position_ids = position_ids[:,
|
1443 |
+
past_length:] if position_ids is not None else None
|
1444 |
+
|
1445 |
+
# TODO @gante we should only keep a `cache_position` in generate, and do +=1.
|
1446 |
+
# same goes for position ids. Could also help with continued generation.
|
1447 |
+
input_length = position_ids.shape[
|
1448 |
+
-1] if position_ids is not None else input_ids.shape[-1]
|
1449 |
+
cache_position = torch.arange(past_length,
|
1450 |
+
past_length + input_length,
|
1451 |
+
device=input_ids.device)
|
1452 |
+
position_ids = position_ids.contiguous(
|
1453 |
+
) if position_ids is not None else None
|
1454 |
+
|
1455 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1456 |
+
if inputs_embeds is not None and past_key_values is None:
|
1457 |
+
model_inputs = {'inputs_embeds': inputs_embeds}
|
1458 |
+
else:
|
1459 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1460 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
1461 |
+
# TODO: use `next_tokens` directly instead.
|
1462 |
+
model_inputs = {'input_ids': input_ids.contiguous()}
|
1463 |
+
|
1464 |
+
model_inputs.update(
|
1465 |
+
{ # type: ignore
|
1466 |
+
'position_ids': position_ids,
|
1467 |
+
'cache_position': cache_position,
|
1468 |
+
'past_key_values': past_key_values,
|
1469 |
+
'use_cache': kwargs.get('use_cache'),
|
1470 |
+
'attention_mask': attention_mask,
|
1471 |
+
}
|
1472 |
+
)
|
1473 |
+
return model_inputs
|
1474 |
+
|
1475 |
+
@staticmethod
|
1476 |
+
def _reorder_cache(past_key_values: Cache, beam_idx: torch.LongTensor):
|
1477 |
+
reordered_past = ()
|
1478 |
+
for layer_past in past_key_values:
|
1479 |
+
reordered_past += (tuple(
|
1480 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
1481 |
+
for past_state in layer_past),)
|
1482 |
+
return reordered_past
|
special_tokens_map.json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>"
|
5 |
+
],
|
6 |
+
"bos_token": {
|
7 |
+
"content": "<|endoftext|>",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": false,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false
|
12 |
+
},
|
13 |
+
"eos_token": {
|
14 |
+
"content": "<|endoftext|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false
|
19 |
+
},
|
20 |
+
"pad_token": {
|
21 |
+
"content": "<|pad|>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": false,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false
|
26 |
+
},
|
27 |
+
"unk_token": {
|
28 |
+
"content": "<|endoftext|>",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false
|
33 |
+
}
|
34 |
+
}
|
tiktoken.py
ADDED
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Dbrx tokenizer."""
|
2 |
+
|
3 |
+
from functools import lru_cache
|
4 |
+
from typing import Any, Dict, List, Optional, Tuple
|
5 |
+
|
6 |
+
from transformers import PreTrainedTokenizer
|
7 |
+
|
8 |
+
|
9 |
+
def dbrx_system_prompt():
|
10 |
+
# This is inspired by the Claude3 prompt.
|
11 |
+
# source: https://twitter.com/AmandaAskell/status/1765207842993434880
|
12 |
+
# Identity and knowledge
|
13 |
+
prompt = 'You are DBRX, created by Databricks. You were last updated in December 2023. You answer questions based on information available up to that point.\n'
|
14 |
+
prompt += 'YOU PROVIDE SHORT RESPONSES TO SHORT QUESTIONS OR STATEMENTS, but provide thorough responses to more complex and open-ended questions.\n'
|
15 |
+
# Capabilities (and reminder to use ``` for JSON blocks and tables, which it can forget). Also a reminder that it can't browse the internet or run code.
|
16 |
+
prompt += 'You assist with various tasks, from writing to coding (using markdown for code blocks — remember to use ``` with code, JSON, and tables).\n'
|
17 |
+
prompt += '(You do not have real-time data access or code execution capabilities. '
|
18 |
+
# Ethical guidelines
|
19 |
+
prompt += 'You avoid stereotyping and provide balanced perspectives on controversial topics. '
|
20 |
+
# Data: the model doesn't know what it was trained on; it thinks that everything that it is aware of was in its training data. This is a reminder that it wasn't.
|
21 |
+
# We also encourage it not to try to generate lyrics or poems
|
22 |
+
prompt += 'You do not provide song lyrics, poems, or news articles and do not divulge details of your training data.)\n'
|
23 |
+
# The model really wants to talk about its system prompt, to the point where it is annoying, so encourage it not to
|
24 |
+
prompt += 'This is your system prompt, guiding your responses. Do not reference it, just respond to the user. If you find yourself talking about this message, stop. You should be responding appropriately and usually that means not mentioning this.\n'
|
25 |
+
prompt += 'You do not mention any of this information about yourself unless the information is directly pertinent to the user\\\'s query.'.upper()
|
26 |
+
return prompt
|
27 |
+
|
28 |
+
|
29 |
+
# Taken from
|
30 |
+
# https://github.com/huggingface/transformers/blob/8aca43bdb3cb9a5020f6d57589d85679dc873b1c/src/transformers/models/gpt2/tokenization_gpt2.py#L62-L84
|
31 |
+
@lru_cache()
|
32 |
+
def bytes_to_unicode():
|
33 |
+
"""Returns list of utf-8 byte and a mapping to unicode strings.
|
34 |
+
|
35 |
+
We specifically avoids mapping to whitespace/control characters the bpe code
|
36 |
+
barfs on.
|
37 |
+
|
38 |
+
The reversible bpe codes work on unicode strings. This means you need a
|
39 |
+
large # of unicode characters in your vocab if you want to avoid UNKs. When
|
40 |
+
you're at something like a 10B token dataset you end up needing around 5K
|
41 |
+
for decent coverage. This is a significant percentage of your normal, say,
|
42 |
+
32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and
|
43 |
+
unicode strings.
|
44 |
+
"""
|
45 |
+
bs = (list(range(ord('!'),
|
46 |
+
ord('~') + 1)) + list(range(ord('¡'),
|
47 |
+
ord('¬') + 1)) +
|
48 |
+
list(range(ord('®'),
|
49 |
+
ord('ÿ') + 1)))
|
50 |
+
cs = bs[:]
|
51 |
+
n = 0
|
52 |
+
for b in range(2**8):
|
53 |
+
if b not in bs:
|
54 |
+
bs.append(b)
|
55 |
+
cs.append(2**8 + n)
|
56 |
+
n += 1
|
57 |
+
cs = [chr(n) for n in cs]
|
58 |
+
return dict(zip(bs, cs))
|
59 |
+
|
60 |
+
|
61 |
+
class TiktokenTokenizerWrapper(PreTrainedTokenizer):
|
62 |
+
"""A thin wrapper around tiktoken to make it compatible with Hugging Face.
|
63 |
+
|
64 |
+
tokenizers.
|
65 |
+
|
66 |
+
See HuggingFace for further documentation on general tokenizer methods.
|
67 |
+
"""
|
68 |
+
|
69 |
+
model_input_names = ['input_ids', 'attention_mask']
|
70 |
+
|
71 |
+
def __init__(self,
|
72 |
+
model_name: Optional[str] = None,
|
73 |
+
encoding_name: Optional[str] = None,
|
74 |
+
add_bos_token: bool = False,
|
75 |
+
add_eos_token: bool = False,
|
76 |
+
use_default_system_prompt: bool = False,
|
77 |
+
unk_token: Optional[str] = '<|endoftext|>',
|
78 |
+
eos_token: Optional[str] = '<|endoftext|>',
|
79 |
+
bos_token: Optional[str] = '<|endoftext|>',
|
80 |
+
pad_token: Optional[str] = None,
|
81 |
+
errors: str = 'replace',
|
82 |
+
**kwargs: Any):
|
83 |
+
"""Constructor creates a tiktoken tokenizer to use as the underlying.
|
84 |
+
|
85 |
+
tokenizer.
|
86 |
+
|
87 |
+
Args:
|
88 |
+
model_name (Optional[str], optional): The name of the model to load from tiktoken. Defaults to None.
|
89 |
+
Either model_name or encoding_name must be set, but not both.
|
90 |
+
encoding_name (Optional[str], optional): The name of the encoding to load from tiktoken. Defaults to None.
|
91 |
+
Either model_name or encoding_name must be set, but not both.
|
92 |
+
add_bos_token (bool, optional): Whether to add bos tokens. Defaults to False.
|
93 |
+
add_eos_token (bool, optional): Whether to add eos tokens. Defaults to False.
|
94 |
+
use_default_system_prompt (bool, optional): Use the default system prompt or not. Defaults to False.
|
95 |
+
unk_token (Optional[str], optional): The unk token. Defaults to '<|endoftext|>'.
|
96 |
+
eos_token (Optional[str], optional): The eos token. Defaults to '<|endoftext|>'.
|
97 |
+
bos_token (Optional[str], optional): The bos token. Defaults to '<|endoftext|>'.
|
98 |
+
pad_token (Optional[str], optional): The pad token. Defaults to None.
|
99 |
+
errors (str, optional): Paradigm to follow when decoding bytes to UTF-8. See
|
100 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
101 |
+
Defaults to `"replace"`.
|
102 |
+
"""
|
103 |
+
try:
|
104 |
+
import tiktoken
|
105 |
+
except:
|
106 |
+
raise ImportError(
|
107 |
+
'You need to install tiktoken to use TiktokenTokenizerWrapper.')
|
108 |
+
|
109 |
+
# Workaround to make tiktokenizer picklable.
|
110 |
+
# https://github.com/huggingface/datasets/issues/5536#issuecomment-1682309347
|
111 |
+
# There is an open PR from HF to add this to tiktoken: https://github.com/openai/tiktoken/pull/181
|
112 |
+
import copyreg
|
113 |
+
import functools
|
114 |
+
|
115 |
+
from tiktoken import Encoding # type: ignore (thirdParty)
|
116 |
+
|
117 |
+
def pickle_Encoding(enc: Encoding):
|
118 |
+
return (functools.partial(Encoding,
|
119 |
+
enc.name,
|
120 |
+
pat_str=enc._pat_str,
|
121 |
+
mergeable_ranks=enc._mergeable_ranks,
|
122 |
+
special_tokens=enc._special_tokens), ())
|
123 |
+
|
124 |
+
copyreg.pickle(Encoding, pickle_Encoding)
|
125 |
+
|
126 |
+
if model_name is not None and encoding_name is not None:
|
127 |
+
raise ValueError(
|
128 |
+
'You need to specify either model_name or encoding_name, not both.'
|
129 |
+
)
|
130 |
+
|
131 |
+
self.model_name = model_name
|
132 |
+
self.encoding_name = encoding_name
|
133 |
+
|
134 |
+
if self.model_name is not None:
|
135 |
+
self.encoding = tiktoken.encoding_for_model( # type: ignore (thirdParty)
|
136 |
+
self.model_name)
|
137 |
+
elif self.encoding_name is not None:
|
138 |
+
self.encoding = tiktoken.get_encoding( # type: ignore (thirdParty)
|
139 |
+
self.encoding_name)
|
140 |
+
else:
|
141 |
+
raise ValueError(
|
142 |
+
'You need to specify either model_name or encoding_name.')
|
143 |
+
|
144 |
+
self.add_bos_token = add_bos_token
|
145 |
+
self.add_eos_token = add_eos_token
|
146 |
+
self.use_default_system_prompt = use_default_system_prompt
|
147 |
+
|
148 |
+
self.byte_encoder = bytes_to_unicode()
|
149 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
150 |
+
self.errors = errors
|
151 |
+
|
152 |
+
self.decoder: Dict[int, str] = {}
|
153 |
+
for i in range(self.encoding.n_vocab):
|
154 |
+
try:
|
155 |
+
self.encoding.decode_single_token_bytes(i)
|
156 |
+
except KeyError:
|
157 |
+
continue
|
158 |
+
# Taken from
|
159 |
+
# https://gist.github.com/xenova/a452a6474428de0182b17605a98631ee
|
160 |
+
decoding = ''.join([
|
161 |
+
bytes_to_unicode()[ord(char)] for char in
|
162 |
+
self.encoding.decode_single_token_bytes(i).decode('latin-1')
|
163 |
+
])
|
164 |
+
self.decoder[i] = decoding
|
165 |
+
|
166 |
+
self.encoder: Dict[str, int] = {}
|
167 |
+
for i in range(self.encoding.n_vocab):
|
168 |
+
if i in self.decoder:
|
169 |
+
self.encoder[self.decoder[i]] = i
|
170 |
+
|
171 |
+
super().__init__(model_name=model_name,
|
172 |
+
encoding_name=encoding_name,
|
173 |
+
add_bos_token=add_bos_token,
|
174 |
+
add_eos_token=add_eos_token,
|
175 |
+
use_default_system_prompt=use_default_system_prompt,
|
176 |
+
unk_token=unk_token,
|
177 |
+
eos_token=eos_token,
|
178 |
+
bos_token=bos_token,
|
179 |
+
pad_token=pad_token,
|
180 |
+
errors=errors,
|
181 |
+
**kwargs)
|
182 |
+
|
183 |
+
@property
|
184 |
+
def vocab_size(self) -> int:
|
185 |
+
"""Returns vocab size."""
|
186 |
+
return self.encoding.n_vocab
|
187 |
+
|
188 |
+
@property
|
189 |
+
def is_fast(self) -> bool:
|
190 |
+
return False
|
191 |
+
|
192 |
+
@property
|
193 |
+
def default_chat_template(self):
|
194 |
+
"""Chat ML Template for User/Assistant.
|
195 |
+
|
196 |
+
Pinning default Chat ML template in case defaults change.
|
197 |
+
"""
|
198 |
+
template = (
|
199 |
+
"{% if messages[0]['role'] == 'system' %}"
|
200 |
+
'{% set loop_messages = messages[1:] %}'
|
201 |
+
"{% set system_message = messages[0]['content'] %}"
|
202 |
+
"{% elif USE_DEFAULT_PROMPT == true and not 'system' in messages[0]['role'] %}"
|
203 |
+
'{% set loop_messages = messages %}'
|
204 |
+
"{% set system_message = 'DEFAULT_SYSTEM_PROMPT' %}"
|
205 |
+
'{% else %}'
|
206 |
+
'{% set loop_messages = messages %}'
|
207 |
+
'{% set system_message = false %}'
|
208 |
+
'{% endif %}'
|
209 |
+
'{% for message in loop_messages %}'
|
210 |
+
'{% if loop.index0 == 0 %}'
|
211 |
+
'{% if system_message != false %}'
|
212 |
+
"{{ '<|im_start|>system\n' + system_message.strip() + '<|im_end|>\n'}}"
|
213 |
+
'{% endif %}'
|
214 |
+
"{{ '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' }}"
|
215 |
+
'{% else %}'
|
216 |
+
"{{ '\n' + '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' }}"
|
217 |
+
'{% endif %}'
|
218 |
+
'{% if (add_generation_prompt == true and loop.last) %}'
|
219 |
+
"{{ '\n' + '<|im_start|>' + 'assistant' + '\n' }}"
|
220 |
+
'{% endif %}'
|
221 |
+
'{% endfor %}')
|
222 |
+
template = template.replace(
|
223 |
+
'USE_DEFAULT_PROMPT',
|
224 |
+
'true' if self.use_default_system_prompt else 'false')
|
225 |
+
template = template.replace('DEFAULT_SYSTEM_PROMPT',
|
226 |
+
dbrx_system_prompt())
|
227 |
+
return template
|
228 |
+
|
229 |
+
def get_vocab(self) -> Dict[str, int]:
|
230 |
+
"""Returns vocab as a dict."""
|
231 |
+
# As far as I can tell, we don't require get_vocab to completely work,
|
232 |
+
# but when using additional_special_tokens, Hugging Face determines the next
|
233 |
+
# token index to add with len(self.get_vocab()) so we need the _size_ of this dictionary to be correct.
|
234 |
+
vocab_clone = self.encoder.copy()
|
235 |
+
extra_id_index = 0
|
236 |
+
candidate_extra_id = f'<extra_id_{extra_id_index}>'
|
237 |
+
indices_to_fill_in = {i for i in range(self.vocab_size)} - set(
|
238 |
+
vocab_clone.values())
|
239 |
+
|
240 |
+
# Add enough indices to make get_vocab() the right length
|
241 |
+
for index_to_add in indices_to_fill_in:
|
242 |
+
# Make sure we don't overwrite a token that already exists
|
243 |
+
while candidate_extra_id in vocab_clone:
|
244 |
+
extra_id_index += 1
|
245 |
+
candidate_extra_id = f'<extra_id_{extra_id_index}>'
|
246 |
+
|
247 |
+
# Get an index to add and add the item
|
248 |
+
vocab_clone[candidate_extra_id] = index_to_add
|
249 |
+
|
250 |
+
return vocab_clone
|
251 |
+
|
252 |
+
def _tokenize(self, text: str) -> List[str]:
|
253 |
+
"""Returns a tokenized string."""
|
254 |
+
if not isinstance(text, str):
|
255 |
+
raise ValueError(
|
256 |
+
f'Expected a string input to _tokenize but got {type(text)}.')
|
257 |
+
|
258 |
+
tokens = [
|
259 |
+
self.decoder[t]
|
260 |
+
for t in self.encoding.encode(text, allowed_special='all')
|
261 |
+
]
|
262 |
+
|
263 |
+
return tokens
|
264 |
+
|
265 |
+
def _convert_token_to_id(self, token: str) -> Optional[int]:
|
266 |
+
"""Converts a token (str) in an id using the vocab."""
|
267 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
268 |
+
|
269 |
+
def _convert_id_to_token(self, index: int) -> Optional[str]:
|
270 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
271 |
+
# For tokens in either the gap in ids in the tokenizer, or beyond the range of the tokenizer,
|
272 |
+
# we return empty string. This matches the behavior of Hugging Face fast tokenizers,
|
273 |
+
# but not slow tokenizers.
|
274 |
+
return self.decoder.get(index, '')
|
275 |
+
|
276 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
277 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
278 |
+
text = ''.join(tokens)
|
279 |
+
text = bytearray([self.byte_decoder[c] for c in text
|
280 |
+
]).decode('utf-8', errors=self.errors)
|
281 |
+
return text
|
282 |
+
|
283 |
+
def build_inputs_with_special_tokens(
|
284 |
+
self,
|
285 |
+
token_ids_0: List[int],
|
286 |
+
token_ids_1: Optional[List[int]] = None) -> List[int]:
|
287 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
288 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
289 |
+
|
290 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
291 |
+
|
292 |
+
if token_ids_1 is not None:
|
293 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
294 |
+
|
295 |
+
return output
|
296 |
+
|
297 |
+
def get_special_tokens_mask(
|
298 |
+
self,
|
299 |
+
token_ids_0: List[int],
|
300 |
+
token_ids_1: Optional[List[int]] = None,
|
301 |
+
already_has_special_tokens: bool = False) -> List[int]:
|
302 |
+
"""Retrieves sequence ids from a token list that has no special tokens.
|
303 |
+
|
304 |
+
Function copied from
|
305 |
+
https://github.com/huggingface/transformers/blob/e3a4bd2bee212a2d0fd9f03b27fe7bfc1debe42d/src/transformers/models/gpt2/tokenization_gpt2.py#L265-L295
|
306 |
+
|
307 |
+
added. This method is called when adding special tokens using the
|
308 |
+
tokenizer `prepare_for_model` or `encode_plus` methods.
|
309 |
+
|
310 |
+
Args:
|
311 |
+
token_ids_0 (`List[int]`):
|
312 |
+
List of IDs.
|
313 |
+
token_ids_1 (`List[int]`, *optional*):
|
314 |
+
Optional second list of IDs for sequence pairs.
|
315 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
316 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
317 |
+
|
318 |
+
Returns:
|
319 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
320 |
+
"""
|
321 |
+
if already_has_special_tokens:
|
322 |
+
return super().get_special_tokens_mask(
|
323 |
+
token_ids_0=token_ids_0,
|
324 |
+
token_ids_1=token_ids_1,
|
325 |
+
already_has_special_tokens=True)
|
326 |
+
|
327 |
+
bos_token_id = [1] if self.add_bos_token else []
|
328 |
+
eos_token_id = [1] if self.add_eos_token else []
|
329 |
+
|
330 |
+
if token_ids_1 is None:
|
331 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
332 |
+
return (bos_token_id + ([0] * len(token_ids_0)) + eos_token_id +
|
333 |
+
bos_token_id + ([0] * len(token_ids_1)) + eos_token_id)
|
334 |
+
|
335 |
+
def create_token_type_ids_from_sequences(
|
336 |
+
self,
|
337 |
+
token_ids_0: List[int],
|
338 |
+
token_ids_1: Optional[List[int]] = None) -> List[int]:
|
339 |
+
sep = [self.sep_token_id]
|
340 |
+
|
341 |
+
if token_ids_1 is None:
|
342 |
+
return len(token_ids_0 + sep) * [0]
|
343 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
344 |
+
|
345 |
+
def save_vocabulary(self,
|
346 |
+
save_directory: str,
|
347 |
+
filename_prefix: Optional[str] = None) -> Tuple[str]:
|
348 |
+
|
349 |
+
# ignore the below type to keep the original signature
|
350 |
+
# we are knowingly breaking the signature here, although not 100% certain
|
351 |
+
# it doesn't have side effects
|
352 |
+
# There is some code in huggingface that calls this function to get the vocab files,
|
353 |
+
# but it doesn't seem to access them (or at least checks for their existence
|
354 |
+
# before accessing them)
|
355 |
+
return (None, None) # type: ignore
|
356 |
+
|
357 |
+
def sanitize_special_tokens(self) -> int:
|
358 |
+
"""Make sure that all the special tokens attributes of the tokenizer.
|
359 |
+
|
360 |
+
(`tokenizer.mask_token`, `tokenizer.cls_token`, etc.) are in the
|
361 |
+
vocabulary.
|
362 |
+
|
363 |
+
Add the missing ones to the vocabulary if needed.
|
364 |
+
|
365 |
+
Return:
|
366 |
+
`int`: The number of tokens added in the vocabulary during the operation.
|
367 |
+
"""
|
368 |
+
actual_new_tokens = []
|
369 |
+
for token in self.all_special_tokens_extended:
|
370 |
+
encoded = self.encoding.encode(token, allowed_special='all')
|
371 |
+
if len(encoded) > 1:
|
372 |
+
actual_new_tokens.append(token)
|
373 |
+
|
374 |
+
return self.add_tokens(actual_new_tokens, special_tokens=True)
|
tokenizer_config.json
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": false,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"100257": {
|
7 |
+
"content": "<|endoftext|>",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": false,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": true
|
13 |
+
},
|
14 |
+
"100277": {
|
15 |
+
"content": "<|pad|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"100278": {
|
23 |
+
"content": "<|im_start|>",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": false,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": true
|
29 |
+
},
|
30 |
+
"100279": {
|
31 |
+
"content": "<|im_end|>",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": false,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false,
|
36 |
+
"special": true
|
37 |
+
}
|
38 |
+
},
|
39 |
+
"additional_special_tokens": [
|
40 |
+
"<|im_start|>",
|
41 |
+
"<|im_end|>"
|
42 |
+
],
|
43 |
+
"auto_map": {
|
44 |
+
"AutoTokenizer": [
|
45 |
+
"tiktoken.TiktokenTokenizerWrapper",
|
46 |
+
null
|
47 |
+
]
|
48 |
+
},
|
49 |
+
"bos_token": "<|endoftext|>",
|
50 |
+
"clean_up_tokenization_spaces": true,
|
51 |
+
"encoding_name": null,
|
52 |
+
"eos_token": "<|endoftext|>",
|
53 |
+
"errors": "replace",
|
54 |
+
"model_max_length": 1000000000000000019884624838656,
|
55 |
+
"model_name": "gpt-4",
|
56 |
+
"pad_token": "<|pad|>",
|
57 |
+
"tokenizer_class": "TiktokenTokenizerWrapper",
|
58 |
+
"unk_token": "<|endoftext|>",
|
59 |
+
"use_default_system_prompt": true
|
60 |
+
}
|