Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- README.md +41 -3
- config.json +47 -0
- configuration_deepseek.py +229 -0
- generation_config.json +8 -0
- model-00001-of-00009.safetensors +3 -0
- model-00002-of-00009.safetensors +3 -0
- model-00003-of-00009.safetensors +3 -0
- model-00004-of-00009.safetensors +3 -0
- model-00005-of-00009.safetensors +3 -0
- model-00006-of-00009.safetensors +3 -0
- model-00007-of-00009.safetensors +3 -0
- model-00008-of-00009.safetensors +3 -0
- model-00009-of-00009.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modelling_deepseek.py +1413 -0
- special_tokens_map.json +50 -0
- tokenizer.json +3 -0
- tokenizer_config.json +104 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,3 +1,41 @@
|
|
1 |
-
---
|
2 |
-
license: mit
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: mit
|
3 |
+
base_model:
|
4 |
+
- ai-sage/GigaChat-20B-A3B-instruct
|
5 |
+
language:
|
6 |
+
- ru
|
7 |
+
- en
|
8 |
+
---
|
9 |
+
# GigaChat-20B-A3B-instruct bf16
|
10 |
+
|
11 |
+
Диалоговая модель из семейства моделей GigaChat, основная на [ai-sage/GigaChat-20B-A3B-instruct](https://huggingface.co/ai-sage/GigaChat-20B-A3B-instruct). Поддерживает контекст в 131 тысячу токенов.
|
12 |
+
|
13 |
+
Больше потребностей в [хабр статье](https://habr.com/en/companies/sberdevices/articles/865996/) и в карточке оригинальной instruct модели.
|
14 |
+
|
15 |
+
|
16 |
+
## Пример использования через transformers
|
17 |
+
|
18 |
+
```bash
|
19 |
+
pip install --upgrade transformers torch accelerate bitsandbytes
|
20 |
+
```
|
21 |
+
|
22 |
+
|
23 |
+
```python
|
24 |
+
import torch
|
25 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
26 |
+
|
27 |
+
model_name = "ai-sage/GigaChat-20B-A3B-instruct-bf16"
|
28 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
29 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, device_map="auto", torch_dtype=torch.bfloat16)
|
30 |
+
model.generation_config = GenerationConfig.from_pretrained(model_name)
|
31 |
+
|
32 |
+
messages = [
|
33 |
+
{"role": "user", "content": "Докажи теорему о неподвижной точке"}
|
34 |
+
]
|
35 |
+
input_tensor = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
|
36 |
+
outputs = model.generate(input_tensor.to(model.device))
|
37 |
+
|
38 |
+
result = tokenizer.decode(outputs[0][input_tensor.shape[1]:], skip_special_tokens=False)
|
39 |
+
print(result)
|
40 |
+
```
|
41 |
+
|
config.json
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/home/jovyan/dvmazur/giga-chat-lite-metrics/fp32/GigaChat-20B-A3B-instruct",
|
3 |
+
"architectures": [
|
4 |
+
"DeepseekForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_bias": false,
|
7 |
+
"attention_dropout": 0.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_deepseek.DeepseekConfig",
|
10 |
+
"AutoModel": "modelling_deepseek.DeepseekModel",
|
11 |
+
"AutoModelForCausalLM": "modelling_deepseek.DeepseekForCausalLM"
|
12 |
+
},
|
13 |
+
"aux_loss_alpha": 0.001,
|
14 |
+
"bos_token_id": 1,
|
15 |
+
"eos_token_id": 128001,
|
16 |
+
"first_k_dense_replace": 1,
|
17 |
+
"head_dim": 128,
|
18 |
+
"hidden_act": "silu",
|
19 |
+
"hidden_size": 2048,
|
20 |
+
"initializer_range": 0.006,
|
21 |
+
"intermediate_size": 14336,
|
22 |
+
"max_position_embeddings": 131072,
|
23 |
+
"mlp_bias": false,
|
24 |
+
"model_type": "deepseek",
|
25 |
+
"moe_implementation": "eager",
|
26 |
+
"moe_intermediate_size": 1792,
|
27 |
+
"moe_layer_freq": 1,
|
28 |
+
"n_routed_experts": 64,
|
29 |
+
"n_shared_experts": 2,
|
30 |
+
"norm_topk_prob": false,
|
31 |
+
"num_attention_heads": 16,
|
32 |
+
"num_experts_per_tok": 6,
|
33 |
+
"num_hidden_layers": 28,
|
34 |
+
"num_key_value_heads": 8,
|
35 |
+
"pad_token_id": 1,
|
36 |
+
"pretraining_tp": 1,
|
37 |
+
"rms_norm_eps": 1e-05,
|
38 |
+
"rope_scaling": null,
|
39 |
+
"rope_theta": 1400000,
|
40 |
+
"scoring_func": "softmax",
|
41 |
+
"seq_aux": true,
|
42 |
+
"tie_word_embeddings": false,
|
43 |
+
"torch_dtype": "bfloat16",
|
44 |
+
"transformers_version": "4.47.0",
|
45 |
+
"use_cache": true,
|
46 |
+
"vocab_size": 128256
|
47 |
+
}
|
configuration_deepseek.py
ADDED
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Deepseek Moe model configuration"""
|
2 |
+
from transformers.utils import logging
|
3 |
+
from transformers.configuration_utils import PretrainedConfig
|
4 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
5 |
+
|
6 |
+
logger = logging.get_logger(__name__)
|
7 |
+
|
8 |
+
DEEPSEEK_FIXES_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
9 |
+
class DeepseekConfig(PretrainedConfig):
|
10 |
+
r"""
|
11 |
+
This is the configuration class to store the configuration of a DeepseekModel`]. It is used to instantiate an DeepSeek
|
12 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
13 |
+
defaults will yield a similar configuration to that of the DeepseekModel-20b.
|
14 |
+
|
15 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
16 |
+
documentation from [`PretrainedConfig`] for more information.
|
17 |
+
|
18 |
+
|
19 |
+
Args:
|
20 |
+
vocab_size (`int`, *optional*, defaults to 128256):
|
21 |
+
Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
|
22 |
+
`inputs_ids` passed when calling [`DeepseekModel`]
|
23 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
24 |
+
Dimension of the hidden representations.
|
25 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
26 |
+
Dimension of the MLP representations.
|
27 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1792):
|
28 |
+
Dimension of the MoE representations.
|
29 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
30 |
+
Number of hidden layers in the Transformer decoder.
|
31 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
32 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
33 |
+
n_shared_experts (`int`, *optional*, defaults to None):
|
34 |
+
Number of shared experts, None means dense model.
|
35 |
+
n_routed_experts (`int`, *optional*, defaults to None):
|
36 |
+
Number of routed experts, None means dense model.
|
37 |
+
num_experts_per_tok (`int`, *optional*, defaults to None):
|
38 |
+
Number of selected experts, None means dense model.
|
39 |
+
moe_layer_freq (`int`, *optional*, defaults to 1):
|
40 |
+
The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
|
41 |
+
first_k_dense_replace (`int`, *optional*, defaults to 0):
|
42 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
43 |
+
\--k dense layers--/
|
44 |
+
norm_topk_prob (`bool`, *optional*, defaults to False):
|
45 |
+
Whether to normalize the weights of the routed experts.
|
46 |
+
scoring_func (`str`, *optional*, defaults to 'softmax'):
|
47 |
+
Method of computing expert weights.
|
48 |
+
aux_loss_alpha (`float`, *optional*, defaults to 0.001):
|
49 |
+
Auxiliary loss weight coefficient.
|
50 |
+
seq_aux = (`bool`, *optional*, defaults to True):
|
51 |
+
Whether to compute the auxiliary loss for each individual sample.
|
52 |
+
num_key_value_heads (`int`, *optional*):
|
53 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
54 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
55 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
56 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
57 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
58 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
59 |
+
`num_attention_heads`.
|
60 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
61 |
+
The non-linear activation function (function or string) in the decoder.
|
62 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
63 |
+
The maximum sequence length that this model might ever be used with.
|
64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
66 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
67 |
+
The epsilon used by the rms normalization layers.
|
68 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
69 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
70 |
+
relevant if `config.is_decoder=True`.
|
71 |
+
pad_token_id (`int`, *optional*):
|
72 |
+
Padding token id.
|
73 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
74 |
+
Beginning of stream token id.
|
75 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
76 |
+
End of stream token id.
|
77 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
78 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
79 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
80 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
81 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
82 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
83 |
+
Whether to tie weight embeddings
|
84 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
85 |
+
The base period of the RoPE embeddings.
|
86 |
+
rope_scaling (`Dict`, *optional*):
|
87 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
88 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
89 |
+
accordingly.
|
90 |
+
Expected contents:
|
91 |
+
`rope_type` (`str`):
|
92 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
93 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
94 |
+
`factor` (`float`, *optional*):
|
95 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
96 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
97 |
+
original maximum pre-trained length.
|
98 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
99 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
100 |
+
pretraining.
|
101 |
+
`attention_factor` (`float`, *optional*):
|
102 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
103 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
104 |
+
`factor` field to infer the suggested value.
|
105 |
+
`beta_fast` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 32.
|
108 |
+
`beta_slow` (`float`, *optional*):
|
109 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
110 |
+
ramp function. If unspecified, it defaults to 1.
|
111 |
+
`short_factor` (`List[float]`, *optional*):
|
112 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
113 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
114 |
+
size divided by the number of attention heads divided by 2
|
115 |
+
`long_factor` (`List[float]`, *optional*):
|
116 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
117 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
118 |
+
size divided by the number of attention heads divided by 2
|
119 |
+
`low_freq_factor` (`float`, *optional*):
|
120 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
121 |
+
`high_freq_factor` (`float`, *optional*):
|
122 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
123 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
124 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
125 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
126 |
+
The dropout ratio for the attention probabilities.
|
127 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
128 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
129 |
+
head_dim (`int`, *optional*):
|
130 |
+
The attention head dimension. If None, it will default to hidden_size // num_heads
|
131 |
+
|
132 |
+
```python
|
133 |
+
>>> from transformers import DeepseekModel, DeepseekConfig
|
134 |
+
|
135 |
+
>>> configuration = DeepseekConfig()
|
136 |
+
>>> model = DeepseekModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "deepseek"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
|
145 |
+
def __init__(
|
146 |
+
self,
|
147 |
+
vocab_size=128256,
|
148 |
+
hidden_size=2048,
|
149 |
+
intermediate_size=14336,
|
150 |
+
moe_intermediate_size = 1792,
|
151 |
+
num_hidden_layers=28,
|
152 |
+
num_attention_heads=16,
|
153 |
+
num_key_value_heads=8,
|
154 |
+
n_shared_experts = None,
|
155 |
+
n_routed_experts = None,
|
156 |
+
num_experts_per_tok = None,
|
157 |
+
moe_layer_freq = 1,
|
158 |
+
first_k_dense_replace = 0,
|
159 |
+
norm_topk_prob = False,
|
160 |
+
scoring_func = 'softmax',
|
161 |
+
aux_loss_alpha = 0.001,
|
162 |
+
seq_aux = True,
|
163 |
+
hidden_act="silu",
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
initializer_range=0.02,
|
166 |
+
rms_norm_eps=1e-6,
|
167 |
+
use_cache=True,
|
168 |
+
pad_token_id=None,
|
169 |
+
bos_token_id=1,
|
170 |
+
eos_token_id=2,
|
171 |
+
pretraining_tp=1,
|
172 |
+
tie_word_embeddings=False,
|
173 |
+
rope_theta=10000.0,
|
174 |
+
rope_scaling=None,
|
175 |
+
attention_bias=False,
|
176 |
+
attention_dropout=0.0,
|
177 |
+
moe_implementation="eager",
|
178 |
+
mlp_bias=False,
|
179 |
+
head_dim=None,
|
180 |
+
**kwargs,
|
181 |
+
):
|
182 |
+
assert moe_implementation in ('eager', ), "Invalid moe_implementation value."
|
183 |
+
self.vocab_size = vocab_size
|
184 |
+
self.max_position_embeddings = max_position_embeddings
|
185 |
+
self.hidden_size = hidden_size
|
186 |
+
self.intermediate_size = intermediate_size
|
187 |
+
self.moe_intermediate_size = moe_intermediate_size
|
188 |
+
self.num_hidden_layers = num_hidden_layers
|
189 |
+
self.num_attention_heads = num_attention_heads
|
190 |
+
self.n_shared_experts = n_shared_experts
|
191 |
+
self.n_routed_experts = n_routed_experts
|
192 |
+
self.num_experts_per_tok = num_experts_per_tok
|
193 |
+
self.moe_layer_freq = moe_layer_freq
|
194 |
+
self.first_k_dense_replace = first_k_dense_replace
|
195 |
+
self.norm_topk_prob = norm_topk_prob
|
196 |
+
self.scoring_func = scoring_func
|
197 |
+
self.aux_loss_alpha = aux_loss_alpha
|
198 |
+
self.seq_aux = seq_aux
|
199 |
+
|
200 |
+
# for backward compatibility
|
201 |
+
if num_key_value_heads is None:
|
202 |
+
num_key_value_heads = num_attention_heads
|
203 |
+
|
204 |
+
self.num_key_value_heads = num_key_value_heads
|
205 |
+
self.hidden_act = hidden_act
|
206 |
+
self.initializer_range = initializer_range
|
207 |
+
self.rms_norm_eps = rms_norm_eps
|
208 |
+
self.pretraining_tp = pretraining_tp
|
209 |
+
self.use_cache = use_cache
|
210 |
+
self.rope_theta = rope_theta
|
211 |
+
self.rope_scaling = rope_scaling
|
212 |
+
self.attention_bias = attention_bias
|
213 |
+
self.attention_dropout = attention_dropout
|
214 |
+
self.mlp_bias = mlp_bias
|
215 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
216 |
+
# Validate the correctness of rotary position embeddings parameters
|
217 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
218 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
219 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
220 |
+
rope_config_validation(self)
|
221 |
+
self.moe_implementation = moe_implementation
|
222 |
+
|
223 |
+
super().__init__(
|
224 |
+
pad_token_id=pad_token_id,
|
225 |
+
bos_token_id=bos_token_id,
|
226 |
+
eos_token_id=eos_token_id,
|
227 |
+
tie_word_embeddings=tie_word_embeddings,
|
228 |
+
**kwargs,
|
229 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 128001,
|
5 |
+
"max_new_tokens": 2048,
|
6 |
+
"pad_token_id": 2,
|
7 |
+
"transformers_version": "4.47.0"
|
8 |
+
}
|
model-00001-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb36e1ff7fa81868b4247ca5a8d7b8ba05781ec8a8e13a5125ecbc64853e39e9
|
3 |
+
size 4993941128
|
model-00002-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:61dec54b1005e5c7dd727899d1febf5fe90923051b45bfefdda576c08c1d7f97
|
3 |
+
size 4997630296
|
model-00003-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:50d79e09c7a173bb2a06a2f55219c23082b9d6f95f00c4f5d284ee1e7598f20c
|
3 |
+
size 4994214328
|
model-00004-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:95212e24368153cd6c33caedb1cef31ef9597479cc439c410e3dcc41ccaf1786
|
3 |
+
size 4997631008
|
model-00005-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b1ac6eaf9a7c03a0879635a5479a2a41408689bc844d1cd78a05b5f3c21b6d42
|
3 |
+
size 4994214840
|
model-00006-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:221159a147ee113cc73ea127873b6701c1e7910ea8b8eb812a41d312e1b0abbf
|
3 |
+
size 4994214872
|
model-00007-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:eceb292bd9cbd432cd3b53732c1f5c89c61721600bb8df6104dce3d9ce085ef8
|
3 |
+
size 4997630984
|
model-00008-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7063cb4a856bb341382a15c406b73ccfc7a68a12896ed230b1edd202fcccf44d
|
3 |
+
size 4994214872
|
model-00009-of-00009.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:59aba95274efdf8750eda28da952e9a04029adbca550c50053f27e4ded0d7869
|
3 |
+
size 1215585864
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modelling_deepseek.py
ADDED
@@ -0,0 +1,1413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
""" PyTorch Deepseek Moe model with fixed Rope and updated code."""
|
3 |
+
import math
|
4 |
+
from typing import List, Optional, Tuple, Union
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn.functional as F
|
8 |
+
import torch.utils.checkpoint
|
9 |
+
from torch import nn
|
10 |
+
|
11 |
+
from transformers.activations import ACT2FN
|
12 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
13 |
+
from transformers.generation import GenerationMixin
|
14 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
15 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs, _flash_attention_forward
|
16 |
+
from transformers.modeling_outputs import (
|
17 |
+
BaseModelOutputWithPast,
|
18 |
+
CausalLMOutputWithPast,
|
19 |
+
SequenceClassifierOutputWithPast,
|
20 |
+
)
|
21 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
22 |
+
from transformers.modeling_utils import PreTrainedModel
|
23 |
+
from transformers.processing_utils import Unpack
|
24 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
25 |
+
from transformers.utils import (
|
26 |
+
LossKwargs,
|
27 |
+
add_start_docstrings,
|
28 |
+
add_start_docstrings_to_model_forward,
|
29 |
+
is_flash_attn_greater_or_equal_2_10,
|
30 |
+
logging,
|
31 |
+
replace_return_docstrings,
|
32 |
+
)
|
33 |
+
from .configuration_deepseek import DeepseekConfig
|
34 |
+
|
35 |
+
|
36 |
+
logger = logging.get_logger(__name__)
|
37 |
+
|
38 |
+
_CONFIG_FOR_DOC = "DeepseekConfig"
|
39 |
+
|
40 |
+
|
41 |
+
class DeepseekRMSNorm(nn.Module):
|
42 |
+
def __init__(self, hidden_size, eps=1e-6):
|
43 |
+
"""
|
44 |
+
DeepseekRMSNorm is equivalent to T5LayerNorm
|
45 |
+
"""
|
46 |
+
super().__init__()
|
47 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
48 |
+
self.variance_epsilon = eps
|
49 |
+
|
50 |
+
def forward(self, hidden_states):
|
51 |
+
input_dtype = hidden_states.dtype
|
52 |
+
hidden_states = hidden_states.to(torch.float32)
|
53 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
54 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
55 |
+
return self.weight * hidden_states.to(input_dtype)
|
56 |
+
|
57 |
+
def extra_repr(self):
|
58 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
59 |
+
|
60 |
+
|
61 |
+
ALL_LAYERNORM_LAYERS.append(DeepseekRMSNorm)
|
62 |
+
|
63 |
+
|
64 |
+
class DeepseekRotaryEmbedding(nn.Module):
|
65 |
+
def __init__(
|
66 |
+
self,
|
67 |
+
dim=None,
|
68 |
+
max_position_embeddings=2048,
|
69 |
+
base=10000,
|
70 |
+
device=None,
|
71 |
+
scaling_factor=1.0,
|
72 |
+
rope_type="default",
|
73 |
+
config: Optional[DeepseekConfig] = None,
|
74 |
+
):
|
75 |
+
super().__init__()
|
76 |
+
# TODO (joao): remove the `if` below, only used for BC
|
77 |
+
self.rope_kwargs = {}
|
78 |
+
if config is None:
|
79 |
+
logger.warning_once(
|
80 |
+
"`DeepseekRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
81 |
+
"`config` argument. All other arguments will be removed in v4.46"
|
82 |
+
)
|
83 |
+
self.rope_kwargs = {
|
84 |
+
"rope_type": rope_type,
|
85 |
+
"factor": scaling_factor,
|
86 |
+
"dim": dim,
|
87 |
+
"base": base,
|
88 |
+
"max_position_embeddings": max_position_embeddings,
|
89 |
+
}
|
90 |
+
self.rope_type = rope_type
|
91 |
+
self.max_seq_len_cached = max_position_embeddings
|
92 |
+
self.original_max_seq_len = max_position_embeddings
|
93 |
+
else:
|
94 |
+
# BC: "rope_type" was originally "type"
|
95 |
+
if config.rope_scaling is not None:
|
96 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
97 |
+
else:
|
98 |
+
self.rope_type = "default"
|
99 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
100 |
+
self.original_max_seq_len = config.max_position_embeddings
|
101 |
+
|
102 |
+
self.config = config
|
103 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
104 |
+
|
105 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
|
106 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
107 |
+
self.original_inv_freq = self.inv_freq
|
108 |
+
|
109 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
110 |
+
"""
|
111 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
112 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
113 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
114 |
+
"""
|
115 |
+
seq_len = torch.max(position_ids) + 1
|
116 |
+
if seq_len > self.max_seq_len_cached: # growth
|
117 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
118 |
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
119 |
+
)
|
120 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
121 |
+
self.max_seq_len_cached = seq_len
|
122 |
+
|
123 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
124 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
125 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
126 |
+
|
127 |
+
@torch.no_grad()
|
128 |
+
def forward(self, x, position_ids):
|
129 |
+
if "dynamic" in self.rope_type:
|
130 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
131 |
+
|
132 |
+
# Core RoPE block
|
133 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
134 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
135 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
136 |
+
device_type = x.device.type
|
137 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
138 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
139 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
140 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
141 |
+
cos = emb.cos()
|
142 |
+
sin = emb.sin()
|
143 |
+
|
144 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
145 |
+
cos = cos * self.attention_scaling
|
146 |
+
sin = sin * self.attention_scaling
|
147 |
+
|
148 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
149 |
+
|
150 |
+
|
151 |
+
class DeepseekLinearScalingRotaryEmbedding(DeepseekRotaryEmbedding):
|
152 |
+
"""DeepseekRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
153 |
+
|
154 |
+
def __init__(self, *args, **kwargs):
|
155 |
+
logger.warning_once(
|
156 |
+
"`DeepseekLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
|
157 |
+
"`DeepseekRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
|
158 |
+
)
|
159 |
+
kwargs["rope_type"] = "linear"
|
160 |
+
super().__init__(*args, **kwargs)
|
161 |
+
|
162 |
+
|
163 |
+
class DeepseekDynamicNTKScalingRotaryEmbedding(DeepseekRotaryEmbedding):
|
164 |
+
"""DeepseekRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
165 |
+
|
166 |
+
def __init__(self, *args, **kwargs):
|
167 |
+
logger.warning_once(
|
168 |
+
"`DeepseekDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
|
169 |
+
"`DeepseekRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
|
170 |
+
"__init__)."
|
171 |
+
)
|
172 |
+
kwargs["rope_type"] = "dynamic"
|
173 |
+
super().__init__(*args, **kwargs)
|
174 |
+
|
175 |
+
|
176 |
+
def rotate_half(x):
|
177 |
+
"""Rotates half the hidden dims of the input."""
|
178 |
+
x1 = x[..., : x.shape[-1] // 2]
|
179 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
180 |
+
return torch.cat((-x2, x1), dim=-1)
|
181 |
+
|
182 |
+
|
183 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
184 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
185 |
+
|
186 |
+
Args:
|
187 |
+
q (`torch.Tensor`): The query tensor.
|
188 |
+
k (`torch.Tensor`): The key tensor.
|
189 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
190 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
191 |
+
position_ids (`torch.Tensor`, *optional*):
|
192 |
+
Deprecated and unused.
|
193 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
194 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
195 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
196 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
197 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
198 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
199 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
200 |
+
Returns:
|
201 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
202 |
+
"""
|
203 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
204 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
205 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
206 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
207 |
+
return q_embed, k_embed
|
208 |
+
|
209 |
+
|
210 |
+
class DeepseekMLP(nn.Module):
|
211 |
+
def __init__(self, config, hidden_size=None, intermediate_size=None):
|
212 |
+
super().__init__()
|
213 |
+
self.config = config
|
214 |
+
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
|
215 |
+
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
|
216 |
+
|
217 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
218 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
219 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
220 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
221 |
+
|
222 |
+
def forward(self, x, **kwargs):
|
223 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
224 |
+
return down_proj
|
225 |
+
|
226 |
+
|
227 |
+
class MoEGate(nn.Module):
|
228 |
+
def __init__(self, config):
|
229 |
+
super().__init__()
|
230 |
+
self.config = config
|
231 |
+
self.top_k = config.num_experts_per_tok
|
232 |
+
self.n_routed_experts = config.n_routed_experts
|
233 |
+
|
234 |
+
self.scoring_func = config.scoring_func
|
235 |
+
self.alpha = config.aux_loss_alpha
|
236 |
+
self.seq_aux = config.seq_aux
|
237 |
+
|
238 |
+
# topk selection algorithm
|
239 |
+
self.norm_topk_prob = config.norm_topk_prob
|
240 |
+
self.gating_dim = config.hidden_size
|
241 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
|
242 |
+
|
243 |
+
self.reset_parameters()
|
244 |
+
|
245 |
+
def reset_parameters(self) -> None:
|
246 |
+
import torch.nn.init as init
|
247 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
248 |
+
|
249 |
+
def forward(self, hidden_states):
|
250 |
+
bsz, seq_len, h = hidden_states.shape
|
251 |
+
# Compute gating score
|
252 |
+
hidden_states = hidden_states.view(-1, h)
|
253 |
+
logits = F.linear(hidden_states, self.weight, None)
|
254 |
+
if self.scoring_func == 'softmax':
|
255 |
+
scores = logits.to(torch.float32).softmax(dim=-1)
|
256 |
+
else:
|
257 |
+
raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
|
258 |
+
|
259 |
+
# Select top-k experts
|
260 |
+
topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
|
261 |
+
|
262 |
+
# Norm gate to sum 1
|
263 |
+
if self.top_k > 1 and self.norm_topk_prob:
|
264 |
+
denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
|
265 |
+
topk_weight = topk_weight / denominator
|
266 |
+
|
267 |
+
# Expert-level computation auxiliary loss
|
268 |
+
aux_loss = None
|
269 |
+
return topk_idx, topk_weight.to(hidden_states.dtype), aux_loss
|
270 |
+
|
271 |
+
|
272 |
+
class AddAuxiliaryLoss(torch.autograd.Function):
|
273 |
+
"""
|
274 |
+
The trick function of adding auxiliary (aux) loss,
|
275 |
+
which includes the gradient of the aux loss during backpropagation.
|
276 |
+
"""
|
277 |
+
|
278 |
+
@staticmethod
|
279 |
+
def forward(ctx, x, loss):
|
280 |
+
assert loss.numel() == 1
|
281 |
+
ctx.dtype = loss.dtype
|
282 |
+
ctx.required_aux_loss = loss.requires_grad
|
283 |
+
return x
|
284 |
+
|
285 |
+
@staticmethod
|
286 |
+
def backward(ctx, grad_output):
|
287 |
+
grad_loss = None
|
288 |
+
if ctx.required_aux_loss:
|
289 |
+
grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
|
290 |
+
return grad_output, grad_loss
|
291 |
+
|
292 |
+
|
293 |
+
class DeepseekMoE(nn.Module):
|
294 |
+
"""
|
295 |
+
A mixed expert module containing shared experts.
|
296 |
+
"""
|
297 |
+
|
298 |
+
def __init__(self, config):
|
299 |
+
super().__init__()
|
300 |
+
self.config = config
|
301 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
302 |
+
self.experts = nn.ModuleList(
|
303 |
+
[DeepseekMLP(config, intermediate_size=config.moe_intermediate_size) for i in
|
304 |
+
range(config.n_routed_experts)])
|
305 |
+
self.gate = MoEGate(config)
|
306 |
+
if config.n_shared_experts is not None:
|
307 |
+
intermediate_size = config.moe_intermediate_size * config.n_shared_experts
|
308 |
+
self.shared_experts = DeepseekMLP(config=config, intermediate_size=intermediate_size)
|
309 |
+
|
310 |
+
def forward(self, hidden_states):
|
311 |
+
identity = hidden_states
|
312 |
+
orig_shape = hidden_states.shape
|
313 |
+
topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
|
314 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
315 |
+
flat_topk_idx = topk_idx.view(-1)
|
316 |
+
if self.training:
|
317 |
+
y = self.moe_train(hidden_states, flat_topk_idx, topk_weight.view(-1, 1))
|
318 |
+
y = y.view(*orig_shape)
|
319 |
+
y = AddAuxiliaryLoss.apply(y, aux_loss)
|
320 |
+
else:
|
321 |
+
y = self.moe_infer(hidden_states, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
|
322 |
+
if self.config.n_shared_experts is not None:
|
323 |
+
y = y + self.shared_experts(identity)
|
324 |
+
return y
|
325 |
+
|
326 |
+
def moe_train(self, hidden_states, flat_topk_idx, topk_weight):
|
327 |
+
hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
|
328 |
+
y = torch.empty_like(hidden_states)
|
329 |
+
for i, expert in enumerate(self.experts):
|
330 |
+
y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
|
331 |
+
y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
|
332 |
+
return y
|
333 |
+
|
334 |
+
@torch.no_grad()
|
335 |
+
def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
|
336 |
+
expert_cache = torch.zeros_like(x)
|
337 |
+
idxs = flat_expert_indices.argsort()
|
338 |
+
tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
|
339 |
+
token_idxs = idxs // self.num_experts_per_tok
|
340 |
+
for i, end_idx in enumerate(tokens_per_expert):
|
341 |
+
start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
|
342 |
+
if start_idx == end_idx:
|
343 |
+
continue
|
344 |
+
expert = self.experts[i]
|
345 |
+
exp_token_idx = token_idxs[start_idx:end_idx]
|
346 |
+
expert_tokens = x[exp_token_idx]
|
347 |
+
expert_out = expert(expert_tokens)
|
348 |
+
expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
|
349 |
+
expert_cache.scatter_reduce_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out, reduce='sum')
|
350 |
+
return expert_cache
|
351 |
+
|
352 |
+
|
353 |
+
Deepseek_MOE_CLASSES = {
|
354 |
+
'eager': DeepseekMoE,
|
355 |
+
}
|
356 |
+
|
357 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
358 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
359 |
+
"""
|
360 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
361 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
362 |
+
"""
|
363 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
364 |
+
if n_rep == 1:
|
365 |
+
return hidden_states
|
366 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
367 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
368 |
+
|
369 |
+
|
370 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->Deepseek
|
371 |
+
class DeepseekAttention(nn.Module):
|
372 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
373 |
+
|
374 |
+
def __init__(self, config: DeepseekConfig, layer_idx: Optional[int] = None):
|
375 |
+
super().__init__()
|
376 |
+
self.config = config
|
377 |
+
self.layer_idx = layer_idx
|
378 |
+
if layer_idx is None:
|
379 |
+
logger.warning_once(
|
380 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
381 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
382 |
+
"when creating this class."
|
383 |
+
)
|
384 |
+
|
385 |
+
self.attention_dropout = config.attention_dropout
|
386 |
+
self.hidden_size = config.hidden_size
|
387 |
+
self.num_heads = config.num_attention_heads
|
388 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
389 |
+
self.num_key_value_heads = config.num_key_value_heads
|
390 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
391 |
+
self.max_position_embeddings = config.max_position_embeddings
|
392 |
+
self.rope_theta = config.rope_theta
|
393 |
+
self.is_causal = True
|
394 |
+
|
395 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
396 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
397 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
398 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
399 |
+
|
400 |
+
# TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
|
401 |
+
self.rotary_emb = DeepseekRotaryEmbedding(config=self.config)
|
402 |
+
|
403 |
+
def forward(
|
404 |
+
self,
|
405 |
+
hidden_states: torch.Tensor,
|
406 |
+
attention_mask: Optional[torch.Tensor] = None,
|
407 |
+
position_ids: Optional[torch.LongTensor] = None,
|
408 |
+
past_key_value: Optional[Cache] = None,
|
409 |
+
output_attentions: bool = False,
|
410 |
+
use_cache: bool = False,
|
411 |
+
cache_position: Optional[torch.LongTensor] = None,
|
412 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
413 |
+
**kwargs,
|
414 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
415 |
+
bsz, q_len, _ = hidden_states.size()
|
416 |
+
|
417 |
+
query_states = self.q_proj(hidden_states)
|
418 |
+
key_states = self.k_proj(hidden_states)
|
419 |
+
value_states = self.v_proj(hidden_states)
|
420 |
+
|
421 |
+
# use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
|
422 |
+
query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
423 |
+
key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
424 |
+
value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
425 |
+
|
426 |
+
if position_embeddings is None:
|
427 |
+
logger.warning_once(
|
428 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
429 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
430 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
431 |
+
"removed and `position_embeddings` will be mandatory."
|
432 |
+
)
|
433 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
434 |
+
else:
|
435 |
+
cos, sin = position_embeddings
|
436 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
437 |
+
|
438 |
+
if past_key_value is not None:
|
439 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
440 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
441 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
442 |
+
|
443 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
444 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
445 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
446 |
+
|
447 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
448 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
449 |
+
attn_weights = attn_weights + causal_mask
|
450 |
+
|
451 |
+
# upcast attention to fp32
|
452 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
453 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
454 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
455 |
+
|
456 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
457 |
+
raise ValueError(
|
458 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
459 |
+
f" {attn_output.size()}"
|
460 |
+
)
|
461 |
+
|
462 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
463 |
+
|
464 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
465 |
+
|
466 |
+
attn_output = self.o_proj(attn_output)
|
467 |
+
|
468 |
+
if not output_attentions:
|
469 |
+
attn_weights = None
|
470 |
+
|
471 |
+
return attn_output, attn_weights, past_key_value
|
472 |
+
|
473 |
+
|
474 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Deepseek
|
475 |
+
class DeepseekFlashAttention2(DeepseekAttention):
|
476 |
+
"""
|
477 |
+
Deepseek flash attention module. This module inherits from `DeepseekAttention` as the weights of the module stays
|
478 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
479 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
480 |
+
"""
|
481 |
+
|
482 |
+
def __init__(self, *args, **kwargs):
|
483 |
+
super().__init__(*args, **kwargs)
|
484 |
+
|
485 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
486 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
487 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
488 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
489 |
+
|
490 |
+
def forward(
|
491 |
+
self,
|
492 |
+
hidden_states: torch.Tensor,
|
493 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
494 |
+
position_ids: Optional[torch.LongTensor] = None,
|
495 |
+
past_key_value: Optional[Cache] = None,
|
496 |
+
output_attentions: bool = False,
|
497 |
+
use_cache: bool = False,
|
498 |
+
cache_position: Optional[torch.LongTensor] = None,
|
499 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
500 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
501 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
502 |
+
if isinstance(past_key_value, StaticCache):
|
503 |
+
raise ValueError(
|
504 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
505 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
506 |
+
)
|
507 |
+
|
508 |
+
output_attentions = False
|
509 |
+
|
510 |
+
bsz, q_len, _ = hidden_states.size()
|
511 |
+
|
512 |
+
query_states = self.q_proj(hidden_states)
|
513 |
+
key_states = self.k_proj(hidden_states)
|
514 |
+
value_states = self.v_proj(hidden_states)
|
515 |
+
|
516 |
+
# Flash attention requires the input to have the shape
|
517 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
518 |
+
# therefore we just need to keep the original shape
|
519 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
520 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
521 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
522 |
+
|
523 |
+
if position_embeddings is None:
|
524 |
+
logger.warning_once(
|
525 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
526 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
527 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
528 |
+
"removed and `position_embeddings` will be mandatory."
|
529 |
+
)
|
530 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
531 |
+
else:
|
532 |
+
cos, sin = position_embeddings
|
533 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
534 |
+
|
535 |
+
if past_key_value is not None:
|
536 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
537 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
538 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
539 |
+
|
540 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
541 |
+
# to be able to avoid many of these transpose/reshape/view.
|
542 |
+
query_states = query_states.transpose(1, 2)
|
543 |
+
key_states = key_states.transpose(1, 2)
|
544 |
+
value_states = value_states.transpose(1, 2)
|
545 |
+
|
546 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
547 |
+
|
548 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
549 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
550 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
551 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
552 |
+
# in fp32. (DeepseekRMSNorm handles it correctly)
|
553 |
+
|
554 |
+
input_dtype = query_states.dtype
|
555 |
+
if input_dtype == torch.float32:
|
556 |
+
if torch.is_autocast_enabled():
|
557 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
558 |
+
# Handle the case where the model is quantized
|
559 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
560 |
+
target_dtype = self.config._pre_quantization_dtype
|
561 |
+
else:
|
562 |
+
target_dtype = self.q_proj.weight.dtype
|
563 |
+
|
564 |
+
logger.warning_once(
|
565 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
566 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
567 |
+
f" {target_dtype}."
|
568 |
+
)
|
569 |
+
|
570 |
+
query_states = query_states.to(target_dtype)
|
571 |
+
key_states = key_states.to(target_dtype)
|
572 |
+
value_states = value_states.to(target_dtype)
|
573 |
+
|
574 |
+
attn_output = _flash_attention_forward(
|
575 |
+
query_states,
|
576 |
+
key_states,
|
577 |
+
value_states,
|
578 |
+
attention_mask,
|
579 |
+
q_len,
|
580 |
+
position_ids=position_ids,
|
581 |
+
dropout=dropout_rate,
|
582 |
+
sliding_window=getattr(self, "sliding_window", None),
|
583 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
584 |
+
is_causal=self.is_causal,
|
585 |
+
**kwargs,
|
586 |
+
)
|
587 |
+
|
588 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
589 |
+
attn_output = self.o_proj(attn_output)
|
590 |
+
|
591 |
+
if not output_attentions:
|
592 |
+
attn_weights = None
|
593 |
+
|
594 |
+
return attn_output, attn_weights, past_key_value
|
595 |
+
|
596 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Deepseek
|
597 |
+
class DeepseekSdpaAttention(DeepseekAttention):
|
598 |
+
"""
|
599 |
+
Deepseek attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
600 |
+
`DeepseekAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
601 |
+
SDPA API.
|
602 |
+
"""
|
603 |
+
|
604 |
+
# Adapted from DeepseekAttention.forward
|
605 |
+
def forward(
|
606 |
+
self,
|
607 |
+
hidden_states: torch.Tensor,
|
608 |
+
attention_mask: Optional[torch.Tensor] = None,
|
609 |
+
position_ids: Optional[torch.LongTensor] = None,
|
610 |
+
past_key_value: Optional[Cache] = None,
|
611 |
+
output_attentions: bool = False,
|
612 |
+
use_cache: bool = False,
|
613 |
+
cache_position: Optional[torch.LongTensor] = None,
|
614 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
615 |
+
**kwargs,
|
616 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
617 |
+
if output_attentions:
|
618 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
619 |
+
logger.warning_once(
|
620 |
+
"DeepseekModel is using DeepseekSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
621 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
622 |
+
)
|
623 |
+
return super().forward(
|
624 |
+
hidden_states=hidden_states,
|
625 |
+
attention_mask=attention_mask,
|
626 |
+
position_ids=position_ids,
|
627 |
+
past_key_value=past_key_value,
|
628 |
+
output_attentions=output_attentions,
|
629 |
+
use_cache=use_cache,
|
630 |
+
cache_position=cache_position,
|
631 |
+
position_embeddings=position_embeddings,
|
632 |
+
)
|
633 |
+
|
634 |
+
bsz, q_len, _ = hidden_states.size()
|
635 |
+
|
636 |
+
query_states = self.q_proj(hidden_states)
|
637 |
+
key_states = self.k_proj(hidden_states)
|
638 |
+
value_states = self.v_proj(hidden_states)
|
639 |
+
|
640 |
+
# use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
|
641 |
+
query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
642 |
+
key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
643 |
+
value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
644 |
+
|
645 |
+
if position_embeddings is None:
|
646 |
+
logger.warning_once(
|
647 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
648 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
649 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
650 |
+
"removed and `position_embeddings` will be mandatory."
|
651 |
+
)
|
652 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
653 |
+
else:
|
654 |
+
cos, sin = position_embeddings
|
655 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
656 |
+
|
657 |
+
if past_key_value is not None:
|
658 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
659 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
660 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
661 |
+
|
662 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
663 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
664 |
+
|
665 |
+
causal_mask = attention_mask
|
666 |
+
if attention_mask is not None:
|
667 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
668 |
+
|
669 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
670 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
671 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
672 |
+
query_states = query_states.contiguous()
|
673 |
+
key_states = key_states.contiguous()
|
674 |
+
value_states = value_states.contiguous()
|
675 |
+
|
676 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
677 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
678 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
679 |
+
|
680 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
681 |
+
query_states,
|
682 |
+
key_states,
|
683 |
+
value_states,
|
684 |
+
attn_mask=causal_mask,
|
685 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
686 |
+
is_causal=is_causal,
|
687 |
+
)
|
688 |
+
|
689 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
690 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
691 |
+
|
692 |
+
attn_output = self.o_proj(attn_output)
|
693 |
+
|
694 |
+
return attn_output, None, past_key_value
|
695 |
+
|
696 |
+
|
697 |
+
Deepseek_ATTENTION_CLASSES = {
|
698 |
+
"eager": DeepseekAttention,
|
699 |
+
"flash_attention_2": DeepseekFlashAttention2,
|
700 |
+
"sdpa": DeepseekSdpaAttention,
|
701 |
+
}
|
702 |
+
|
703 |
+
|
704 |
+
class DeepseekDecoderLayer(nn.Module):
|
705 |
+
def __init__(self, config: DeepseekConfig, layer_idx: int):
|
706 |
+
super().__init__()
|
707 |
+
self.hidden_size = config.hidden_size
|
708 |
+
|
709 |
+
self.self_attn = Deepseek_ATTENTION_CLASSES[config._attn_implementation](config=config,
|
710 |
+
layer_idx=layer_idx)
|
711 |
+
|
712 |
+
self.mlp = Deepseek_MOE_CLASSES[config.moe_implementation](config) if (config.n_routed_experts is not None and \
|
713 |
+
layer_idx >= config.first_k_dense_replace and layer_idx % config.moe_layer_freq == 0) \
|
714 |
+
else DeepseekMLP(config)
|
715 |
+
self.input_layernorm = DeepseekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
716 |
+
self.post_attention_layernorm = DeepseekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
717 |
+
|
718 |
+
def forward(
|
719 |
+
self,
|
720 |
+
hidden_states: torch.Tensor,
|
721 |
+
attention_mask: Optional[torch.Tensor] = None,
|
722 |
+
position_ids: Optional[torch.LongTensor] = None,
|
723 |
+
past_key_value: Optional[Cache] = None,
|
724 |
+
output_attentions: Optional[bool] = False,
|
725 |
+
use_cache: Optional[bool] = False,
|
726 |
+
cache_position: Optional[torch.LongTensor] = None,
|
727 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
728 |
+
**kwargs,
|
729 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
730 |
+
"""
|
731 |
+
Args:
|
732 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
733 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
734 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
735 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
736 |
+
output_attentions (`bool`, *optional*):
|
737 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
738 |
+
returned tensors for more detail.
|
739 |
+
use_cache (`bool`, *optional*):
|
740 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
741 |
+
(see `past_key_values`).
|
742 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
743 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
744 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
745 |
+
position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
746 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
747 |
+
with `head_dim` being the embedding dimension of each attention head.
|
748 |
+
kwargs (`dict`, *optional*):
|
749 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
750 |
+
into the model
|
751 |
+
"""
|
752 |
+
residual = hidden_states
|
753 |
+
|
754 |
+
hidden_states = self.input_layernorm(hidden_states)
|
755 |
+
|
756 |
+
# Self Attention
|
757 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
758 |
+
hidden_states=hidden_states,
|
759 |
+
attention_mask=attention_mask,
|
760 |
+
position_ids=position_ids,
|
761 |
+
past_key_value=past_key_value,
|
762 |
+
output_attentions=output_attentions,
|
763 |
+
use_cache=use_cache,
|
764 |
+
cache_position=cache_position,
|
765 |
+
position_embeddings=position_embeddings,
|
766 |
+
**kwargs,
|
767 |
+
)
|
768 |
+
hidden_states = residual + hidden_states
|
769 |
+
|
770 |
+
# Fully Connected
|
771 |
+
residual = hidden_states
|
772 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
773 |
+
hidden_states = self.mlp(hidden_states)
|
774 |
+
hidden_states = residual + hidden_states
|
775 |
+
|
776 |
+
outputs = (hidden_states,)
|
777 |
+
|
778 |
+
if output_attentions:
|
779 |
+
outputs += (self_attn_weights,)
|
780 |
+
|
781 |
+
if use_cache:
|
782 |
+
outputs += (present_key_value,)
|
783 |
+
|
784 |
+
return outputs
|
785 |
+
|
786 |
+
|
787 |
+
Deepseek_START_DOCSTRING = r"""
|
788 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
789 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
790 |
+
etc.)
|
791 |
+
|
792 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
793 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
794 |
+
and behavior.
|
795 |
+
|
796 |
+
Parameters:
|
797 |
+
config ([`DeepseekConfig`]):
|
798 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
799 |
+
load the weights associated with the model, only the configuration. Check out the
|
800 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
801 |
+
"""
|
802 |
+
|
803 |
+
|
804 |
+
@add_start_docstrings(
|
805 |
+
"The bare Deepseek Model outputting raw hidden-states without any specific head on top.",
|
806 |
+
Deepseek_START_DOCSTRING,
|
807 |
+
)
|
808 |
+
class DeepseekPreTrainedModel(PreTrainedModel):
|
809 |
+
config_class = DeepseekConfig
|
810 |
+
base_model_prefix = "model"
|
811 |
+
supports_gradient_checkpointing = True
|
812 |
+
_no_split_modules = ["DeepseekDecoderLayer"]
|
813 |
+
_skip_keys_device_placement = "past_key_values"
|
814 |
+
_supports_flash_attn_2 = True
|
815 |
+
_supports_sdpa = True
|
816 |
+
_supports_cache_class = True
|
817 |
+
_supports_quantized_cache = True
|
818 |
+
_supports_static_cache = True
|
819 |
+
|
820 |
+
def _init_weights(self, module):
|
821 |
+
std = self.config.initializer_range
|
822 |
+
if isinstance(module, nn.Linear):
|
823 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
824 |
+
if module.bias is not None:
|
825 |
+
module.bias.data.zero_()
|
826 |
+
elif isinstance(module, nn.Embedding):
|
827 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
828 |
+
if module.padding_idx is not None:
|
829 |
+
module.weight.data[module.padding_idx].zero_()
|
830 |
+
|
831 |
+
|
832 |
+
Deepseek_INPUTS_DOCSTRING = r"""
|
833 |
+
Args:
|
834 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
835 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
836 |
+
it.
|
837 |
+
|
838 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
839 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
840 |
+
|
841 |
+
[What are input IDs?](../glossary#input-ids)
|
842 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
843 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
844 |
+
|
845 |
+
- 1 for tokens that are **not masked**,
|
846 |
+
- 0 for tokens that are **masked**.
|
847 |
+
|
848 |
+
[What are attention masks?](../glossary#attention-mask)
|
849 |
+
|
850 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
851 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
852 |
+
|
853 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
854 |
+
`past_key_values`).
|
855 |
+
|
856 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
857 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
858 |
+
information on the default strategy.
|
859 |
+
|
860 |
+
- 1 indicates the head is **not masked**,
|
861 |
+
- 0 indicates the head is **masked**.
|
862 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
863 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
864 |
+
config.n_positions - 1]`.
|
865 |
+
|
866 |
+
[What are position IDs?](../glossary#position-ids)
|
867 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
868 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
869 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
870 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
871 |
+
|
872 |
+
Two formats are allowed:
|
873 |
+
- a [`~cache_utils.Cache`] instance, see our
|
874 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
875 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
876 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
877 |
+
cache format.
|
878 |
+
|
879 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
880 |
+
legacy cache format will be returned.
|
881 |
+
|
882 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
883 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
884 |
+
of shape `(batch_size, sequence_length)`.
|
885 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
886 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
887 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
888 |
+
model's internal embedding lookup matrix.
|
889 |
+
use_cache (`bool`, *optional*):
|
890 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
891 |
+
`past_key_values`).
|
892 |
+
output_attentions (`bool`, *optional*):
|
893 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
894 |
+
tensors for more detail.
|
895 |
+
output_hidden_states (`bool`, *optional*):
|
896 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
897 |
+
more detail.
|
898 |
+
return_dict (`bool`, *optional*):
|
899 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
900 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
901 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
902 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
903 |
+
the complete sequence length.
|
904 |
+
"""
|
905 |
+
|
906 |
+
|
907 |
+
@add_start_docstrings(
|
908 |
+
"The bare Deepseek Model outputting raw hidden-states without any specific head on top.",
|
909 |
+
Deepseek_START_DOCSTRING,
|
910 |
+
)
|
911 |
+
class DeepseekModel(DeepseekPreTrainedModel):
|
912 |
+
"""
|
913 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekDecoderLayer`]
|
914 |
+
|
915 |
+
Args:
|
916 |
+
config: DeepseekConfig
|
917 |
+
"""
|
918 |
+
|
919 |
+
def __init__(self, config: DeepseekConfig):
|
920 |
+
super().__init__(config)
|
921 |
+
self.padding_idx = config.pad_token_id
|
922 |
+
self.vocab_size = config.vocab_size
|
923 |
+
|
924 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
925 |
+
self.layers = nn.ModuleList(
|
926 |
+
[DeepseekDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
927 |
+
)
|
928 |
+
self.norm = DeepseekRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
929 |
+
self.rotary_emb = DeepseekRotaryEmbedding(config=config)
|
930 |
+
|
931 |
+
self.gradient_checkpointing = False
|
932 |
+
if getattr(config, "pretraining_tp", 1) != 1:
|
933 |
+
logger.warn("`pretraining_tp` is deprecated, please use `model.tensor_parallel` instead.")
|
934 |
+
|
935 |
+
# Initialize weights and apply final processing
|
936 |
+
self.post_init()
|
937 |
+
|
938 |
+
def get_input_embeddings(self):
|
939 |
+
return self.embed_tokens
|
940 |
+
|
941 |
+
def set_input_embeddings(self, value):
|
942 |
+
self.embed_tokens = value
|
943 |
+
|
944 |
+
@add_start_docstrings_to_model_forward(Deepseek_INPUTS_DOCSTRING)
|
945 |
+
def forward(
|
946 |
+
self,
|
947 |
+
input_ids: torch.LongTensor = None,
|
948 |
+
attention_mask: Optional[torch.Tensor] = None,
|
949 |
+
position_ids: Optional[torch.LongTensor] = None,
|
950 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
951 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
952 |
+
use_cache: Optional[bool] = None,
|
953 |
+
output_attentions: Optional[bool] = None,
|
954 |
+
output_hidden_states: Optional[bool] = None,
|
955 |
+
return_dict: Optional[bool] = None,
|
956 |
+
cache_position: Optional[torch.LongTensor] = None,
|
957 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
958 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
959 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
960 |
+
output_hidden_states = (
|
961 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
962 |
+
)
|
963 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
964 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
965 |
+
|
966 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
967 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
968 |
+
|
969 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
970 |
+
logger.warning_once(
|
971 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
972 |
+
)
|
973 |
+
use_cache = False
|
974 |
+
|
975 |
+
if inputs_embeds is None:
|
976 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
977 |
+
|
978 |
+
# kept for BC (non `Cache` `past_key_values` inputs)
|
979 |
+
return_legacy_cache = False
|
980 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
981 |
+
return_legacy_cache = True
|
982 |
+
if past_key_values is None:
|
983 |
+
past_key_values = DynamicCache()
|
984 |
+
else:
|
985 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
986 |
+
logger.warning_once(
|
987 |
+
"We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
|
988 |
+
"will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
|
989 |
+
"(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
|
990 |
+
)
|
991 |
+
|
992 |
+
if cache_position is None:
|
993 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
994 |
+
cache_position = torch.arange(
|
995 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
996 |
+
)
|
997 |
+
if position_ids is None:
|
998 |
+
position_ids = cache_position.unsqueeze(0)
|
999 |
+
|
1000 |
+
causal_mask = self._update_causal_mask(
|
1001 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
1002 |
+
)
|
1003 |
+
hidden_states = inputs_embeds
|
1004 |
+
|
1005 |
+
# create position embeddings to be shared across the decoder layers
|
1006 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
1007 |
+
|
1008 |
+
# decoder layers
|
1009 |
+
all_hidden_states = () if output_hidden_states else None
|
1010 |
+
all_self_attns = () if output_attentions else None
|
1011 |
+
next_decoder_cache = None
|
1012 |
+
|
1013 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
1014 |
+
if output_hidden_states:
|
1015 |
+
all_hidden_states += (hidden_states,)
|
1016 |
+
|
1017 |
+
if self.gradient_checkpointing and self.training:
|
1018 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1019 |
+
decoder_layer.__call__,
|
1020 |
+
hidden_states,
|
1021 |
+
causal_mask,
|
1022 |
+
position_ids,
|
1023 |
+
past_key_values,
|
1024 |
+
output_attentions,
|
1025 |
+
use_cache,
|
1026 |
+
cache_position,
|
1027 |
+
position_embeddings,
|
1028 |
+
)
|
1029 |
+
else:
|
1030 |
+
layer_outputs = decoder_layer(
|
1031 |
+
hidden_states,
|
1032 |
+
attention_mask=causal_mask,
|
1033 |
+
position_ids=position_ids,
|
1034 |
+
past_key_value=past_key_values,
|
1035 |
+
output_attentions=output_attentions,
|
1036 |
+
use_cache=use_cache,
|
1037 |
+
cache_position=cache_position,
|
1038 |
+
position_embeddings=position_embeddings,
|
1039 |
+
**flash_attn_kwargs,
|
1040 |
+
)
|
1041 |
+
|
1042 |
+
hidden_states = layer_outputs[0]
|
1043 |
+
|
1044 |
+
if use_cache:
|
1045 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1046 |
+
|
1047 |
+
if output_attentions:
|
1048 |
+
all_self_attns += (layer_outputs[1],)
|
1049 |
+
|
1050 |
+
hidden_states = self.norm(hidden_states)
|
1051 |
+
|
1052 |
+
# add hidden states from the last decoder layer
|
1053 |
+
if output_hidden_states:
|
1054 |
+
all_hidden_states += (hidden_states,)
|
1055 |
+
|
1056 |
+
next_cache = next_decoder_cache if use_cache else None
|
1057 |
+
if return_legacy_cache:
|
1058 |
+
next_cache = next_cache.to_legacy_cache()
|
1059 |
+
|
1060 |
+
if not return_dict:
|
1061 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1062 |
+
return BaseModelOutputWithPast(
|
1063 |
+
last_hidden_state=hidden_states,
|
1064 |
+
past_key_values=next_cache,
|
1065 |
+
hidden_states=all_hidden_states,
|
1066 |
+
attentions=all_self_attns,
|
1067 |
+
)
|
1068 |
+
|
1069 |
+
def _update_causal_mask(
|
1070 |
+
self,
|
1071 |
+
attention_mask: torch.Tensor,
|
1072 |
+
input_tensor: torch.Tensor,
|
1073 |
+
cache_position: torch.Tensor,
|
1074 |
+
past_key_values: Cache,
|
1075 |
+
output_attentions: bool,
|
1076 |
+
):
|
1077 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1078 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1079 |
+
return attention_mask
|
1080 |
+
return None
|
1081 |
+
|
1082 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1083 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1084 |
+
# to infer the attention mask.
|
1085 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
1086 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
1087 |
+
|
1088 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
1089 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
1090 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
1091 |
+
attention_mask,
|
1092 |
+
inputs_embeds=input_tensor,
|
1093 |
+
past_key_values_length=past_seen_tokens,
|
1094 |
+
is_training=self.training,
|
1095 |
+
):
|
1096 |
+
return None
|
1097 |
+
|
1098 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1099 |
+
sequence_length = input_tensor.shape[1]
|
1100 |
+
if using_static_cache:
|
1101 |
+
target_length = past_key_values.get_max_cache_shape()
|
1102 |
+
else:
|
1103 |
+
target_length = (
|
1104 |
+
attention_mask.shape[-1]
|
1105 |
+
if isinstance(attention_mask, torch.Tensor)
|
1106 |
+
else past_seen_tokens + sequence_length + 1
|
1107 |
+
)
|
1108 |
+
|
1109 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
1110 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
1111 |
+
attention_mask,
|
1112 |
+
sequence_length=sequence_length,
|
1113 |
+
target_length=target_length,
|
1114 |
+
dtype=dtype,
|
1115 |
+
device=device,
|
1116 |
+
cache_position=cache_position,
|
1117 |
+
batch_size=input_tensor.shape[0],
|
1118 |
+
)
|
1119 |
+
|
1120 |
+
if (
|
1121 |
+
self.config._attn_implementation == "sdpa"
|
1122 |
+
and attention_mask is not None
|
1123 |
+
and attention_mask.device.type == "cuda"
|
1124 |
+
and not output_attentions
|
1125 |
+
):
|
1126 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1127 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1128 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1129 |
+
min_dtype = torch.finfo(dtype).min
|
1130 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
1131 |
+
|
1132 |
+
return causal_mask
|
1133 |
+
|
1134 |
+
@staticmethod
|
1135 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
1136 |
+
attention_mask: torch.Tensor,
|
1137 |
+
sequence_length: int,
|
1138 |
+
target_length: int,
|
1139 |
+
dtype: torch.dtype,
|
1140 |
+
device: torch.device,
|
1141 |
+
cache_position: torch.Tensor,
|
1142 |
+
batch_size: int,
|
1143 |
+
**kwargs,
|
1144 |
+
):
|
1145 |
+
"""
|
1146 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
1147 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
1148 |
+
|
1149 |
+
Args:
|
1150 |
+
attention_mask (`torch.Tensor`):
|
1151 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
1152 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
1153 |
+
sequence_length (`int`):
|
1154 |
+
The sequence length being processed.
|
1155 |
+
target_length (`int`):
|
1156 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
1157 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
1158 |
+
dtype (`torch.dtype`):
|
1159 |
+
The dtype to use for the 4D attention mask.
|
1160 |
+
device (`torch.device`):
|
1161 |
+
The device to plcae the 4D attention mask on.
|
1162 |
+
cache_position (`torch.Tensor`):
|
1163 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
1164 |
+
batch_size (`torch.Tensor`):
|
1165 |
+
Batch size.
|
1166 |
+
"""
|
1167 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
1168 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
1169 |
+
causal_mask = attention_mask
|
1170 |
+
else:
|
1171 |
+
min_dtype = torch.finfo(dtype).min
|
1172 |
+
causal_mask = torch.full(
|
1173 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
1174 |
+
)
|
1175 |
+
if sequence_length != 1:
|
1176 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
1177 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
1178 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
1179 |
+
if attention_mask is not None:
|
1180 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
1181 |
+
mask_length = attention_mask.shape[-1]
|
1182 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
1183 |
+
padding_mask = padding_mask == 0
|
1184 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
1185 |
+
padding_mask, min_dtype
|
1186 |
+
)
|
1187 |
+
|
1188 |
+
return causal_mask
|
1189 |
+
|
1190 |
+
|
1191 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
1192 |
+
|
1193 |
+
|
1194 |
+
class DeepseekForCausalLM(DeepseekPreTrainedModel, GenerationMixin):
|
1195 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1196 |
+
|
1197 |
+
def __init__(self, config):
|
1198 |
+
super().__init__(config)
|
1199 |
+
self.model = DeepseekModel(config)
|
1200 |
+
self.vocab_size = config.vocab_size
|
1201 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1202 |
+
|
1203 |
+
# Initialize weights and apply final processing
|
1204 |
+
self.post_init()
|
1205 |
+
|
1206 |
+
def get_input_embeddings(self):
|
1207 |
+
return self.model.embed_tokens
|
1208 |
+
|
1209 |
+
def set_input_embeddings(self, value):
|
1210 |
+
self.model.embed_tokens = value
|
1211 |
+
|
1212 |
+
def get_output_embeddings(self):
|
1213 |
+
return self.lm_head
|
1214 |
+
|
1215 |
+
def set_output_embeddings(self, new_embeddings):
|
1216 |
+
self.lm_head = new_embeddings
|
1217 |
+
|
1218 |
+
def set_decoder(self, decoder):
|
1219 |
+
self.model = decoder
|
1220 |
+
|
1221 |
+
def get_decoder(self):
|
1222 |
+
return self.model
|
1223 |
+
|
1224 |
+
@add_start_docstrings_to_model_forward(Deepseek_INPUTS_DOCSTRING)
|
1225 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1226 |
+
def forward(
|
1227 |
+
self,
|
1228 |
+
input_ids: torch.LongTensor = None,
|
1229 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1230 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1231 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1232 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1233 |
+
labels: Optional[torch.LongTensor] = None,
|
1234 |
+
use_cache: Optional[bool] = None,
|
1235 |
+
output_attentions: Optional[bool] = None,
|
1236 |
+
output_hidden_states: Optional[bool] = None,
|
1237 |
+
return_dict: Optional[bool] = None,
|
1238 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1239 |
+
num_logits_to_keep: int = 0,
|
1240 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
1241 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1242 |
+
r"""
|
1243 |
+
Args:
|
1244 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1245 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1246 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1247 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1248 |
+
|
1249 |
+
num_logits_to_keep (`int`, *optional*):
|
1250 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
1251 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
1252 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
1253 |
+
|
1254 |
+
Returns:
|
1255 |
+
|
1256 |
+
Example:
|
1257 |
+
|
1258 |
+
```python
|
1259 |
+
>>> from transformers import AutoTokenizer
|
1260 |
+
|
1261 |
+
>>> model = DeepseekForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1262 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1263 |
+
|
1264 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1265 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1266 |
+
|
1267 |
+
>>> # Generate
|
1268 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1269 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1270 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1271 |
+
```"""
|
1272 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1273 |
+
output_hidden_states = (
|
1274 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1275 |
+
)
|
1276 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1277 |
+
|
1278 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1279 |
+
outputs = self.model(
|
1280 |
+
input_ids=input_ids,
|
1281 |
+
attention_mask=attention_mask,
|
1282 |
+
position_ids=position_ids,
|
1283 |
+
past_key_values=past_key_values,
|
1284 |
+
inputs_embeds=inputs_embeds,
|
1285 |
+
use_cache=use_cache,
|
1286 |
+
output_attentions=output_attentions,
|
1287 |
+
output_hidden_states=output_hidden_states,
|
1288 |
+
return_dict=return_dict,
|
1289 |
+
)
|
1290 |
+
|
1291 |
+
hidden_states = outputs[0]
|
1292 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
1293 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
1294 |
+
|
1295 |
+
loss = None
|
1296 |
+
if labels is not None:
|
1297 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
1298 |
+
|
1299 |
+
if not return_dict:
|
1300 |
+
output = (logits,) + outputs[1:]
|
1301 |
+
return (loss,) + output if loss is not None else output
|
1302 |
+
|
1303 |
+
return CausalLMOutputWithPast(
|
1304 |
+
loss=loss,
|
1305 |
+
logits=logits,
|
1306 |
+
past_key_values=outputs.past_key_values,
|
1307 |
+
hidden_states=outputs.hidden_states,
|
1308 |
+
attentions=outputs.attentions,
|
1309 |
+
)
|
1310 |
+
|
1311 |
+
|
1312 |
+
@add_start_docstrings(
|
1313 |
+
"""
|
1314 |
+
The Deepseek Model transformer with a sequence classification head on top (linear layer).
|
1315 |
+
|
1316 |
+
[`DeepseekForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1317 |
+
(e.g. GPT-2) do.
|
1318 |
+
|
1319 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1320 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1321 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1322 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1323 |
+
each row of the batch).
|
1324 |
+
""",
|
1325 |
+
Deepseek_START_DOCSTRING,
|
1326 |
+
)
|
1327 |
+
class DeepseekForSequenceClassification(DeepseekPreTrainedModel):
|
1328 |
+
def __init__(self, config):
|
1329 |
+
super().__init__(config)
|
1330 |
+
self.num_labels = config.num_labels
|
1331 |
+
self.model = DeepseekModel(config)
|
1332 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1333 |
+
|
1334 |
+
# Initialize weights and apply final processing
|
1335 |
+
self.post_init()
|
1336 |
+
|
1337 |
+
def get_input_embeddings(self):
|
1338 |
+
return self.model.embed_tokens
|
1339 |
+
|
1340 |
+
def set_input_embeddings(self, value):
|
1341 |
+
self.model.embed_tokens = value
|
1342 |
+
|
1343 |
+
@add_start_docstrings_to_model_forward(Deepseek_INPUTS_DOCSTRING)
|
1344 |
+
def forward(
|
1345 |
+
self,
|
1346 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1347 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1348 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1349 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1350 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1351 |
+
labels: Optional[torch.LongTensor] = None,
|
1352 |
+
use_cache: Optional[bool] = None,
|
1353 |
+
output_attentions: Optional[bool] = None,
|
1354 |
+
output_hidden_states: Optional[bool] = None,
|
1355 |
+
return_dict: Optional[bool] = None,
|
1356 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1357 |
+
r"""
|
1358 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1359 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1360 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1361 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1362 |
+
"""
|
1363 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1364 |
+
|
1365 |
+
transformer_outputs = self.model(
|
1366 |
+
input_ids,
|
1367 |
+
attention_mask=attention_mask,
|
1368 |
+
position_ids=position_ids,
|
1369 |
+
past_key_values=past_key_values,
|
1370 |
+
inputs_embeds=inputs_embeds,
|
1371 |
+
use_cache=use_cache,
|
1372 |
+
output_attentions=output_attentions,
|
1373 |
+
output_hidden_states=output_hidden_states,
|
1374 |
+
return_dict=return_dict,
|
1375 |
+
)
|
1376 |
+
hidden_states = transformer_outputs[0]
|
1377 |
+
logits = self.score(hidden_states)
|
1378 |
+
|
1379 |
+
if input_ids is not None:
|
1380 |
+
batch_size = input_ids.shape[0]
|
1381 |
+
else:
|
1382 |
+
batch_size = inputs_embeds.shape[0]
|
1383 |
+
|
1384 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1385 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1386 |
+
if self.config.pad_token_id is None:
|
1387 |
+
sequence_lengths = -1
|
1388 |
+
else:
|
1389 |
+
if input_ids is not None:
|
1390 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1391 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1392 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1393 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1394 |
+
else:
|
1395 |
+
sequence_lengths = -1
|
1396 |
+
|
1397 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1398 |
+
|
1399 |
+
loss = None
|
1400 |
+
if labels is not None:
|
1401 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
1402 |
+
|
1403 |
+
if not return_dict:
|
1404 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1405 |
+
return ((loss,) + output) if loss is not None else output
|
1406 |
+
|
1407 |
+
return SequenceClassifierOutputWithPast(
|
1408 |
+
loss=loss,
|
1409 |
+
logits=pooled_logits,
|
1410 |
+
past_key_values=transformer_outputs.past_key_values,
|
1411 |
+
hidden_states=transformer_outputs.hidden_states,
|
1412 |
+
attentions=transformer_outputs.attentions,
|
1413 |
+
)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|role_sep|>",
|
4 |
+
"<|message_sep|>",
|
5 |
+
"[",
|
6 |
+
"]",
|
7 |
+
{
|
8 |
+
"content": "<|role_sep|>",
|
9 |
+
"lstrip": false,
|
10 |
+
"normalized": false,
|
11 |
+
"rstrip": false,
|
12 |
+
"single_word": false
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"content": "<|message_sep|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"content": "[",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false
|
27 |
+
},
|
28 |
+
{
|
29 |
+
"content": "]",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": false,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false
|
34 |
+
}
|
35 |
+
],
|
36 |
+
"bos_token": {
|
37 |
+
"content": "<s>",
|
38 |
+
"lstrip": false,
|
39 |
+
"normalized": false,
|
40 |
+
"rstrip": false,
|
41 |
+
"single_word": false
|
42 |
+
},
|
43 |
+
"eos_token": {
|
44 |
+
"content": "<|message_sep|>",
|
45 |
+
"lstrip": false,
|
46 |
+
"normalized": false,
|
47 |
+
"rstrip": false,
|
48 |
+
"single_word": false
|
49 |
+
}
|
50 |
+
}
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6fc8146adda45ec7f4876d832f80b55e8dd3e1fa648fbd54d059a601ee73cea3
|
3 |
+
size 10678892
|
tokenizer_config.json
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens": {
|
3 |
+
"1": {
|
4 |
+
"content": "<s>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"128000": {
|
12 |
+
"content": "<|role_sep|>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"128001": {
|
20 |
+
"content": "<|message_sep|>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"61": {
|
28 |
+
"content": "[",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"63": {
|
36 |
+
"content": "]",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
}
|
43 |
+
},
|
44 |
+
"added_tokens_decoder": {
|
45 |
+
"1": {
|
46 |
+
"content": "<s>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"61": {
|
54 |
+
"content": "[",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"63": {
|
62 |
+
"content": "]",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"128000": {
|
70 |
+
"content": "<|role_sep|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"128001": {
|
78 |
+
"content": "<|message_sep|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
}
|
85 |
+
},
|
86 |
+
"additional_special_tokens": [
|
87 |
+
"<|role_sep|>",
|
88 |
+
"<|message_sep|>",
|
89 |
+
"[",
|
90 |
+
"]",
|
91 |
+
"<|role_sep|>",
|
92 |
+
"<|message_sep|>",
|
93 |
+
"[",
|
94 |
+
"]"
|
95 |
+
],
|
96 |
+
"bos_token": "<s>",
|
97 |
+
"chat_template": "{% if messages[0]['role'] == 'system' -%}\n {%- set loop_messages = messages[1:] -%}\n {%- set system_message = bos_token + messages[0]['content'] + additional_special_tokens[1] -%}\n{%- else -%}\n {%- set loop_messages = messages -%}\n {%- set system_message = bos_token + '' -%}\n{%- endif -%}\n{%- for message in loop_messages %}\n {% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}\n {{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}\n {% endif %}\n \n {%- if loop.index0 == 0 -%}\n {{ system_message -}}\n {%- endif -%}\n {%- if message['role'] == 'user' -%}\n {{ message['role'] + additional_special_tokens[0] + message['content'] + additional_special_tokens[1] -}}\n {{ 'available functions' + additional_special_tokens[0] + additional_special_tokens[2] + additional_special_tokens[3] + additional_special_tokens[1] -}}\n {%- endif -%}\n {%- if message['role'] == 'assistant' -%}\n {{ message['role'] + additional_special_tokens[0] + message['content'] + additional_special_tokens[1] -}}\n {%- endif -%}\n {%- if loop.last and add_generation_prompt -%}\n {{ 'assistant' + additional_special_tokens[0] -}}\n {%- endif -%}\n{%- endfor %}",
|
98 |
+
"clean_up_tokenization_spaces": true,
|
99 |
+
"eos_token": "<|message_sep|>",
|
100 |
+
"extra_special_tokens": {},
|
101 |
+
"model_max_length": 1000000000000000019884624838656,
|
102 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
103 |
+
"unk_token": null
|
104 |
+
}
|