ChuckMcSneed
commited on
Commit
•
8f4110e
1
Parent(s):
14cd8c8
Upload 12 files
Browse files- added_tokens.json +4 -0
- config.json +36 -0
- configuration_dbrx.py +264 -0
- generation_config.json +8 -0
- merges.txt +0 -0
- model.safetensors.index.json +330 -0
- modeling_dbrx.py +1482 -0
- special_tokens_map.json +34 -0
- tiktoken.py +374 -0
- tokenizer.json +0 -0
- tokenizer_config.json +55 -0
- vocab.json +0 -0
added_tokens.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<|im_end|>": 100278,
|
3 |
+
"<|im_start|>": 100277
|
4 |
+
}
|
config.json
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"DbrxForCausalLM"
|
4 |
+
],
|
5 |
+
"attn_config": {
|
6 |
+
"clip_qkv": 8,
|
7 |
+
"kv_n_heads": 8,
|
8 |
+
"model_type": "",
|
9 |
+
"rope_theta": 500000
|
10 |
+
},
|
11 |
+
"d_model": 6144,
|
12 |
+
"emb_pdrop": 0.0,
|
13 |
+
"ffn_config": {
|
14 |
+
"ffn_hidden_size": 10752,
|
15 |
+
"model_type": "",
|
16 |
+
"moe_jitter_eps": 0,
|
17 |
+
"moe_loss_weight": 0.05,
|
18 |
+
"moe_num_experts": 16,
|
19 |
+
"moe_top_k": 4,
|
20 |
+
"ffn_act_fn": {
|
21 |
+
"name": "silu"
|
22 |
+
}
|
23 |
+
},
|
24 |
+
"initializer_range": 0.02,
|
25 |
+
"max_seq_len": 32768,
|
26 |
+
"model_type": "dbrx",
|
27 |
+
"n_heads": 48,
|
28 |
+
"n_layers": 40,
|
29 |
+
"output_router_logits": false,
|
30 |
+
"resid_pdrop": 0.0,
|
31 |
+
"tie_word_embeddings": false,
|
32 |
+
"torch_dtype": "bfloat16",
|
33 |
+
"transformers_version": "4.40.0",
|
34 |
+
"use_cache": true,
|
35 |
+
"vocab_size": 100352
|
36 |
+
}
|
configuration_dbrx.py
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Dbrx configuration."""
|
2 |
+
from typing import Any, Optional
|
3 |
+
|
4 |
+
from transformers.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 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"eos_token_id": [
|
4 |
+
100257,
|
5 |
+
100279
|
6 |
+
],
|
7 |
+
"transformers_version": "4.40.0.dev0"
|
8 |
+
}
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 263193047040
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"transformer.blocks.0.ffn.experts.mlp.v1": "model-00001-of-00061.safetensors",
|
7 |
+
"transformer.blocks.0.ffn.experts.mlp.w1": "model-00001-of-00061.safetensors",
|
8 |
+
"transformer.blocks.0.ffn.experts.mlp.w2": "model-00002-of-00061.safetensors",
|
9 |
+
"lm_head.weight": "model-00002-of-00061.safetensors",
|
10 |
+
"transformer.blocks.0.ffn.router.layer.weight": "model-00002-of-00061.safetensors",
|
11 |
+
"transformer.blocks.0.norm_attn_norm.attn.Wqkv.weight": "model-00002-of-00061.safetensors",
|
12 |
+
"transformer.blocks.0.norm_attn_norm.attn.out_proj.weight": "model-00002-of-00061.safetensors",
|
13 |
+
"transformer.blocks.0.norm_attn_norm.norm_1.weight": "model-00002-of-00061.safetensors",
|
14 |
+
"transformer.blocks.0.norm_attn_norm.norm_2.weight": "model-00002-of-00061.safetensors",
|
15 |
+
"transformer.norm_f.weight": "model-00002-of-00061.safetensors",
|
16 |
+
"transformer.wte.weight": "model-00002-of-00061.safetensors",
|
17 |
+
"transformer.blocks.1.ffn.experts.mlp.v1": "model-00003-of-00061.safetensors",
|
18 |
+
"transformer.blocks.1.ffn.experts.mlp.w1": "model-00003-of-00061.safetensors",
|
19 |
+
"transformer.blocks.1.ffn.experts.mlp.w2": "model-00004-of-00061.safetensors",
|
20 |
+
"transformer.blocks.1.ffn.router.layer.weight": "model-00004-of-00061.safetensors",
|
21 |
+
"transformer.blocks.1.norm_attn_norm.attn.Wqkv.weight": "model-00004-of-00061.safetensors",
|
22 |
+
"transformer.blocks.1.norm_attn_norm.attn.out_proj.weight": "model-00004-of-00061.safetensors",
|
23 |
+
"transformer.blocks.1.norm_attn_norm.norm_1.weight": "model-00004-of-00061.safetensors",
|
24 |
+
"transformer.blocks.1.norm_attn_norm.norm_2.weight": "model-00004-of-00061.safetensors",
|
25 |
+
"transformer.blocks.2.ffn.experts.mlp.v1": "model-00004-of-00061.safetensors",
|
26 |
+
"transformer.blocks.2.ffn.experts.mlp.w1": "model-00005-of-00061.safetensors",
|
27 |
+
"transformer.blocks.2.ffn.experts.mlp.w2": "model-00005-of-00061.safetensors",
|
28 |
+
"transformer.blocks.2.ffn.router.layer.weight": "model-00005-of-00061.safetensors",
|
29 |
+
"transformer.blocks.2.norm_attn_norm.attn.Wqkv.weight": "model-00005-of-00061.safetensors",
|
30 |
+
"transformer.blocks.2.norm_attn_norm.attn.out_proj.weight": "model-00005-of-00061.safetensors",
|
31 |
+
"transformer.blocks.2.norm_attn_norm.norm_1.weight": "model-00005-of-00061.safetensors",
|
32 |
+
"transformer.blocks.2.norm_attn_norm.norm_2.weight": "model-00005-of-00061.safetensors",
|
33 |
+
"transformer.blocks.3.ffn.experts.mlp.v1": "model-00006-of-00061.safetensors",
|
34 |
+
"transformer.blocks.3.ffn.experts.mlp.w1": "model-00006-of-00061.safetensors",
|
35 |
+
"transformer.blocks.3.ffn.experts.mlp.w2": "model-00007-of-00061.safetensors",
|
36 |
+
"transformer.blocks.3.ffn.router.layer.weight": "model-00007-of-00061.safetensors",
|
37 |
+
"transformer.blocks.3.norm_attn_norm.attn.Wqkv.weight": "model-00007-of-00061.safetensors",
|
38 |
+
"transformer.blocks.3.norm_attn_norm.attn.out_proj.weight": "model-00007-of-00061.safetensors",
|
39 |
+
"transformer.blocks.3.norm_attn_norm.norm_1.weight": "model-00007-of-00061.safetensors",
|
40 |
+
"transformer.blocks.3.norm_attn_norm.norm_2.weight": "model-00007-of-00061.safetensors",
|
41 |
+
"transformer.blocks.4.ffn.experts.mlp.v1": "model-00007-of-00061.safetensors",
|
42 |
+
"transformer.blocks.4.ffn.experts.mlp.w1": "model-00008-of-00061.safetensors",
|
43 |
+
"transformer.blocks.4.ffn.experts.mlp.w2": "model-00008-of-00061.safetensors",
|
44 |
+
"transformer.blocks.4.ffn.router.layer.weight": "model-00008-of-00061.safetensors",
|
45 |
+
"transformer.blocks.4.norm_attn_norm.attn.Wqkv.weight": "model-00008-of-00061.safetensors",
|
46 |
+
"transformer.blocks.4.norm_attn_norm.attn.out_proj.weight": "model-00008-of-00061.safetensors",
|
47 |
+
"transformer.blocks.4.norm_attn_norm.norm_1.weight": "model-00008-of-00061.safetensors",
|
48 |
+
"transformer.blocks.4.norm_attn_norm.norm_2.weight": "model-00008-of-00061.safetensors",
|
49 |
+
"transformer.blocks.5.ffn.experts.mlp.v1": "model-00009-of-00061.safetensors",
|
50 |
+
"transformer.blocks.5.ffn.experts.mlp.w1": "model-00009-of-00061.safetensors",
|
51 |
+
"transformer.blocks.5.ffn.experts.mlp.w2": "model-00010-of-00061.safetensors",
|
52 |
+
"transformer.blocks.5.ffn.router.layer.weight": "model-00010-of-00061.safetensors",
|
53 |
+
"transformer.blocks.5.norm_attn_norm.attn.Wqkv.weight": "model-00010-of-00061.safetensors",
|
54 |
+
"transformer.blocks.5.norm_attn_norm.attn.out_proj.weight": "model-00010-of-00061.safetensors",
|
55 |
+
"transformer.blocks.5.norm_attn_norm.norm_1.weight": "model-00010-of-00061.safetensors",
|
56 |
+
"transformer.blocks.5.norm_attn_norm.norm_2.weight": "model-00010-of-00061.safetensors",
|
57 |
+
"transformer.blocks.6.ffn.experts.mlp.v1": "model-00010-of-00061.safetensors",
|
58 |
+
"transformer.blocks.6.ffn.experts.mlp.w1": "model-00011-of-00061.safetensors",
|
59 |
+
"transformer.blocks.6.ffn.experts.mlp.w2": "model-00011-of-00061.safetensors",
|
60 |
+
"transformer.blocks.6.ffn.router.layer.weight": "model-00011-of-00061.safetensors",
|
61 |
+
"transformer.blocks.6.norm_attn_norm.attn.Wqkv.weight": "model-00011-of-00061.safetensors",
|
62 |
+
"transformer.blocks.6.norm_attn_norm.attn.out_proj.weight": "model-00011-of-00061.safetensors",
|
63 |
+
"transformer.blocks.6.norm_attn_norm.norm_1.weight": "model-00011-of-00061.safetensors",
|
64 |
+
"transformer.blocks.6.norm_attn_norm.norm_2.weight": "model-00011-of-00061.safetensors",
|
65 |
+
"transformer.blocks.7.ffn.experts.mlp.v1": "model-00012-of-00061.safetensors",
|
66 |
+
"transformer.blocks.7.ffn.experts.mlp.w1": "model-00012-of-00061.safetensors",
|
67 |
+
"transformer.blocks.7.ffn.experts.mlp.w2": "model-00013-of-00061.safetensors",
|
68 |
+
"transformer.blocks.7.ffn.router.layer.weight": "model-00013-of-00061.safetensors",
|
69 |
+
"transformer.blocks.7.norm_attn_norm.attn.Wqkv.weight": "model-00013-of-00061.safetensors",
|
70 |
+
"transformer.blocks.7.norm_attn_norm.attn.out_proj.weight": "model-00013-of-00061.safetensors",
|
71 |
+
"transformer.blocks.7.norm_attn_norm.norm_1.weight": "model-00013-of-00061.safetensors",
|
72 |
+
"transformer.blocks.7.norm_attn_norm.norm_2.weight": "model-00013-of-00061.safetensors",
|
73 |
+
"transformer.blocks.8.ffn.experts.mlp.v1": "model-00013-of-00061.safetensors",
|
74 |
+
"transformer.blocks.8.ffn.experts.mlp.w1": "model-00014-of-00061.safetensors",
|
75 |
+
"transformer.blocks.8.ffn.experts.mlp.w2": "model-00014-of-00061.safetensors",
|
76 |
+
"transformer.blocks.8.ffn.router.layer.weight": "model-00014-of-00061.safetensors",
|
77 |
+
"transformer.blocks.8.norm_attn_norm.attn.Wqkv.weight": "model-00014-of-00061.safetensors",
|
78 |
+
"transformer.blocks.8.norm_attn_norm.attn.out_proj.weight": "model-00014-of-00061.safetensors",
|
79 |
+
"transformer.blocks.8.norm_attn_norm.norm_1.weight": "model-00014-of-00061.safetensors",
|
80 |
+
"transformer.blocks.8.norm_attn_norm.norm_2.weight": "model-00014-of-00061.safetensors",
|
81 |
+
"transformer.blocks.9.ffn.experts.mlp.v1": "model-00015-of-00061.safetensors",
|
82 |
+
"transformer.blocks.9.ffn.experts.mlp.w1": "model-00015-of-00061.safetensors",
|
83 |
+
"transformer.blocks.9.ffn.experts.mlp.w2": "model-00016-of-00061.safetensors",
|
84 |
+
"transformer.blocks.9.ffn.router.layer.weight": "model-00016-of-00061.safetensors",
|
85 |
+
"transformer.blocks.9.norm_attn_norm.attn.Wqkv.weight": "model-00016-of-00061.safetensors",
|
86 |
+
"transformer.blocks.9.norm_attn_norm.attn.out_proj.weight": "model-00016-of-00061.safetensors",
|
87 |
+
"transformer.blocks.9.norm_attn_norm.norm_1.weight": "model-00016-of-00061.safetensors",
|
88 |
+
"transformer.blocks.9.norm_attn_norm.norm_2.weight": "model-00016-of-00061.safetensors",
|
89 |
+
"transformer.blocks.10.ffn.experts.mlp.v1": "model-00016-of-00061.safetensors",
|
90 |
+
"transformer.blocks.10.ffn.experts.mlp.w1": "model-00017-of-00061.safetensors",
|
91 |
+
"transformer.blocks.10.ffn.experts.mlp.w2": "model-00017-of-00061.safetensors",
|
92 |
+
"transformer.blocks.10.ffn.router.layer.weight": "model-00017-of-00061.safetensors",
|
93 |
+
"transformer.blocks.10.norm_attn_norm.attn.Wqkv.weight": "model-00017-of-00061.safetensors",
|
94 |
+
"transformer.blocks.10.norm_attn_norm.attn.out_proj.weight": "model-00017-of-00061.safetensors",
|
95 |
+
"transformer.blocks.10.norm_attn_norm.norm_1.weight": "model-00017-of-00061.safetensors",
|
96 |
+
"transformer.blocks.10.norm_attn_norm.norm_2.weight": "model-00017-of-00061.safetensors",
|
97 |
+
"transformer.blocks.11.ffn.experts.mlp.v1": "model-00018-of-00061.safetensors",
|
98 |
+
"transformer.blocks.11.ffn.experts.mlp.w1": "model-00018-of-00061.safetensors",
|
99 |
+
"transformer.blocks.11.ffn.experts.mlp.w2": "model-00019-of-00061.safetensors",
|
100 |
+
"transformer.blocks.11.ffn.router.layer.weight": "model-00019-of-00061.safetensors",
|
101 |
+
"transformer.blocks.11.norm_attn_norm.attn.Wqkv.weight": "model-00019-of-00061.safetensors",
|
102 |
+
"transformer.blocks.11.norm_attn_norm.attn.out_proj.weight": "model-00019-of-00061.safetensors",
|
103 |
+
"transformer.blocks.11.norm_attn_norm.norm_1.weight": "model-00019-of-00061.safetensors",
|
104 |
+
"transformer.blocks.11.norm_attn_norm.norm_2.weight": "model-00019-of-00061.safetensors",
|
105 |
+
"transformer.blocks.12.ffn.experts.mlp.v1": "model-00019-of-00061.safetensors",
|
106 |
+
"transformer.blocks.12.ffn.experts.mlp.w1": "model-00020-of-00061.safetensors",
|
107 |
+
"transformer.blocks.12.ffn.experts.mlp.w2": "model-00020-of-00061.safetensors",
|
108 |
+
"transformer.blocks.12.ffn.router.layer.weight": "model-00020-of-00061.safetensors",
|
109 |
+
"transformer.blocks.12.norm_attn_norm.attn.Wqkv.weight": "model-00020-of-00061.safetensors",
|
110 |
+
"transformer.blocks.12.norm_attn_norm.attn.out_proj.weight": "model-00020-of-00061.safetensors",
|
111 |
+
"transformer.blocks.12.norm_attn_norm.norm_1.weight": "model-00020-of-00061.safetensors",
|
112 |
+
"transformer.blocks.12.norm_attn_norm.norm_2.weight": "model-00020-of-00061.safetensors",
|
113 |
+
"transformer.blocks.13.ffn.experts.mlp.v1": "model-00021-of-00061.safetensors",
|
114 |
+
"transformer.blocks.13.ffn.experts.mlp.w1": "model-00021-of-00061.safetensors",
|
115 |
+
"transformer.blocks.13.ffn.experts.mlp.w2": "model-00022-of-00061.safetensors",
|
116 |
+
"transformer.blocks.13.ffn.router.layer.weight": "model-00022-of-00061.safetensors",
|
117 |
+
"transformer.blocks.13.norm_attn_norm.attn.Wqkv.weight": "model-00022-of-00061.safetensors",
|
118 |
+
"transformer.blocks.13.norm_attn_norm.attn.out_proj.weight": "model-00022-of-00061.safetensors",
|
119 |
+
"transformer.blocks.13.norm_attn_norm.norm_1.weight": "model-00022-of-00061.safetensors",
|
120 |
+
"transformer.blocks.13.norm_attn_norm.norm_2.weight": "model-00022-of-00061.safetensors",
|
121 |
+
"transformer.blocks.14.ffn.experts.mlp.v1": "model-00022-of-00061.safetensors",
|
122 |
+
"transformer.blocks.14.ffn.experts.mlp.w1": "model-00023-of-00061.safetensors",
|
123 |
+
"transformer.blocks.14.ffn.experts.mlp.w2": "model-00023-of-00061.safetensors",
|
124 |
+
"transformer.blocks.14.ffn.router.layer.weight": "model-00023-of-00061.safetensors",
|
125 |
+
"transformer.blocks.14.norm_attn_norm.attn.Wqkv.weight": "model-00023-of-00061.safetensors",
|
126 |
+
"transformer.blocks.14.norm_attn_norm.attn.out_proj.weight": "model-00023-of-00061.safetensors",
|
127 |
+
"transformer.blocks.14.norm_attn_norm.norm_1.weight": "model-00023-of-00061.safetensors",
|
128 |
+
"transformer.blocks.14.norm_attn_norm.norm_2.weight": "model-00023-of-00061.safetensors",
|
129 |
+
"transformer.blocks.15.ffn.experts.mlp.v1": "model-00024-of-00061.safetensors",
|
130 |
+
"transformer.blocks.15.ffn.experts.mlp.w1": "model-00024-of-00061.safetensors",
|
131 |
+
"transformer.blocks.15.ffn.experts.mlp.w2": "model-00025-of-00061.safetensors",
|
132 |
+
"transformer.blocks.15.ffn.router.layer.weight": "model-00025-of-00061.safetensors",
|
133 |
+
"transformer.blocks.15.norm_attn_norm.attn.Wqkv.weight": "model-00025-of-00061.safetensors",
|
134 |
+
"transformer.blocks.15.norm_attn_norm.attn.out_proj.weight": "model-00025-of-00061.safetensors",
|
135 |
+
"transformer.blocks.15.norm_attn_norm.norm_1.weight": "model-00025-of-00061.safetensors",
|
136 |
+
"transformer.blocks.15.norm_attn_norm.norm_2.weight": "model-00025-of-00061.safetensors",
|
137 |
+
"transformer.blocks.16.ffn.experts.mlp.v1": "model-00025-of-00061.safetensors",
|
138 |
+
"transformer.blocks.16.ffn.experts.mlp.w1": "model-00026-of-00061.safetensors",
|
139 |
+
"transformer.blocks.16.ffn.experts.mlp.w2": "model-00026-of-00061.safetensors",
|
140 |
+
"transformer.blocks.16.ffn.router.layer.weight": "model-00026-of-00061.safetensors",
|
141 |
+
"transformer.blocks.16.norm_attn_norm.attn.Wqkv.weight": "model-00026-of-00061.safetensors",
|
142 |
+
"transformer.blocks.16.norm_attn_norm.attn.out_proj.weight": "model-00026-of-00061.safetensors",
|
143 |
+
"transformer.blocks.16.norm_attn_norm.norm_1.weight": "model-00026-of-00061.safetensors",
|
144 |
+
"transformer.blocks.16.norm_attn_norm.norm_2.weight": "model-00026-of-00061.safetensors",
|
145 |
+
"transformer.blocks.17.ffn.experts.mlp.v1": "model-00027-of-00061.safetensors",
|
146 |
+
"transformer.blocks.17.ffn.experts.mlp.w1": "model-00027-of-00061.safetensors",
|
147 |
+
"transformer.blocks.17.ffn.experts.mlp.w2": "model-00028-of-00061.safetensors",
|
148 |
+
"transformer.blocks.17.ffn.router.layer.weight": "model-00028-of-00061.safetensors",
|
149 |
+
"transformer.blocks.17.norm_attn_norm.attn.Wqkv.weight": "model-00028-of-00061.safetensors",
|
150 |
+
"transformer.blocks.17.norm_attn_norm.attn.out_proj.weight": "model-00028-of-00061.safetensors",
|
151 |
+
"transformer.blocks.17.norm_attn_norm.norm_1.weight": "model-00028-of-00061.safetensors",
|
152 |
+
"transformer.blocks.17.norm_attn_norm.norm_2.weight": "model-00028-of-00061.safetensors",
|
153 |
+
"transformer.blocks.18.ffn.experts.mlp.v1": "model-00028-of-00061.safetensors",
|
154 |
+
"transformer.blocks.18.ffn.experts.mlp.w1": "model-00029-of-00061.safetensors",
|
155 |
+
"transformer.blocks.18.ffn.experts.mlp.w2": "model-00029-of-00061.safetensors",
|
156 |
+
"transformer.blocks.18.ffn.router.layer.weight": "model-00029-of-00061.safetensors",
|
157 |
+
"transformer.blocks.18.norm_attn_norm.attn.Wqkv.weight": "model-00029-of-00061.safetensors",
|
158 |
+
"transformer.blocks.18.norm_attn_norm.attn.out_proj.weight": "model-00029-of-00061.safetensors",
|
159 |
+
"transformer.blocks.18.norm_attn_norm.norm_1.weight": "model-00029-of-00061.safetensors",
|
160 |
+
"transformer.blocks.18.norm_attn_norm.norm_2.weight": "model-00029-of-00061.safetensors",
|
161 |
+
"transformer.blocks.19.ffn.experts.mlp.v1": "model-00030-of-00061.safetensors",
|
162 |
+
"transformer.blocks.19.ffn.experts.mlp.w1": "model-00030-of-00061.safetensors",
|
163 |
+
"transformer.blocks.19.ffn.experts.mlp.w2": "model-00031-of-00061.safetensors",
|
164 |
+
"transformer.blocks.19.ffn.router.layer.weight": "model-00031-of-00061.safetensors",
|
165 |
+
"transformer.blocks.19.norm_attn_norm.attn.Wqkv.weight": "model-00031-of-00061.safetensors",
|
166 |
+
"transformer.blocks.19.norm_attn_norm.attn.out_proj.weight": "model-00031-of-00061.safetensors",
|
167 |
+
"transformer.blocks.19.norm_attn_norm.norm_1.weight": "model-00031-of-00061.safetensors",
|
168 |
+
"transformer.blocks.19.norm_attn_norm.norm_2.weight": "model-00031-of-00061.safetensors",
|
169 |
+
"transformer.blocks.20.ffn.experts.mlp.v1": "model-00031-of-00061.safetensors",
|
170 |
+
"transformer.blocks.20.ffn.experts.mlp.w1": "model-00032-of-00061.safetensors",
|
171 |
+
"transformer.blocks.20.ffn.experts.mlp.w2": "model-00032-of-00061.safetensors",
|
172 |
+
"transformer.blocks.20.ffn.router.layer.weight": "model-00032-of-00061.safetensors",
|
173 |
+
"transformer.blocks.20.norm_attn_norm.attn.Wqkv.weight": "model-00032-of-00061.safetensors",
|
174 |
+
"transformer.blocks.20.norm_attn_norm.attn.out_proj.weight": "model-00032-of-00061.safetensors",
|
175 |
+
"transformer.blocks.20.norm_attn_norm.norm_1.weight": "model-00032-of-00061.safetensors",
|
176 |
+
"transformer.blocks.20.norm_attn_norm.norm_2.weight": "model-00032-of-00061.safetensors",
|
177 |
+
"transformer.blocks.21.ffn.experts.mlp.v1": "model-00033-of-00061.safetensors",
|
178 |
+
"transformer.blocks.21.ffn.experts.mlp.w1": "model-00033-of-00061.safetensors",
|
179 |
+
"transformer.blocks.21.ffn.experts.mlp.w2": "model-00034-of-00061.safetensors",
|
180 |
+
"transformer.blocks.21.ffn.router.layer.weight": "model-00034-of-00061.safetensors",
|
181 |
+
"transformer.blocks.21.norm_attn_norm.attn.Wqkv.weight": "model-00034-of-00061.safetensors",
|
182 |
+
"transformer.blocks.21.norm_attn_norm.attn.out_proj.weight": "model-00034-of-00061.safetensors",
|
183 |
+
"transformer.blocks.21.norm_attn_norm.norm_1.weight": "model-00034-of-00061.safetensors",
|
184 |
+
"transformer.blocks.21.norm_attn_norm.norm_2.weight": "model-00034-of-00061.safetensors",
|
185 |
+
"transformer.blocks.22.ffn.experts.mlp.v1": "model-00034-of-00061.safetensors",
|
186 |
+
"transformer.blocks.22.ffn.experts.mlp.w1": "model-00035-of-00061.safetensors",
|
187 |
+
"transformer.blocks.22.ffn.experts.mlp.w2": "model-00035-of-00061.safetensors",
|
188 |
+
"transformer.blocks.22.ffn.router.layer.weight": "model-00035-of-00061.safetensors",
|
189 |
+
"transformer.blocks.22.norm_attn_norm.attn.Wqkv.weight": "model-00035-of-00061.safetensors",
|
190 |
+
"transformer.blocks.22.norm_attn_norm.attn.out_proj.weight": "model-00035-of-00061.safetensors",
|
191 |
+
"transformer.blocks.22.norm_attn_norm.norm_1.weight": "model-00035-of-00061.safetensors",
|
192 |
+
"transformer.blocks.22.norm_attn_norm.norm_2.weight": "model-00035-of-00061.safetensors",
|
193 |
+
"transformer.blocks.23.ffn.experts.mlp.v1": "model-00036-of-00061.safetensors",
|
194 |
+
"transformer.blocks.23.ffn.experts.mlp.w1": "model-00036-of-00061.safetensors",
|
195 |
+
"transformer.blocks.23.ffn.experts.mlp.w2": "model-00037-of-00061.safetensors",
|
196 |
+
"transformer.blocks.23.ffn.router.layer.weight": "model-00037-of-00061.safetensors",
|
197 |
+
"transformer.blocks.23.norm_attn_norm.attn.Wqkv.weight": "model-00037-of-00061.safetensors",
|
198 |
+
"transformer.blocks.23.norm_attn_norm.attn.out_proj.weight": "model-00037-of-00061.safetensors",
|
199 |
+
"transformer.blocks.23.norm_attn_norm.norm_1.weight": "model-00037-of-00061.safetensors",
|
200 |
+
"transformer.blocks.23.norm_attn_norm.norm_2.weight": "model-00037-of-00061.safetensors",
|
201 |
+
"transformer.blocks.24.ffn.experts.mlp.v1": "model-00037-of-00061.safetensors",
|
202 |
+
"transformer.blocks.24.ffn.experts.mlp.w1": "model-00038-of-00061.safetensors",
|
203 |
+
"transformer.blocks.24.ffn.experts.mlp.w2": "model-00038-of-00061.safetensors",
|
204 |
+
"transformer.blocks.24.ffn.router.layer.weight": "model-00038-of-00061.safetensors",
|
205 |
+
"transformer.blocks.24.norm_attn_norm.attn.Wqkv.weight": "model-00038-of-00061.safetensors",
|
206 |
+
"transformer.blocks.24.norm_attn_norm.attn.out_proj.weight": "model-00038-of-00061.safetensors",
|
207 |
+
"transformer.blocks.24.norm_attn_norm.norm_1.weight": "model-00038-of-00061.safetensors",
|
208 |
+
"transformer.blocks.24.norm_attn_norm.norm_2.weight": "model-00038-of-00061.safetensors",
|
209 |
+
"transformer.blocks.25.ffn.experts.mlp.v1": "model-00039-of-00061.safetensors",
|
210 |
+
"transformer.blocks.25.ffn.experts.mlp.w1": "model-00039-of-00061.safetensors",
|
211 |
+
"transformer.blocks.25.ffn.experts.mlp.w2": "model-00040-of-00061.safetensors",
|
212 |
+
"transformer.blocks.25.ffn.router.layer.weight": "model-00040-of-00061.safetensors",
|
213 |
+
"transformer.blocks.25.norm_attn_norm.attn.Wqkv.weight": "model-00040-of-00061.safetensors",
|
214 |
+
"transformer.blocks.25.norm_attn_norm.attn.out_proj.weight": "model-00040-of-00061.safetensors",
|
215 |
+
"transformer.blocks.25.norm_attn_norm.norm_1.weight": "model-00040-of-00061.safetensors",
|
216 |
+
"transformer.blocks.25.norm_attn_norm.norm_2.weight": "model-00040-of-00061.safetensors",
|
217 |
+
"transformer.blocks.26.ffn.experts.mlp.v1": "model-00040-of-00061.safetensors",
|
218 |
+
"transformer.blocks.26.ffn.experts.mlp.w1": "model-00041-of-00061.safetensors",
|
219 |
+
"transformer.blocks.26.ffn.experts.mlp.w2": "model-00041-of-00061.safetensors",
|
220 |
+
"transformer.blocks.26.ffn.router.layer.weight": "model-00041-of-00061.safetensors",
|
221 |
+
"transformer.blocks.26.norm_attn_norm.attn.Wqkv.weight": "model-00041-of-00061.safetensors",
|
222 |
+
"transformer.blocks.26.norm_attn_norm.attn.out_proj.weight": "model-00041-of-00061.safetensors",
|
223 |
+
"transformer.blocks.26.norm_attn_norm.norm_1.weight": "model-00041-of-00061.safetensors",
|
224 |
+
"transformer.blocks.26.norm_attn_norm.norm_2.weight": "model-00041-of-00061.safetensors",
|
225 |
+
"transformer.blocks.27.ffn.experts.mlp.v1": "model-00042-of-00061.safetensors",
|
226 |
+
"transformer.blocks.27.ffn.experts.mlp.w1": "model-00042-of-00061.safetensors",
|
227 |
+
"transformer.blocks.27.ffn.experts.mlp.w2": "model-00043-of-00061.safetensors",
|
228 |
+
"transformer.blocks.27.ffn.router.layer.weight": "model-00043-of-00061.safetensors",
|
229 |
+
"transformer.blocks.27.norm_attn_norm.attn.Wqkv.weight": "model-00043-of-00061.safetensors",
|
230 |
+
"transformer.blocks.27.norm_attn_norm.attn.out_proj.weight": "model-00043-of-00061.safetensors",
|
231 |
+
"transformer.blocks.27.norm_attn_norm.norm_1.weight": "model-00043-of-00061.safetensors",
|
232 |
+
"transformer.blocks.27.norm_attn_norm.norm_2.weight": "model-00043-of-00061.safetensors",
|
233 |
+
"transformer.blocks.28.ffn.experts.mlp.v1": "model-00043-of-00061.safetensors",
|
234 |
+
"transformer.blocks.28.ffn.experts.mlp.w1": "model-00044-of-00061.safetensors",
|
235 |
+
"transformer.blocks.28.ffn.experts.mlp.w2": "model-00044-of-00061.safetensors",
|
236 |
+
"transformer.blocks.28.ffn.router.layer.weight": "model-00044-of-00061.safetensors",
|
237 |
+
"transformer.blocks.28.norm_attn_norm.attn.Wqkv.weight": "model-00044-of-00061.safetensors",
|
238 |
+
"transformer.blocks.28.norm_attn_norm.attn.out_proj.weight": "model-00044-of-00061.safetensors",
|
239 |
+
"transformer.blocks.28.norm_attn_norm.norm_1.weight": "model-00044-of-00061.safetensors",
|
240 |
+
"transformer.blocks.28.norm_attn_norm.norm_2.weight": "model-00044-of-00061.safetensors",
|
241 |
+
"transformer.blocks.29.ffn.experts.mlp.v1": "model-00045-of-00061.safetensors",
|
242 |
+
"transformer.blocks.29.ffn.experts.mlp.w1": "model-00045-of-00061.safetensors",
|
243 |
+
"transformer.blocks.29.ffn.experts.mlp.w2": "model-00046-of-00061.safetensors",
|
244 |
+
"transformer.blocks.29.ffn.router.layer.weight": "model-00046-of-00061.safetensors",
|
245 |
+
"transformer.blocks.29.norm_attn_norm.attn.Wqkv.weight": "model-00046-of-00061.safetensors",
|
246 |
+
"transformer.blocks.29.norm_attn_norm.attn.out_proj.weight": "model-00046-of-00061.safetensors",
|
247 |
+
"transformer.blocks.29.norm_attn_norm.norm_1.weight": "model-00046-of-00061.safetensors",
|
248 |
+
"transformer.blocks.29.norm_attn_norm.norm_2.weight": "model-00046-of-00061.safetensors",
|
249 |
+
"transformer.blocks.30.ffn.experts.mlp.v1": "model-00046-of-00061.safetensors",
|
250 |
+
"transformer.blocks.30.ffn.experts.mlp.w1": "model-00047-of-00061.safetensors",
|
251 |
+
"transformer.blocks.30.ffn.experts.mlp.w2": "model-00047-of-00061.safetensors",
|
252 |
+
"transformer.blocks.30.ffn.router.layer.weight": "model-00047-of-00061.safetensors",
|
253 |
+
"transformer.blocks.30.norm_attn_norm.attn.Wqkv.weight": "model-00047-of-00061.safetensors",
|
254 |
+
"transformer.blocks.30.norm_attn_norm.attn.out_proj.weight": "model-00047-of-00061.safetensors",
|
255 |
+
"transformer.blocks.30.norm_attn_norm.norm_1.weight": "model-00047-of-00061.safetensors",
|
256 |
+
"transformer.blocks.30.norm_attn_norm.norm_2.weight": "model-00047-of-00061.safetensors",
|
257 |
+
"transformer.blocks.31.ffn.experts.mlp.v1": "model-00048-of-00061.safetensors",
|
258 |
+
"transformer.blocks.31.ffn.experts.mlp.w1": "model-00048-of-00061.safetensors",
|
259 |
+
"transformer.blocks.31.ffn.experts.mlp.w2": "model-00049-of-00061.safetensors",
|
260 |
+
"transformer.blocks.31.ffn.router.layer.weight": "model-00049-of-00061.safetensors",
|
261 |
+
"transformer.blocks.31.norm_attn_norm.attn.Wqkv.weight": "model-00049-of-00061.safetensors",
|
262 |
+
"transformer.blocks.31.norm_attn_norm.attn.out_proj.weight": "model-00049-of-00061.safetensors",
|
263 |
+
"transformer.blocks.31.norm_attn_norm.norm_1.weight": "model-00049-of-00061.safetensors",
|
264 |
+
"transformer.blocks.31.norm_attn_norm.norm_2.weight": "model-00049-of-00061.safetensors",
|
265 |
+
"transformer.blocks.32.ffn.experts.mlp.v1": "model-00049-of-00061.safetensors",
|
266 |
+
"transformer.blocks.32.ffn.experts.mlp.w1": "model-00050-of-00061.safetensors",
|
267 |
+
"transformer.blocks.32.ffn.experts.mlp.w2": "model-00050-of-00061.safetensors",
|
268 |
+
"transformer.blocks.32.ffn.router.layer.weight": "model-00050-of-00061.safetensors",
|
269 |
+
"transformer.blocks.32.norm_attn_norm.attn.Wqkv.weight": "model-00050-of-00061.safetensors",
|
270 |
+
"transformer.blocks.32.norm_attn_norm.attn.out_proj.weight": "model-00050-of-00061.safetensors",
|
271 |
+
"transformer.blocks.32.norm_attn_norm.norm_1.weight": "model-00050-of-00061.safetensors",
|
272 |
+
"transformer.blocks.32.norm_attn_norm.norm_2.weight": "model-00050-of-00061.safetensors",
|
273 |
+
"transformer.blocks.33.ffn.experts.mlp.v1": "model-00051-of-00061.safetensors",
|
274 |
+
"transformer.blocks.33.ffn.experts.mlp.w1": "model-00051-of-00061.safetensors",
|
275 |
+
"transformer.blocks.33.ffn.experts.mlp.w2": "model-00052-of-00061.safetensors",
|
276 |
+
"transformer.blocks.33.ffn.router.layer.weight": "model-00052-of-00061.safetensors",
|
277 |
+
"transformer.blocks.33.norm_attn_norm.attn.Wqkv.weight": "model-00052-of-00061.safetensors",
|
278 |
+
"transformer.blocks.33.norm_attn_norm.attn.out_proj.weight": "model-00052-of-00061.safetensors",
|
279 |
+
"transformer.blocks.33.norm_attn_norm.norm_1.weight": "model-00052-of-00061.safetensors",
|
280 |
+
"transformer.blocks.33.norm_attn_norm.norm_2.weight": "model-00052-of-00061.safetensors",
|
281 |
+
"transformer.blocks.34.ffn.experts.mlp.v1": "model-00052-of-00061.safetensors",
|
282 |
+
"transformer.blocks.34.ffn.experts.mlp.w1": "model-00053-of-00061.safetensors",
|
283 |
+
"transformer.blocks.34.ffn.experts.mlp.w2": "model-00053-of-00061.safetensors",
|
284 |
+
"transformer.blocks.34.ffn.router.layer.weight": "model-00053-of-00061.safetensors",
|
285 |
+
"transformer.blocks.34.norm_attn_norm.attn.Wqkv.weight": "model-00053-of-00061.safetensors",
|
286 |
+
"transformer.blocks.34.norm_attn_norm.attn.out_proj.weight": "model-00053-of-00061.safetensors",
|
287 |
+
"transformer.blocks.34.norm_attn_norm.norm_1.weight": "model-00053-of-00061.safetensors",
|
288 |
+
"transformer.blocks.34.norm_attn_norm.norm_2.weight": "model-00053-of-00061.safetensors",
|
289 |
+
"transformer.blocks.35.ffn.experts.mlp.v1": "model-00054-of-00061.safetensors",
|
290 |
+
"transformer.blocks.35.ffn.experts.mlp.w1": "model-00054-of-00061.safetensors",
|
291 |
+
"transformer.blocks.35.ffn.experts.mlp.w2": "model-00055-of-00061.safetensors",
|
292 |
+
"transformer.blocks.35.ffn.router.layer.weight": "model-00055-of-00061.safetensors",
|
293 |
+
"transformer.blocks.35.norm_attn_norm.attn.Wqkv.weight": "model-00055-of-00061.safetensors",
|
294 |
+
"transformer.blocks.35.norm_attn_norm.attn.out_proj.weight": "model-00055-of-00061.safetensors",
|
295 |
+
"transformer.blocks.35.norm_attn_norm.norm_1.weight": "model-00055-of-00061.safetensors",
|
296 |
+
"transformer.blocks.35.norm_attn_norm.norm_2.weight": "model-00055-of-00061.safetensors",
|
297 |
+
"transformer.blocks.36.ffn.experts.mlp.v1": "model-00055-of-00061.safetensors",
|
298 |
+
"transformer.blocks.36.ffn.experts.mlp.w1": "model-00056-of-00061.safetensors",
|
299 |
+
"transformer.blocks.36.ffn.experts.mlp.w2": "model-00056-of-00061.safetensors",
|
300 |
+
"transformer.blocks.36.ffn.router.layer.weight": "model-00056-of-00061.safetensors",
|
301 |
+
"transformer.blocks.36.norm_attn_norm.attn.Wqkv.weight": "model-00056-of-00061.safetensors",
|
302 |
+
"transformer.blocks.36.norm_attn_norm.attn.out_proj.weight": "model-00056-of-00061.safetensors",
|
303 |
+
"transformer.blocks.36.norm_attn_norm.norm_1.weight": "model-00056-of-00061.safetensors",
|
304 |
+
"transformer.blocks.36.norm_attn_norm.norm_2.weight": "model-00056-of-00061.safetensors",
|
305 |
+
"transformer.blocks.37.ffn.experts.mlp.v1": "model-00057-of-00061.safetensors",
|
306 |
+
"transformer.blocks.37.ffn.experts.mlp.w1": "model-00057-of-00061.safetensors",
|
307 |
+
"transformer.blocks.37.ffn.experts.mlp.w2": "model-00058-of-00061.safetensors",
|
308 |
+
"transformer.blocks.37.ffn.router.layer.weight": "model-00058-of-00061.safetensors",
|
309 |
+
"transformer.blocks.37.norm_attn_norm.attn.Wqkv.weight": "model-00058-of-00061.safetensors",
|
310 |
+
"transformer.blocks.37.norm_attn_norm.attn.out_proj.weight": "model-00058-of-00061.safetensors",
|
311 |
+
"transformer.blocks.37.norm_attn_norm.norm_1.weight": "model-00058-of-00061.safetensors",
|
312 |
+
"transformer.blocks.37.norm_attn_norm.norm_2.weight": "model-00058-of-00061.safetensors",
|
313 |
+
"transformer.blocks.38.ffn.experts.mlp.v1": "model-00058-of-00061.safetensors",
|
314 |
+
"transformer.blocks.38.ffn.experts.mlp.w1": "model-00059-of-00061.safetensors",
|
315 |
+
"transformer.blocks.38.ffn.experts.mlp.w2": "model-00059-of-00061.safetensors",
|
316 |
+
"transformer.blocks.38.ffn.router.layer.weight": "model-00059-of-00061.safetensors",
|
317 |
+
"transformer.blocks.38.norm_attn_norm.attn.Wqkv.weight": "model-00059-of-00061.safetensors",
|
318 |
+
"transformer.blocks.38.norm_attn_norm.attn.out_proj.weight": "model-00059-of-00061.safetensors",
|
319 |
+
"transformer.blocks.38.norm_attn_norm.norm_1.weight": "model-00059-of-00061.safetensors",
|
320 |
+
"transformer.blocks.38.norm_attn_norm.norm_2.weight": "model-00059-of-00061.safetensors",
|
321 |
+
"transformer.blocks.39.ffn.experts.mlp.v1": "model-00060-of-00061.safetensors",
|
322 |
+
"transformer.blocks.39.ffn.experts.mlp.w1": "model-00060-of-00061.safetensors",
|
323 |
+
"transformer.blocks.39.ffn.experts.mlp.w2": "model-00061-of-00061.safetensors",
|
324 |
+
"transformer.blocks.39.ffn.router.layer.weight": "model-00061-of-00061.safetensors",
|
325 |
+
"transformer.blocks.39.norm_attn_norm.attn.Wqkv.weight": "model-00061-of-00061.safetensors",
|
326 |
+
"transformer.blocks.39.norm_attn_norm.attn.out_proj.weight": "model-00061-of-00061.safetensors",
|
327 |
+
"transformer.blocks.39.norm_attn_norm.norm_1.weight": "model-00061-of-00061.safetensors",
|
328 |
+
"transformer.blocks.39.norm_attn_norm.norm_2.weight": "model-00061-of-00061.safetensors"
|
329 |
+
}
|
330 |
+
}
|
modeling_dbrx.py
ADDED
@@ -0,0 +1,1482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": "<|im_end|>",
|
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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": "<|im_start|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"100278": {
|
23 |
+
"content": "<|im_end|>",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": false,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": true
|
29 |
+
},
|
30 |
+
"100279": {
|
31 |
+
"content": "<|pad|>",
|
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 |
+
"bos_token": "<|endoftext|>",
|
44 |
+
"chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
|
45 |
+
"clean_up_tokenization_spaces": true,
|
46 |
+
"encoding_name": null,
|
47 |
+
"eos_token": "<|im_end|>",
|
48 |
+
"errors": "replace",
|
49 |
+
"model_max_length": 1000000000000000019884624838656,
|
50 |
+
"model_name": "gpt-4",
|
51 |
+
"pad_token": "<|pad|>",
|
52 |
+
"tokenizer_class": "GPT2Tokenizer",
|
53 |
+
"unk_token": "<|endoftext|>",
|
54 |
+
"use_default_system_prompt": false
|
55 |
+
}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|