Upload 4 files
Browse files- configuration_qwen.py +71 -0
- modeling_qwen_yarn.py +1522 -0
- qwen_generation_utils.py +416 -0
- tokenization_qwen.py +276 -0
configuration_qwen.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Alibaba Cloud.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
from transformers import PretrainedConfig
|
7 |
+
|
8 |
+
|
9 |
+
class QWenConfig(PretrainedConfig):
|
10 |
+
model_type = "qwen"
|
11 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
12 |
+
|
13 |
+
def __init__(
|
14 |
+
self,
|
15 |
+
vocab_size=151936,
|
16 |
+
hidden_size=4096,
|
17 |
+
num_hidden_layers=32,
|
18 |
+
num_attention_heads=32,
|
19 |
+
emb_dropout_prob=0.0,
|
20 |
+
attn_dropout_prob=0.0,
|
21 |
+
layer_norm_epsilon=1e-6,
|
22 |
+
initializer_range=0.02,
|
23 |
+
max_position_embeddings=8192,
|
24 |
+
scale_attn_weights=True,
|
25 |
+
use_cache=True,
|
26 |
+
bf16=False,
|
27 |
+
fp16=False,
|
28 |
+
fp32=False,
|
29 |
+
kv_channels=128,
|
30 |
+
rotary_pct=1.0,
|
31 |
+
rotary_emb_base=10000,
|
32 |
+
use_dynamic_ntk=True,
|
33 |
+
use_logn_attn=True,
|
34 |
+
use_flash_attn="auto",
|
35 |
+
intermediate_size=22016,
|
36 |
+
no_bias=True,
|
37 |
+
tie_word_embeddings=False,
|
38 |
+
use_cache_quantization=False,
|
39 |
+
use_cache_kernel=False,
|
40 |
+
softmax_in_fp32=False,
|
41 |
+
**kwargs,
|
42 |
+
):
|
43 |
+
self.vocab_size = vocab_size
|
44 |
+
self.hidden_size = hidden_size
|
45 |
+
self.intermediate_size = intermediate_size
|
46 |
+
self.num_hidden_layers = num_hidden_layers
|
47 |
+
self.num_attention_heads = num_attention_heads
|
48 |
+
self.emb_dropout_prob = emb_dropout_prob
|
49 |
+
self.attn_dropout_prob = attn_dropout_prob
|
50 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
51 |
+
self.initializer_range = initializer_range
|
52 |
+
self.scale_attn_weights = scale_attn_weights
|
53 |
+
self.use_cache = use_cache
|
54 |
+
self.max_position_embeddings = max_position_embeddings
|
55 |
+
self.bf16 = bf16
|
56 |
+
self.fp16 = fp16
|
57 |
+
self.fp32 = fp32
|
58 |
+
self.kv_channels = kv_channels
|
59 |
+
self.rotary_pct = rotary_pct
|
60 |
+
self.rotary_emb_base = rotary_emb_base
|
61 |
+
self.use_dynamic_ntk = use_dynamic_ntk
|
62 |
+
self.use_logn_attn = use_logn_attn
|
63 |
+
self.use_flash_attn = use_flash_attn
|
64 |
+
self.no_bias = no_bias
|
65 |
+
self.use_cache_quantization = use_cache_quantization
|
66 |
+
self.use_cache_kernel = use_cache_kernel
|
67 |
+
self.softmax_in_fp32 = softmax_in_fp32
|
68 |
+
super().__init__(
|
69 |
+
tie_word_embeddings=tie_word_embeddings,
|
70 |
+
**kwargs
|
71 |
+
)
|
modeling_qwen_yarn.py
ADDED
@@ -0,0 +1,1522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Alibaba Cloud.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
import importlib
|
7 |
+
import math
|
8 |
+
from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
import torch.utils.checkpoint
|
13 |
+
from torch.cuda.amp import autocast
|
14 |
+
|
15 |
+
from torch.nn import CrossEntropyLoss
|
16 |
+
from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
|
17 |
+
from transformers.generation.logits_process import LogitsProcessorList
|
18 |
+
|
19 |
+
if TYPE_CHECKING:
|
20 |
+
from transformers.generation.streamers import BaseStreamer
|
21 |
+
from transformers.generation.utils import GenerateOutput
|
22 |
+
from transformers.modeling_outputs import (
|
23 |
+
BaseModelOutputWithPast,
|
24 |
+
CausalLMOutputWithPast,
|
25 |
+
)
|
26 |
+
from transformers.modeling_utils import PreTrainedModel
|
27 |
+
from transformers.utils import logging
|
28 |
+
|
29 |
+
try:
|
30 |
+
from einops import rearrange
|
31 |
+
except ImportError:
|
32 |
+
rearrange = None
|
33 |
+
from torch import nn
|
34 |
+
|
35 |
+
try:
|
36 |
+
from kernels.cpp_kernels import cache_autogptq_cuda_256
|
37 |
+
except ImportError:
|
38 |
+
cache_autogptq_cuda_256 = None
|
39 |
+
|
40 |
+
SUPPORT_CUDA = torch.cuda.is_available()
|
41 |
+
SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
|
42 |
+
SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
|
43 |
+
|
44 |
+
from .configuration_qwen import QWenConfig
|
45 |
+
from .qwen_generation_utils import (
|
46 |
+
HistoryType,
|
47 |
+
make_context,
|
48 |
+
decode_tokens,
|
49 |
+
get_stop_words_ids,
|
50 |
+
StopWordsLogitsProcessor,
|
51 |
+
)
|
52 |
+
from flash_attn.bert_padding import unpad_input, pad_input
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
_CHECKPOINT_FOR_DOC = "qwen"
|
57 |
+
_CONFIG_FOR_DOC = "QWenConfig"
|
58 |
+
|
59 |
+
QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
|
60 |
+
|
61 |
+
_ERROR_BAD_CHAT_FORMAT = """\
|
62 |
+
We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml".
|
63 |
+
If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat().
|
64 |
+
我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
|
65 |
+
如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
|
66 |
+
"""
|
67 |
+
|
68 |
+
_SENTINEL = object()
|
69 |
+
_ERROR_STREAM_IN_CHAT = """\
|
70 |
+
Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
|
71 |
+
向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
|
72 |
+
"""
|
73 |
+
|
74 |
+
_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\
|
75 |
+
We detect you have activated flash attention support, but running model computation on CPU. Please make sure that your input data has been placed on GPU. If you actually want to run CPU computation, please following the readme and set device_map="cpu" to disable flash attention when loading the model (calling AutoModelForCausalLM.from_pretrained).
|
76 |
+
检测到您的模型已激活了flash attention支持,但正在执行CPU运算任务。如使用flash attention,请您确认模型输入已经传到GPU上。如果您确认要执行CPU运算,请您在载入模型(调用AutoModelForCausalLM.from_pretrained)时,按照readme说法,指定device_map="cpu"以禁用flash attention。
|
77 |
+
"""
|
78 |
+
|
79 |
+
apply_rotary_emb_func = None
|
80 |
+
rms_norm = None
|
81 |
+
flash_attn_unpadded_func = None
|
82 |
+
|
83 |
+
def _import_flash_attn():
|
84 |
+
global apply_rotary_emb_func, rms_norm, flash_attn_unpadded_func
|
85 |
+
try:
|
86 |
+
from flash_attn.layers.rotary import apply_rotary_emb_func as __apply_rotary_emb_func
|
87 |
+
apply_rotary_emb_func = __apply_rotary_emb_func
|
88 |
+
except ImportError:
|
89 |
+
logger.warn(
|
90 |
+
"Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency "
|
91 |
+
"https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary"
|
92 |
+
)
|
93 |
+
|
94 |
+
try:
|
95 |
+
from flash_attn.ops.rms_norm import rms_norm as __rms_norm
|
96 |
+
rms_norm = __rms_norm
|
97 |
+
except ImportError:
|
98 |
+
logger.warn(
|
99 |
+
"Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
|
100 |
+
"https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
|
101 |
+
)
|
102 |
+
|
103 |
+
try:
|
104 |
+
import flash_attn
|
105 |
+
if not hasattr(flash_attn, '__version__'):
|
106 |
+
from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
|
107 |
+
else:
|
108 |
+
if int(flash_attn.__version__.split(".")[0]) >= 2:
|
109 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_func as __flash_attn_unpadded_func
|
110 |
+
else:
|
111 |
+
from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
|
112 |
+
flash_attn_unpadded_func = __flash_attn_unpadded_func
|
113 |
+
except ImportError:
|
114 |
+
logger.warn(
|
115 |
+
"Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
|
116 |
+
"https://github.com/Dao-AILab/flash-attention"
|
117 |
+
)
|
118 |
+
|
119 |
+
def quantize_cache_v(fdata, bits, qmax, qmin):
|
120 |
+
# b, s, head, h-dim->b, head, s, h-dim
|
121 |
+
qtype = torch.uint8
|
122 |
+
device = fdata.device
|
123 |
+
shape = fdata.shape
|
124 |
+
|
125 |
+
fdata_cal = torch.flatten(fdata, 2)
|
126 |
+
fmax = torch.amax(fdata_cal, dim=-1, keepdim=True)
|
127 |
+
fmin = torch.amin(fdata_cal, dim=-1, keepdim=True)
|
128 |
+
# Compute params
|
129 |
+
if qmax.device != fmax.device:
|
130 |
+
qmax = qmax.to(device)
|
131 |
+
qmin = qmin.to(device)
|
132 |
+
scale = (fmax - fmin) / (qmax - qmin)
|
133 |
+
zero = qmin - fmin / scale
|
134 |
+
scale = scale.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
|
135 |
+
zero = zero.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
|
136 |
+
# Quantize
|
137 |
+
res_data = fdata / scale + zero
|
138 |
+
qdata = torch.clamp(res_data, qmin, qmax).to(qtype)
|
139 |
+
return qdata.contiguous(), scale, zero
|
140 |
+
|
141 |
+
def dequantize_cache_torch(qdata, scale, zero):
|
142 |
+
data = scale * (qdata - zero)
|
143 |
+
return data
|
144 |
+
|
145 |
+
class FlashSelfAttention(torch.nn.Module):
|
146 |
+
def __init__(
|
147 |
+
self,
|
148 |
+
causal=False,
|
149 |
+
softmax_scale=None,
|
150 |
+
attention_dropout=0.0,
|
151 |
+
):
|
152 |
+
super().__init__()
|
153 |
+
assert flash_attn_unpadded_func is not None, (
|
154 |
+
"Please install FlashAttention first, " "e.g., with pip install flash-attn"
|
155 |
+
)
|
156 |
+
assert (
|
157 |
+
rearrange is not None
|
158 |
+
), "Please install einops first, e.g., with pip install einops"
|
159 |
+
self.causal = causal
|
160 |
+
self.softmax_scale = softmax_scale
|
161 |
+
self.dropout_p = attention_dropout
|
162 |
+
|
163 |
+
def unpad_input(self, hidden_states, attention_mask):
|
164 |
+
valid_mask = attention_mask.squeeze(1).squeeze(1).eq(0)
|
165 |
+
seqlens_in_batch = valid_mask.sum(dim=-1, dtype=torch.int32)
|
166 |
+
indices = torch.nonzero(valid_mask.flatten(), as_tuple=False).flatten()
|
167 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
168 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
169 |
+
hidden_states = hidden_states[indices]
|
170 |
+
return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
|
171 |
+
|
172 |
+
def pad_input(self, hidden_states, indices, batch, seqlen):
|
173 |
+
#torch.cuda.empty_cache()
|
174 |
+
output = torch.zeros(batch * seqlen, *hidden_states.shape[1:], device=hidden_states.device,
|
175 |
+
dtype=hidden_states.dtype)
|
176 |
+
output[indices] = hidden_states
|
177 |
+
return rearrange(output, '(b s) ... -> b s ...', b=batch)
|
178 |
+
|
179 |
+
def forward(self, q, k, v, attention_mask=None):
|
180 |
+
assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
|
181 |
+
assert all((i.is_cuda for i in (q, k, v)))
|
182 |
+
q_len_origin=q.shape[1]
|
183 |
+
batch_size, seqlen_q = q.shape[0], q.shape[1]
|
184 |
+
seqlen_k = k.shape[1]
|
185 |
+
|
186 |
+
q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
|
187 |
+
cu_seqlens_q = torch.arange(
|
188 |
+
0,
|
189 |
+
(batch_size + 1) * seqlen_q,
|
190 |
+
step=seqlen_q,
|
191 |
+
dtype=torch.int32,
|
192 |
+
device=q.device,
|
193 |
+
)
|
194 |
+
|
195 |
+
if attention_mask is not None:
|
196 |
+
k, indices_k, cu_seqlens_k, seqlen_k = self.unpad_input(k, attention_mask)
|
197 |
+
v = v[indices_k]
|
198 |
+
if self.training or q.size(0) == k.size(0):
|
199 |
+
q = q[indices_k]
|
200 |
+
cu_seqlens_q = cu_seqlens_k
|
201 |
+
seqlen_q = seqlen_k
|
202 |
+
else:
|
203 |
+
cu_seqlens_k = torch.arange(
|
204 |
+
0,
|
205 |
+
(batch_size + 1) * seqlen_k,
|
206 |
+
step=seqlen_k,
|
207 |
+
dtype=torch.int32,
|
208 |
+
device=q.device,
|
209 |
+
)
|
210 |
+
|
211 |
+
if self.training:
|
212 |
+
assert seqlen_k == seqlen_q
|
213 |
+
is_causal = self.causal
|
214 |
+
dropout_p = self.dropout_p
|
215 |
+
else:
|
216 |
+
is_causal = seqlen_q == seqlen_k
|
217 |
+
dropout_p = 0
|
218 |
+
|
219 |
+
output = flash_attn_unpadded_func(
|
220 |
+
q,
|
221 |
+
k,
|
222 |
+
v,
|
223 |
+
cu_seqlens_q,
|
224 |
+
cu_seqlens_k,
|
225 |
+
seqlen_q,
|
226 |
+
seqlen_k,
|
227 |
+
dropout_p,
|
228 |
+
softmax_scale=self.softmax_scale,
|
229 |
+
causal=is_causal,
|
230 |
+
)
|
231 |
+
if attention_mask is not None and seqlen_q == seqlen_k:
|
232 |
+
output = self.pad_input(output, indices_k, batch_size, seqlen_q)
|
233 |
+
|
234 |
+
|
235 |
+
else:
|
236 |
+
new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
|
237 |
+
output = output.view(new_shape)
|
238 |
+
return output
|
239 |
+
|
240 |
+
|
241 |
+
class QWenAttention(nn.Module):
|
242 |
+
def __init__(self, config):
|
243 |
+
super().__init__()
|
244 |
+
|
245 |
+
self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
|
246 |
+
self.seq_length = config.seq_length
|
247 |
+
|
248 |
+
self.hidden_size = config.hidden_size
|
249 |
+
self.split_size = config.hidden_size
|
250 |
+
self.num_heads = config.num_attention_heads
|
251 |
+
self.head_dim = self.hidden_size // self.num_heads
|
252 |
+
|
253 |
+
self.use_flash_attn = config.use_flash_attn
|
254 |
+
self.scale_attn_weights = True
|
255 |
+
|
256 |
+
self.projection_size = config.kv_channels * config.num_attention_heads
|
257 |
+
|
258 |
+
assert self.projection_size % config.num_attention_heads == 0
|
259 |
+
self.hidden_size_per_attention_head = (
|
260 |
+
self.projection_size // config.num_attention_heads
|
261 |
+
)
|
262 |
+
|
263 |
+
self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
|
264 |
+
|
265 |
+
self.c_proj = nn.Linear(
|
266 |
+
config.hidden_size, self.projection_size, bias=not config.no_bias
|
267 |
+
)
|
268 |
+
|
269 |
+
self.is_fp32 = not (config.bf16 or config.fp16)
|
270 |
+
if (
|
271 |
+
self.use_flash_attn
|
272 |
+
and flash_attn_unpadded_func is not None
|
273 |
+
and not self.is_fp32
|
274 |
+
):
|
275 |
+
self.core_attention_flash = FlashSelfAttention(
|
276 |
+
causal=True, attention_dropout=config.attn_dropout_prob
|
277 |
+
)
|
278 |
+
self.bf16 = config.bf16
|
279 |
+
|
280 |
+
self.use_dynamic_ntk = config.use_dynamic_ntk
|
281 |
+
self.use_logn_attn = config.use_logn_attn
|
282 |
+
|
283 |
+
logn_list = [
|
284 |
+
math.log(i, self.seq_length) if i > self.seq_length else 1
|
285 |
+
for i in range(1, 32768)
|
286 |
+
]
|
287 |
+
logn_tensor = torch.tensor(logn_list)[None, :, None, None]
|
288 |
+
self.register_buffer("logn_tensor", logn_tensor, persistent=False)
|
289 |
+
|
290 |
+
self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
|
291 |
+
self.use_cache_quantization = config.use_cache_quantization if hasattr(config, 'use_cache_quantization') else False
|
292 |
+
self.use_cache_kernel = config.use_cache_kernel if hasattr(config,'use_cache_kernel') else False
|
293 |
+
cache_dtype = torch.float
|
294 |
+
if self.bf16:
|
295 |
+
cache_dtype=torch.bfloat16
|
296 |
+
elif config.fp16:
|
297 |
+
cache_dtype = torch.float16
|
298 |
+
self.cache_qmax = torch.tensor(torch.iinfo(torch.uint8).max, dtype=cache_dtype)
|
299 |
+
self.cache_qmin = torch.tensor(torch.iinfo(torch.uint8).min, dtype=cache_dtype)
|
300 |
+
|
301 |
+
def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None):
|
302 |
+
device = query.device
|
303 |
+
if self.use_cache_quantization:
|
304 |
+
qk, qk_scale, qk_zero = key
|
305 |
+
if self.use_cache_kernel and cache_autogptq_cuda_256 is not None:
|
306 |
+
shape = query.shape[:-1] + (qk.shape[-2],)
|
307 |
+
attn_weights = torch.zeros(shape, dtype=torch.float16, device=device)
|
308 |
+
cache_autogptq_cuda_256.vecquant8matmul_batched_faster_old(
|
309 |
+
query.contiguous() if query.dtype == torch.float16 else query.to(torch.float16).contiguous(),
|
310 |
+
qk.transpose(-1, -2).contiguous(),
|
311 |
+
attn_weights,
|
312 |
+
qk_scale.contiguous() if qk_scale.dtype == torch.float16 else qk_scale.to(torch.float16).contiguous(),
|
313 |
+
qk_zero.contiguous()if qk_zero.dtype == torch.float16 else qk_zero.to(torch.float16).contiguous())
|
314 |
+
# attn_weights = attn_weights.to(query.dtype).contiguous()
|
315 |
+
else:
|
316 |
+
key = dequantize_cache_torch(qk, qk_scale, qk_zero)
|
317 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2))
|
318 |
+
else:
|
319 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2))
|
320 |
+
|
321 |
+
if self.scale_attn_weights:
|
322 |
+
if self.use_cache_quantization:
|
323 |
+
size_temp = value[0].size(-1)
|
324 |
+
else:
|
325 |
+
size_temp = value.size(-1)
|
326 |
+
attn_weights = attn_weights / torch.full(
|
327 |
+
[],
|
328 |
+
size_temp ** 0.5,
|
329 |
+
dtype=attn_weights.dtype,
|
330 |
+
device=attn_weights.device,
|
331 |
+
)
|
332 |
+
if self.use_cache_quantization:
|
333 |
+
query_length, key_length = query.size(-2), key[0].size(-2)
|
334 |
+
else:
|
335 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
336 |
+
causal_mask = registered_causal_mask[
|
337 |
+
:, :, key_length - query_length : key_length, :key_length
|
338 |
+
]
|
339 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
340 |
+
mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
|
341 |
+
attn_weights.device
|
342 |
+
)
|
343 |
+
attn_weights = torch.where(
|
344 |
+
causal_mask, attn_weights.to(attn_weights.dtype), mask_value
|
345 |
+
)
|
346 |
+
|
347 |
+
if attention_mask is not None:
|
348 |
+
attn_weights = attn_weights + attention_mask
|
349 |
+
|
350 |
+
attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)
|
351 |
+
|
352 |
+
attn_weights = attn_weights.type(query.dtype)
|
353 |
+
attn_weights = self.attn_dropout(attn_weights)
|
354 |
+
|
355 |
+
if head_mask is not None:
|
356 |
+
attn_weights = attn_weights * head_mask
|
357 |
+
|
358 |
+
if self.use_cache_quantization:
|
359 |
+
qv, qv_scale, qv_zero = value
|
360 |
+
if self.use_cache_kernel and cache_autogptq_cuda_256 is not None:
|
361 |
+
shape = attn_weights.shape[:-1] + (query.shape[-1],)
|
362 |
+
attn_output = torch.zeros(shape, dtype=torch.float16, device=device)
|
363 |
+
cache_autogptq_cuda_256.vecquant8matmul_batched_column_compression_faster_old(
|
364 |
+
attn_weights.contiguous() if attn_weights.dtype == torch.float16 else attn_weights.to(torch.float16).contiguous(),
|
365 |
+
qv.contiguous(), # dtype: int32
|
366 |
+
attn_output,
|
367 |
+
qv_scale.contiguous() if qv_scale.dtype == torch.float16 else qv_scale.to(torch.float16).contiguous(),
|
368 |
+
qv_zero.contiguous() if qv_zero.dtype == torch.float16 else qv_zero.to(torch.float16).contiguous())
|
369 |
+
if attn_output.dtype != query.dtype:
|
370 |
+
attn_output = attn_output.to(query.dtype)
|
371 |
+
attn_weights = attn_weights.to(query.dtype)
|
372 |
+
else:
|
373 |
+
value = dequantize_cache_torch(qv, qv_scale, qv_zero)
|
374 |
+
attn_output = torch.matmul(attn_weights, value)
|
375 |
+
else:
|
376 |
+
attn_output = torch.matmul(attn_weights, value)
|
377 |
+
|
378 |
+
attn_output = attn_output.transpose(1, 2)
|
379 |
+
|
380 |
+
return attn_output, attn_weights
|
381 |
+
|
382 |
+
def _upcast_and_reordered_attn(
|
383 |
+
self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None
|
384 |
+
):
|
385 |
+
bsz, num_heads, q_seq_len, dk = query.size()
|
386 |
+
_, _, k_seq_len, _ = key.size()
|
387 |
+
|
388 |
+
attn_weights = torch.empty(
|
389 |
+
bsz * num_heads,
|
390 |
+
q_seq_len,
|
391 |
+
k_seq_len,
|
392 |
+
dtype=torch.float32,
|
393 |
+
device=query.device,
|
394 |
+
)
|
395 |
+
|
396 |
+
scale_factor = 1.0
|
397 |
+
if self.scale_attn_weights:
|
398 |
+
scale_factor /= float(value.size(-1)) ** 0.5
|
399 |
+
|
400 |
+
with autocast(enabled=False):
|
401 |
+
q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
|
402 |
+
-1, dk, k_seq_len
|
403 |
+
)
|
404 |
+
attn_weights = torch.baddbmm(
|
405 |
+
attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
|
406 |
+
)
|
407 |
+
attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
|
408 |
+
|
409 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
410 |
+
causal_mask = registered_causal_mask[
|
411 |
+
:, :, key_length - query_length : key_length, :key_length
|
412 |
+
] #registered_causal_mask是shape为(1, 1, max_positions, max_positions)的二值张量,其中max_positions为8192
|
413 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
414 |
+
mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
|
415 |
+
attn_weights.device
|
416 |
+
)
|
417 |
+
attn_weights = torch.where(causal_mask, attn_weights, mask_value) #causal_mask中为1的位置,attn_weights中保留,否则用mask_value填充
|
418 |
+
|
419 |
+
if attention_mask is not None:
|
420 |
+
attn_weights = attn_weights + attention_mask
|
421 |
+
|
422 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
423 |
+
|
424 |
+
if attn_weights.dtype != torch.float32:
|
425 |
+
raise RuntimeError(
|
426 |
+
"Error with upcasting, attn_weights does not have dtype torch.float32"
|
427 |
+
)
|
428 |
+
attn_weights = attn_weights.type(value.dtype)
|
429 |
+
attn_weights = self.attn_dropout(attn_weights)
|
430 |
+
|
431 |
+
if head_mask is not None:
|
432 |
+
attn_weights = attn_weights * head_mask
|
433 |
+
|
434 |
+
attn_output = torch.matmul(attn_weights, value)
|
435 |
+
|
436 |
+
return attn_output, attn_weights
|
437 |
+
|
438 |
+
def _split_heads(self, tensor, num_heads, attn_head_size):
|
439 |
+
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
|
440 |
+
tensor = tensor.view(new_shape)
|
441 |
+
return tensor
|
442 |
+
|
443 |
+
def _merge_heads(self, tensor, num_heads, attn_head_size):
|
444 |
+
tensor = tensor.contiguous()
|
445 |
+
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
|
446 |
+
return tensor.view(new_shape)
|
447 |
+
|
448 |
+
def forward(
|
449 |
+
self,
|
450 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
451 |
+
rotary_pos_emb_list: Optional[List[torch.Tensor]] = None,
|
452 |
+
registered_causal_mask: Optional[torch.Tensor] = None,
|
453 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
454 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
455 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
456 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
457 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
458 |
+
output_attentions: Optional[bool] = False,
|
459 |
+
use_cache: Optional[bool] = False,
|
460 |
+
):
|
461 |
+
mixed_x_layer = self.c_attn(hidden_states)
|
462 |
+
|
463 |
+
query, key, value = mixed_x_layer.split(self.split_size, dim=2)
|
464 |
+
|
465 |
+
query = self._split_heads(query, self.num_heads, self.head_dim)
|
466 |
+
key = self._split_heads(key, self.num_heads, self.head_dim)
|
467 |
+
value = self._split_heads(value, self.num_heads, self.head_dim)
|
468 |
+
|
469 |
+
if rotary_pos_emb_list is not None:
|
470 |
+
cur_len = query.shape[1]
|
471 |
+
if len(rotary_pos_emb_list) == 1:
|
472 |
+
rotary_pos_emb = rotary_pos_emb_list[0]
|
473 |
+
rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
|
474 |
+
rotary_pos_emb = (rotary_pos_emb,) * 2
|
475 |
+
q_pos_emb, k_pos_emb = rotary_pos_emb
|
476 |
+
# Slice the pos emb for current inference
|
477 |
+
query = apply_rotary_pos_emb(query, q_pos_emb)
|
478 |
+
key = apply_rotary_pos_emb(key, k_pos_emb)
|
479 |
+
else:
|
480 |
+
query_list = []
|
481 |
+
key_list = []
|
482 |
+
for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):
|
483 |
+
rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
|
484 |
+
rotary_pos_emb = (rotary_pos_emb,) * 2
|
485 |
+
q_pos_emb, k_pos_emb = rotary_pos_emb
|
486 |
+
# Slice the pos emb for current inference
|
487 |
+
query_list += [apply_rotary_pos_emb(query[i:i+1, :, :], q_pos_emb)]
|
488 |
+
key_list += [apply_rotary_pos_emb(key[i:i+1, :, :], k_pos_emb)]
|
489 |
+
query = torch.cat(query_list, dim=0)
|
490 |
+
key = torch.cat(key_list, dim=0)
|
491 |
+
|
492 |
+
if self.use_cache_quantization:
|
493 |
+
key = quantize_cache_v(key.permute(0, 2, 1, 3),
|
494 |
+
bits=8,
|
495 |
+
qmin=self.cache_qmin,
|
496 |
+
qmax=self.cache_qmax)
|
497 |
+
value = quantize_cache_v(value.permute(0, 2, 1, 3),
|
498 |
+
bits=8,
|
499 |
+
qmin=self.cache_qmin,
|
500 |
+
qmax=self.cache_qmax)
|
501 |
+
|
502 |
+
|
503 |
+
if layer_past is not None:
|
504 |
+
past_key, past_value = layer_past[0], layer_past[1]
|
505 |
+
if self.use_cache_quantization:
|
506 |
+
# use_cache_quantization:
|
507 |
+
# present=((q_key,key_scale,key_zero_point),
|
508 |
+
# (q_value,value_scale,value_zero_point))
|
509 |
+
key = (torch.cat((past_key[0], key[0]), dim=2),
|
510 |
+
torch.cat((past_key[1], key[1]), dim=2),
|
511 |
+
torch.cat((past_key[2], key[2]), dim=2))
|
512 |
+
value = (torch.cat((past_value[0], value[0]), dim=2),
|
513 |
+
torch.cat((past_value[1], value[1]), dim=2),
|
514 |
+
torch.cat((past_value[2], value[2]), dim=2))
|
515 |
+
else:
|
516 |
+
# not use_cache_quantization:
|
517 |
+
# present=(key,value)
|
518 |
+
key = torch.cat((past_key, key), dim=1)
|
519 |
+
value = torch.cat((past_value, value), dim=1)
|
520 |
+
|
521 |
+
if use_cache:
|
522 |
+
present = (key, value)
|
523 |
+
else:
|
524 |
+
present = None
|
525 |
+
|
526 |
+
if self.use_logn_attn and not self.training:
|
527 |
+
if self.use_cache_quantization:
|
528 |
+
seq_start = key[0].size(2) - query.size(1)
|
529 |
+
seq_end = key[0].size(2)
|
530 |
+
else:
|
531 |
+
seq_start = key.size(1) - query.size(1)
|
532 |
+
seq_end = key.size(1)
|
533 |
+
logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
|
534 |
+
query = query * logn_tensor.expand_as(query) #使用logn_attn时,query乘以logn_tensor,避免长文本时注意力不稳定
|
535 |
+
|
536 |
+
if (
|
537 |
+
self.use_flash_attn
|
538 |
+
and flash_attn_unpadded_func is not None
|
539 |
+
and not self.is_fp32
|
540 |
+
and query.is_cuda
|
541 |
+
):
|
542 |
+
q, k, v = query, key, value
|
543 |
+
context_layer = self.core_attention_flash(q, k, v, attention_mask=attention_mask)
|
544 |
+
|
545 |
+
# b s h d -> b s (h d)
|
546 |
+
context_layer = context_layer.flatten(2,3).contiguous()
|
547 |
+
|
548 |
+
else:
|
549 |
+
query = query.permute(0, 2, 1, 3)
|
550 |
+
if not self.use_cache_quantization:
|
551 |
+
key = key.permute(0, 2, 1, 3)
|
552 |
+
value = value.permute(0, 2, 1, 3)
|
553 |
+
if (
|
554 |
+
registered_causal_mask is None
|
555 |
+
and self.use_flash_attn
|
556 |
+
and flash_attn_unpadded_func is not None
|
557 |
+
and not self.is_fp32
|
558 |
+
and not query.is_cuda
|
559 |
+
):
|
560 |
+
raise Exception(_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED)
|
561 |
+
attn_output, attn_weight = self._attn(
|
562 |
+
query, key, value, registered_causal_mask, attention_mask, head_mask
|
563 |
+
) #如果没有使用flash attention,才会使用registered_causal_mask
|
564 |
+
context_layer = self._merge_heads(
|
565 |
+
attn_output, self.num_heads, self.head_dim
|
566 |
+
)
|
567 |
+
|
568 |
+
attn_output = self.c_proj(context_layer)
|
569 |
+
|
570 |
+
outputs = (attn_output, present)
|
571 |
+
if output_attentions:
|
572 |
+
if (
|
573 |
+
self.use_flash_attn
|
574 |
+
and flash_attn_unpadded_func is not None
|
575 |
+
and not self.is_fp32
|
576 |
+
):
|
577 |
+
raise ValueError("Cannot output attentions while using flash-attn")
|
578 |
+
else:
|
579 |
+
outputs += (attn_weight,)
|
580 |
+
|
581 |
+
return outputs
|
582 |
+
|
583 |
+
|
584 |
+
class QWenMLP(nn.Module):
|
585 |
+
def __init__(self, config):
|
586 |
+
super().__init__()
|
587 |
+
self.w1 = nn.Linear(
|
588 |
+
config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
|
589 |
+
)
|
590 |
+
self.w2 = nn.Linear(
|
591 |
+
config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
|
592 |
+
)
|
593 |
+
ff_dim_in = config.intermediate_size // 2
|
594 |
+
self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
|
595 |
+
|
596 |
+
def forward(self, hidden_states):
|
597 |
+
a1 = self.w1(hidden_states)
|
598 |
+
a2 = self.w2(hidden_states)
|
599 |
+
intermediate_parallel = a1 * F.silu(a2)
|
600 |
+
output = self.c_proj(intermediate_parallel)
|
601 |
+
return output
|
602 |
+
|
603 |
+
class QWenBlock(nn.Module):
|
604 |
+
def __init__(self, config):
|
605 |
+
super().__init__()
|
606 |
+
hidden_size = config.hidden_size
|
607 |
+
self.bf16 = config.bf16
|
608 |
+
|
609 |
+
self.ln_1 = RMSNorm(
|
610 |
+
hidden_size,
|
611 |
+
eps=config.layer_norm_epsilon,
|
612 |
+
)
|
613 |
+
self.attn = QWenAttention(config)
|
614 |
+
self.ln_2 = RMSNorm(
|
615 |
+
hidden_size,
|
616 |
+
eps=config.layer_norm_epsilon,
|
617 |
+
)
|
618 |
+
|
619 |
+
self.mlp = QWenMLP(config)
|
620 |
+
|
621 |
+
def forward(
|
622 |
+
self,
|
623 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
624 |
+
rotary_pos_emb_list: Optional[List[torch.Tensor]] = None,
|
625 |
+
registered_causal_mask: Optional[torch.Tensor] = None,
|
626 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
627 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
628 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
629 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
630 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
631 |
+
use_cache: Optional[bool] = False,
|
632 |
+
output_attentions: Optional[bool] = False,
|
633 |
+
):
|
634 |
+
layernorm_output = self.ln_1(hidden_states)
|
635 |
+
|
636 |
+
attn_outputs = self.attn(
|
637 |
+
layernorm_output,
|
638 |
+
rotary_pos_emb_list,
|
639 |
+
registered_causal_mask=registered_causal_mask,
|
640 |
+
layer_past=layer_past,
|
641 |
+
attention_mask=attention_mask,
|
642 |
+
head_mask=head_mask,
|
643 |
+
use_cache=use_cache,
|
644 |
+
output_attentions=output_attentions,
|
645 |
+
)
|
646 |
+
attn_output = attn_outputs[0]
|
647 |
+
|
648 |
+
outputs = attn_outputs[1:]
|
649 |
+
|
650 |
+
residual = hidden_states
|
651 |
+
layernorm_input = attn_output + residual
|
652 |
+
|
653 |
+
layernorm_output = self.ln_2(layernorm_input)
|
654 |
+
|
655 |
+
residual = layernorm_input
|
656 |
+
mlp_output = self.mlp(layernorm_output)
|
657 |
+
hidden_states = residual + mlp_output
|
658 |
+
|
659 |
+
if use_cache:
|
660 |
+
outputs = (hidden_states,) + outputs
|
661 |
+
else:
|
662 |
+
outputs = (hidden_states,) + outputs[1:]
|
663 |
+
|
664 |
+
return outputs
|
665 |
+
|
666 |
+
|
667 |
+
class QWenPreTrainedModel(PreTrainedModel):
|
668 |
+
config_class = QWenConfig
|
669 |
+
base_model_prefix = "transformer"
|
670 |
+
is_parallelizable = False
|
671 |
+
supports_gradient_checkpointing = True
|
672 |
+
_no_split_modules = ["QWenBlock"]
|
673 |
+
|
674 |
+
def __init__(self, *inputs, **kwargs):
|
675 |
+
super().__init__(*inputs, **kwargs)
|
676 |
+
|
677 |
+
def _init_weights(self, module):
|
678 |
+
"""Initialize the weights."""
|
679 |
+
if isinstance(module, nn.Linear):
|
680 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
681 |
+
if module.bias is not None:
|
682 |
+
module.bias.data.zero_()
|
683 |
+
elif isinstance(module, nn.Embedding):
|
684 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
685 |
+
if module.padding_idx is not None:
|
686 |
+
module.weight.data[module.padding_idx].zero_()
|
687 |
+
elif isinstance(module, RMSNorm):
|
688 |
+
module.weight.data.fill_(1.0)
|
689 |
+
|
690 |
+
for name, p in module.named_parameters():
|
691 |
+
if name == "c_proj.weight":
|
692 |
+
p.data.normal_(
|
693 |
+
mean=0.0,
|
694 |
+
std=(
|
695 |
+
self.config.initializer_range
|
696 |
+
/ math.sqrt(2 * self.config.num_hidden_layers)
|
697 |
+
),
|
698 |
+
)
|
699 |
+
|
700 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
701 |
+
if isinstance(module, QWenModel):
|
702 |
+
module.gradient_checkpointing = value
|
703 |
+
|
704 |
+
|
705 |
+
class QWenModel(QWenPreTrainedModel):
|
706 |
+
_keys_to_ignore_on_load_missing = ["attn.masked_bias"]
|
707 |
+
|
708 |
+
def __init__(self, config):
|
709 |
+
super().__init__(config)
|
710 |
+
self.vocab_size = config.vocab_size
|
711 |
+
self.num_hidden_layers = config.num_hidden_layers
|
712 |
+
self.embed_dim = config.hidden_size
|
713 |
+
self.use_cache_quantization = self.config.use_cache_quantization if hasattr(self.config, 'use_cache_quantization') else False
|
714 |
+
|
715 |
+
self.gradient_checkpointing = False
|
716 |
+
self.use_dynamic_ntk = config.use_dynamic_ntk
|
717 |
+
self.seq_length = config.seq_length
|
718 |
+
|
719 |
+
self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
|
720 |
+
|
721 |
+
self.drop = nn.Dropout(config.emb_dropout_prob)
|
722 |
+
|
723 |
+
if config.rotary_pct == 1.0:
|
724 |
+
self.rotary_ndims = None
|
725 |
+
else:
|
726 |
+
assert config.rotary_pct < 1
|
727 |
+
self.rotary_ndims = int(
|
728 |
+
config.kv_channels * config.rotary_pct
|
729 |
+
)
|
730 |
+
dim = (
|
731 |
+
self.rotary_ndims
|
732 |
+
if self.rotary_ndims is not None
|
733 |
+
else config.kv_channels
|
734 |
+
)
|
735 |
+
self.rotary_emb = YaRNRotaryEmbedding(dim, base=config.rotary_emb_base,original_max_position_embeddings=config.seq_length)
|
736 |
+
#self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
|
737 |
+
import warnings
|
738 |
+
warnings.warn("使用YarnRotaryEmbedding,强制设置config.use_logn_attn = False,config.use_dynamic_ntk = True")
|
739 |
+
config.use_logn_attn = False
|
740 |
+
config.use_dynamic_ntk = True
|
741 |
+
|
742 |
+
self.use_flash_attn = config.use_flash_attn
|
743 |
+
self.is_fp32 = not (config.bf16 or config.fp16)
|
744 |
+
if (
|
745 |
+
self.use_flash_attn
|
746 |
+
and flash_attn_unpadded_func is not None
|
747 |
+
and not self.is_fp32
|
748 |
+
):
|
749 |
+
self.registered_causal_mask = None
|
750 |
+
else:
|
751 |
+
max_positions = config.max_position_embeddings
|
752 |
+
self.register_buffer(
|
753 |
+
"registered_causal_mask",
|
754 |
+
torch.tril(
|
755 |
+
torch.ones((max_positions, max_positions), dtype=torch.bool)
|
756 |
+
).view(1, 1, max_positions, max_positions),
|
757 |
+
persistent=False,
|
758 |
+
)
|
759 |
+
|
760 |
+
self.h = nn.ModuleList(
|
761 |
+
[
|
762 |
+
QWenBlock(
|
763 |
+
config
|
764 |
+
)
|
765 |
+
for i in range(config.num_hidden_layers)
|
766 |
+
]
|
767 |
+
)
|
768 |
+
self.ln_f = RMSNorm(
|
769 |
+
self.embed_dim,
|
770 |
+
eps=config.layer_norm_epsilon,
|
771 |
+
)
|
772 |
+
|
773 |
+
self.post_init()
|
774 |
+
|
775 |
+
def get_input_embeddings(self):
|
776 |
+
return self.wte
|
777 |
+
|
778 |
+
def set_input_embeddings(self, new_embeddings):
|
779 |
+
self.wte = new_embeddings
|
780 |
+
|
781 |
+
def get_ntk_alpha(self, true_seq_len):
|
782 |
+
ntk_alpha = true_seq_len / self.seq_length + 512/self.seq_length
|
783 |
+
ntk_alpha = max(ntk_alpha, 1)
|
784 |
+
# context_value = math.log(true_seq_len / self.seq_length, 2) + 1
|
785 |
+
# ntk_alpha = 2 ** math.ceil(context_value) - 1
|
786 |
+
# ntk_alpha = max(ntk_alpha, 1)
|
787 |
+
|
788 |
+
#假设seq_length=2k,true_seq_len=8k,context_value=3,ntk_alpha=7,相当于扩展到14k长度
|
789 |
+
return ntk_alpha
|
790 |
+
|
791 |
+
def forward(
|
792 |
+
self,
|
793 |
+
input_ids: Optional[torch.LongTensor] = None,
|
794 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
795 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
796 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
797 |
+
position_ids: Optional[torch.LongTensor] = None,
|
798 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
799 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
800 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
801 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
802 |
+
use_cache: Optional[bool] = None,
|
803 |
+
output_attentions: Optional[bool] = None,
|
804 |
+
output_hidden_states: Optional[bool] = None,
|
805 |
+
return_dict: Optional[bool] = None,
|
806 |
+
):
|
807 |
+
output_attentions = (
|
808 |
+
output_attentions
|
809 |
+
if output_attentions is not None
|
810 |
+
else self.config.output_attentions
|
811 |
+
)
|
812 |
+
output_hidden_states = (
|
813 |
+
output_hidden_states
|
814 |
+
if output_hidden_states is not None
|
815 |
+
else self.config.output_hidden_states
|
816 |
+
)
|
817 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
818 |
+
return_dict = (
|
819 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
820 |
+
)
|
821 |
+
|
822 |
+
if input_ids is not None and inputs_embeds is not None:
|
823 |
+
raise ValueError(
|
824 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
825 |
+
)
|
826 |
+
elif input_ids is not None:
|
827 |
+
input_shape = input_ids.size()
|
828 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
829 |
+
batch_size = input_ids.shape[0]
|
830 |
+
elif inputs_embeds is not None:
|
831 |
+
input_shape = inputs_embeds.size()[:-1]
|
832 |
+
batch_size = inputs_embeds.shape[0]
|
833 |
+
else:
|
834 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
835 |
+
|
836 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
837 |
+
|
838 |
+
if token_type_ids is not None:
|
839 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
840 |
+
if position_ids is not None:
|
841 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
842 |
+
|
843 |
+
if past_key_values is None:
|
844 |
+
past_length = 0
|
845 |
+
past_key_values = tuple([None] * len(self.h))
|
846 |
+
else:
|
847 |
+
if self.use_cache_quantization:
|
848 |
+
past_length = past_key_values[0][0][0].size(2)
|
849 |
+
else:
|
850 |
+
past_length = past_key_values[0][0].size(-2)
|
851 |
+
if position_ids is None:
|
852 |
+
position_ids = torch.arange(
|
853 |
+
past_length,
|
854 |
+
input_shape[-1] + past_length,
|
855 |
+
dtype=torch.long,
|
856 |
+
device=device,
|
857 |
+
)
|
858 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
859 |
+
|
860 |
+
if attention_mask is not None:
|
861 |
+
if batch_size <= 0:
|
862 |
+
raise ValueError("batch_size has to be defined and > 0")
|
863 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
864 |
+
attention_mask = attention_mask[:, None, None, :]
|
865 |
+
attention_mask = attention_mask.to(dtype=self.dtype)
|
866 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
867 |
+
|
868 |
+
encoder_attention_mask = None
|
869 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
870 |
+
|
871 |
+
if inputs_embeds is None:
|
872 |
+
inputs_embeds = self.wte(input_ids)
|
873 |
+
hidden_states = inputs_embeds
|
874 |
+
|
875 |
+
kv_seq_len = hidden_states.size()[1]
|
876 |
+
if past_key_values[0] is not None:
|
877 |
+
# past key values[0][0] shape: bs * seq_len * head_num * dim
|
878 |
+
if self.use_cache_quantization:
|
879 |
+
kv_seq_len += past_key_values[0][0][0].shape[2]
|
880 |
+
else:
|
881 |
+
kv_seq_len += past_key_values[0][0].shape[1]
|
882 |
+
|
883 |
+
#if self.training or not self.use_dynamic_ntk:
|
884 |
+
if not self.use_dynamic_ntk:
|
885 |
+
ntk_alpha_list = [1.0]
|
886 |
+
elif kv_seq_len != hidden_states.size()[1]:
|
887 |
+
ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list
|
888 |
+
else:
|
889 |
+
ntk_alpha_list = []
|
890 |
+
if attention_mask is not None and kv_seq_len > self.seq_length:
|
891 |
+
true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)
|
892 |
+
for i in range(hidden_states.size()[0]):
|
893 |
+
#给batch中的每个样本计算ntk_alpha,计算方法是 true_seq_len / self.seq_length。qwen-7b中,self.seq_length=8192,qwen-14b中,self.seq_length=2048
|
894 |
+
true_seq_len = true_seq_lens[i].item()
|
895 |
+
ntk_alpha = self.get_ntk_alpha(true_seq_len)
|
896 |
+
ntk_alpha_list.append(ntk_alpha)
|
897 |
+
else:
|
898 |
+
ntk_alpha = self.get_ntk_alpha(kv_seq_len)
|
899 |
+
ntk_alpha_list.append(ntk_alpha)
|
900 |
+
self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list
|
901 |
+
|
902 |
+
rotary_pos_emb_list = []
|
903 |
+
for ntk_alpha in ntk_alpha_list:
|
904 |
+
rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha) #训练时,ntk_alpha=1.0,rotary_emb根据kv_seq_len生成
|
905 |
+
rotary_pos_emb_list.append(rotary_pos_emb)
|
906 |
+
|
907 |
+
hidden_states = self.drop(hidden_states)
|
908 |
+
output_shape = input_shape + (hidden_states.size(-1),)
|
909 |
+
|
910 |
+
if self.gradient_checkpointing and self.training:
|
911 |
+
if use_cache:
|
912 |
+
logger.warning_once(
|
913 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
914 |
+
)
|
915 |
+
use_cache = False
|
916 |
+
|
917 |
+
presents = () if use_cache else None
|
918 |
+
all_self_attentions = () if output_attentions else None
|
919 |
+
all_hidden_states = () if output_hidden_states else None
|
920 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
921 |
+
|
922 |
+
if output_hidden_states:
|
923 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
924 |
+
|
925 |
+
if self.gradient_checkpointing and self.training:
|
926 |
+
|
927 |
+
def create_custom_forward(module):
|
928 |
+
def custom_forward(*inputs):
|
929 |
+
# None for past_key_value
|
930 |
+
return module(*inputs, use_cache, output_attentions)
|
931 |
+
|
932 |
+
return custom_forward
|
933 |
+
|
934 |
+
outputs = torch.utils.checkpoint.checkpoint(
|
935 |
+
create_custom_forward(block),
|
936 |
+
hidden_states,
|
937 |
+
rotary_pos_emb_list,
|
938 |
+
self.registered_causal_mask,
|
939 |
+
None,
|
940 |
+
attention_mask,
|
941 |
+
head_mask[i],
|
942 |
+
encoder_hidden_states,
|
943 |
+
encoder_attention_mask,
|
944 |
+
)
|
945 |
+
else:
|
946 |
+
outputs = block(
|
947 |
+
hidden_states,
|
948 |
+
layer_past=layer_past,
|
949 |
+
rotary_pos_emb_list=rotary_pos_emb_list,
|
950 |
+
registered_causal_mask=self.registered_causal_mask,
|
951 |
+
attention_mask=attention_mask,
|
952 |
+
head_mask=head_mask[i],
|
953 |
+
encoder_hidden_states=encoder_hidden_states,
|
954 |
+
encoder_attention_mask=encoder_attention_mask,
|
955 |
+
use_cache=use_cache,
|
956 |
+
output_attentions=output_attentions,
|
957 |
+
)
|
958 |
+
|
959 |
+
hidden_states = outputs[0]
|
960 |
+
if use_cache is True:
|
961 |
+
presents = presents + (outputs[1],)
|
962 |
+
|
963 |
+
if output_attentions:
|
964 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
965 |
+
|
966 |
+
hidden_states = self.ln_f(hidden_states)
|
967 |
+
hidden_states = hidden_states.view(output_shape)
|
968 |
+
# Add last hidden state
|
969 |
+
if output_hidden_states:
|
970 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
971 |
+
|
972 |
+
if not return_dict:
|
973 |
+
return tuple(
|
974 |
+
v for v in [hidden_states, presents, all_hidden_states] if v is not None
|
975 |
+
)
|
976 |
+
|
977 |
+
return BaseModelOutputWithPast(
|
978 |
+
last_hidden_state=hidden_states,
|
979 |
+
past_key_values=presents,
|
980 |
+
hidden_states=all_hidden_states,
|
981 |
+
attentions=all_self_attentions,
|
982 |
+
)
|
983 |
+
|
984 |
+
|
985 |
+
class QWenLMHeadModel(QWenPreTrainedModel):
|
986 |
+
_keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
|
987 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
|
988 |
+
|
989 |
+
def __init__(self, config):
|
990 |
+
super().__init__(config)
|
991 |
+
assert (
|
992 |
+
config.bf16 + config.fp16 + config.fp32 <= 1
|
993 |
+
), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
|
994 |
+
logger.warn(
|
995 |
+
"Warning: please make sure that you are using the latest codes and checkpoints, "
|
996 |
+
"especially if you used Qwen-7B before 09.25.2023."
|
997 |
+
"请使用最新模型和代码,尤其如果你在9月25日前已经开始使用Qwen-7B,千万注意不要使用错误代码和模型。"
|
998 |
+
)
|
999 |
+
|
1000 |
+
autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
|
1001 |
+
|
1002 |
+
if autoset_precision:
|
1003 |
+
if SUPPORT_BF16:
|
1004 |
+
logger.warn(
|
1005 |
+
"The model is automatically converting to bf16 for faster inference. "
|
1006 |
+
"If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
|
1007 |
+
)
|
1008 |
+
config.bf16 = True
|
1009 |
+
elif SUPPORT_FP16:
|
1010 |
+
logger.warn(
|
1011 |
+
"The model is automatically converting to fp16 for faster inference. "
|
1012 |
+
"If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
|
1013 |
+
)
|
1014 |
+
config.fp16 = True
|
1015 |
+
else:
|
1016 |
+
config.fp32 = True
|
1017 |
+
|
1018 |
+
if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
|
1019 |
+
logger.warn("Your device does NOT seem to support bf16, you can switch to fp16 or fp32 by by passing fp16/fp32=True in \"AutoModelForCausalLM.from_pretrained\".")
|
1020 |
+
if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
|
1021 |
+
logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
|
1022 |
+
if config.fp32:
|
1023 |
+
if SUPPORT_BF16:
|
1024 |
+
logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
|
1025 |
+
elif SUPPORT_FP16:
|
1026 |
+
logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
|
1027 |
+
|
1028 |
+
if config.use_flash_attn == "auto":
|
1029 |
+
if config.bf16 or config.fp16:
|
1030 |
+
logger.warn("Try importing flash-attention for faster inference...")
|
1031 |
+
config.use_flash_attn = True
|
1032 |
+
else:
|
1033 |
+
config.use_flash_attn = False
|
1034 |
+
if config.use_flash_attn and config.fp32:
|
1035 |
+
logger.warn("Flash attention will be disabled because it does NOT support fp32.")
|
1036 |
+
|
1037 |
+
if config.use_flash_attn:
|
1038 |
+
_import_flash_attn()
|
1039 |
+
|
1040 |
+
|
1041 |
+
if hasattr(config, 'use_cache_quantization') and config.use_cache_quantization:
|
1042 |
+
config.use_flash_attn = False
|
1043 |
+
if hasattr(config, 'use_cache_kernel') and config.use_cache_kernel:
|
1044 |
+
try:
|
1045 |
+
from kernels.cpp_kernels import cache_autogptq_cuda_256
|
1046 |
+
except ImportError:
|
1047 |
+
cache_autogptq_cuda_256 = None
|
1048 |
+
|
1049 |
+
self.transformer = QWenModel(config)
|
1050 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1051 |
+
|
1052 |
+
if config.bf16:
|
1053 |
+
self.transformer.bfloat16()
|
1054 |
+
self.lm_head.bfloat16()
|
1055 |
+
if config.fp16:
|
1056 |
+
self.transformer.half()
|
1057 |
+
self.lm_head.half()
|
1058 |
+
self.post_init()
|
1059 |
+
|
1060 |
+
|
1061 |
+
def get_output_embeddings(self):
|
1062 |
+
return self.lm_head
|
1063 |
+
|
1064 |
+
def set_output_embeddings(self, new_embeddings):
|
1065 |
+
self.lm_head = new_embeddings
|
1066 |
+
|
1067 |
+
def prepare_inputs_for_generation(
|
1068 |
+
self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
|
1069 |
+
):
|
1070 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
1071 |
+
if past_key_values:
|
1072 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
1073 |
+
if token_type_ids is not None:
|
1074 |
+
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
1075 |
+
|
1076 |
+
attention_mask = kwargs.get("attention_mask", None)
|
1077 |
+
position_ids = kwargs.get("position_ids", None)
|
1078 |
+
|
1079 |
+
if attention_mask is not None and position_ids is None:
|
1080 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1081 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1082 |
+
if past_key_values:
|
1083 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
1084 |
+
else:
|
1085 |
+
position_ids = None
|
1086 |
+
|
1087 |
+
if inputs_embeds is not None and past_key_values is None:
|
1088 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1089 |
+
else:
|
1090 |
+
model_inputs = {"input_ids": input_ids}
|
1091 |
+
|
1092 |
+
model_inputs.update(
|
1093 |
+
{
|
1094 |
+
"past_key_values": past_key_values,
|
1095 |
+
"use_cache": kwargs.get("use_cache"),
|
1096 |
+
"position_ids": position_ids,
|
1097 |
+
"attention_mask": attention_mask,
|
1098 |
+
"token_type_ids": token_type_ids,
|
1099 |
+
}
|
1100 |
+
)
|
1101 |
+
return model_inputs
|
1102 |
+
|
1103 |
+
def forward(
|
1104 |
+
self,
|
1105 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1106 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1107 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1108 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1109 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1110 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1111 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1112 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1113 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
1114 |
+
labels: Optional[torch.LongTensor] = None,
|
1115 |
+
use_cache: Optional[bool] = None,
|
1116 |
+
output_attentions: Optional[bool] = None,
|
1117 |
+
output_hidden_states: Optional[bool] = None,
|
1118 |
+
return_dict: Optional[bool] = None,
|
1119 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1120 |
+
|
1121 |
+
return_dict = (
|
1122 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1123 |
+
)
|
1124 |
+
|
1125 |
+
transformer_outputs = self.transformer(
|
1126 |
+
input_ids,
|
1127 |
+
past_key_values=past_key_values,
|
1128 |
+
attention_mask=attention_mask,
|
1129 |
+
token_type_ids=token_type_ids,
|
1130 |
+
position_ids=position_ids,
|
1131 |
+
head_mask=head_mask,
|
1132 |
+
inputs_embeds=inputs_embeds,
|
1133 |
+
encoder_hidden_states=encoder_hidden_states,
|
1134 |
+
encoder_attention_mask=encoder_attention_mask,
|
1135 |
+
use_cache=use_cache,
|
1136 |
+
output_attentions=output_attentions,
|
1137 |
+
output_hidden_states=output_hidden_states,
|
1138 |
+
return_dict=return_dict,
|
1139 |
+
)
|
1140 |
+
hidden_states = transformer_outputs[0]
|
1141 |
+
|
1142 |
+
lm_logits = self.lm_head(hidden_states)
|
1143 |
+
|
1144 |
+
loss = None
|
1145 |
+
if labels is not None:
|
1146 |
+
labels = labels.to(lm_logits.device)
|
1147 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1148 |
+
shift_labels = labels[..., 1:].contiguous()
|
1149 |
+
loss_fct = CrossEntropyLoss()
|
1150 |
+
loss = loss_fct(
|
1151 |
+
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
|
1152 |
+
)
|
1153 |
+
|
1154 |
+
|
1155 |
+
if not return_dict:
|
1156 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1157 |
+
return ((loss,) + output) if loss is not None else output
|
1158 |
+
|
1159 |
+
if self.training:
|
1160 |
+
lm_logits=None
|
1161 |
+
return CausalLMOutputWithPast(
|
1162 |
+
loss=loss,
|
1163 |
+
logits=lm_logits,
|
1164 |
+
past_key_values=transformer_outputs.past_key_values,
|
1165 |
+
hidden_states=transformer_outputs.hidden_states,
|
1166 |
+
attentions=transformer_outputs.attentions,
|
1167 |
+
)
|
1168 |
+
|
1169 |
+
@staticmethod
|
1170 |
+
def _reorder_cache(
|
1171 |
+
past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
|
1172 |
+
) -> Tuple[Tuple[torch.Tensor]]:
|
1173 |
+
|
1174 |
+
return tuple(
|
1175 |
+
tuple(
|
1176 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
1177 |
+
for past_state in layer_past
|
1178 |
+
)
|
1179 |
+
for layer_past in past_key_values
|
1180 |
+
)
|
1181 |
+
|
1182 |
+
def chat(
|
1183 |
+
self,
|
1184 |
+
tokenizer: PreTrainedTokenizer,
|
1185 |
+
query: str,
|
1186 |
+
history: Optional[HistoryType],
|
1187 |
+
system: str = "You are a helpful assistant.",
|
1188 |
+
append_history: bool = True,
|
1189 |
+
stream: Optional[bool] = _SENTINEL,
|
1190 |
+
stop_words_ids: Optional[List[List[int]]] = None,
|
1191 |
+
generation_config: Optional[GenerationConfig] = None,
|
1192 |
+
**kwargs,
|
1193 |
+
) -> Tuple[str, HistoryType]:
|
1194 |
+
generation_config = generation_config if generation_config is not None else self.generation_config
|
1195 |
+
|
1196 |
+
assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
|
1197 |
+
assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
|
1198 |
+
if history is None:
|
1199 |
+
history = []
|
1200 |
+
if stop_words_ids is None:
|
1201 |
+
stop_words_ids = []
|
1202 |
+
|
1203 |
+
max_window_size = kwargs.get('max_window_size', None)
|
1204 |
+
if max_window_size is None:
|
1205 |
+
max_window_size = generation_config.max_window_size
|
1206 |
+
raw_text, context_tokens = make_context(
|
1207 |
+
tokenizer,
|
1208 |
+
query,
|
1209 |
+
history=history,
|
1210 |
+
system=system,
|
1211 |
+
max_window_size=max_window_size,
|
1212 |
+
chat_format=generation_config.chat_format,
|
1213 |
+
)
|
1214 |
+
|
1215 |
+
stop_words_ids.extend(get_stop_words_ids(
|
1216 |
+
generation_config.chat_format, tokenizer
|
1217 |
+
))
|
1218 |
+
input_ids = torch.tensor([context_tokens]).to(self.device)
|
1219 |
+
outputs = self.generate(
|
1220 |
+
input_ids,
|
1221 |
+
stop_words_ids=stop_words_ids,
|
1222 |
+
return_dict_in_generate=False,
|
1223 |
+
generation_config=generation_config,
|
1224 |
+
**kwargs,
|
1225 |
+
)
|
1226 |
+
|
1227 |
+
response = decode_tokens(
|
1228 |
+
outputs[0],
|
1229 |
+
tokenizer,
|
1230 |
+
raw_text_len=len(raw_text),
|
1231 |
+
context_length=len(context_tokens),
|
1232 |
+
chat_format=generation_config.chat_format,
|
1233 |
+
verbose=False,
|
1234 |
+
errors='replace'
|
1235 |
+
)
|
1236 |
+
|
1237 |
+
if append_history:
|
1238 |
+
history.append((query, response))
|
1239 |
+
|
1240 |
+
return response, history
|
1241 |
+
|
1242 |
+
def chat_stream(
|
1243 |
+
self,
|
1244 |
+
tokenizer: PreTrainedTokenizer,
|
1245 |
+
query: str,
|
1246 |
+
history: Optional[HistoryType],
|
1247 |
+
system: str = "You are a helpful assistant.",
|
1248 |
+
stop_words_ids: Optional[List[List[int]]] = None,
|
1249 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
1250 |
+
generation_config: Optional[GenerationConfig] = None,
|
1251 |
+
**kwargs,
|
1252 |
+
) -> Generator[str, Any, None]:
|
1253 |
+
generation_config = generation_config if generation_config is not None else self.generation_config
|
1254 |
+
assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
|
1255 |
+
if history is None:
|
1256 |
+
history = []
|
1257 |
+
if stop_words_ids is None:
|
1258 |
+
stop_words_ids = []
|
1259 |
+
|
1260 |
+
max_window_size = kwargs.get('max_window_size', None)
|
1261 |
+
if max_window_size is None:
|
1262 |
+
max_window_size = generation_config.max_window_size
|
1263 |
+
raw_text, context_tokens = make_context(
|
1264 |
+
tokenizer,
|
1265 |
+
query,
|
1266 |
+
history=history,
|
1267 |
+
system=system,
|
1268 |
+
max_window_size=max_window_size,
|
1269 |
+
chat_format=generation_config.chat_format,
|
1270 |
+
)
|
1271 |
+
|
1272 |
+
stop_words_ids.extend(get_stop_words_ids(
|
1273 |
+
generation_config.chat_format, tokenizer
|
1274 |
+
))
|
1275 |
+
if stop_words_ids is not None:
|
1276 |
+
stop_words_logits_processor = StopWordsLogitsProcessor(
|
1277 |
+
stop_words_ids=stop_words_ids,
|
1278 |
+
eos_token_id=generation_config.eos_token_id,
|
1279 |
+
)
|
1280 |
+
if logits_processor is None:
|
1281 |
+
logits_processor = LogitsProcessorList([stop_words_logits_processor])
|
1282 |
+
else:
|
1283 |
+
logits_processor.append(stop_words_logits_processor)
|
1284 |
+
input_ids = torch.tensor([context_tokens]).to(self.device)
|
1285 |
+
|
1286 |
+
from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
|
1287 |
+
self.__class__.generate_stream = NewGenerationMixin.generate
|
1288 |
+
self.__class__.sample_stream = NewGenerationMixin.sample_stream
|
1289 |
+
stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
|
1290 |
+
|
1291 |
+
def stream_generator():
|
1292 |
+
outputs = []
|
1293 |
+
for token in self.generate_stream(
|
1294 |
+
input_ids,
|
1295 |
+
return_dict_in_generate=False,
|
1296 |
+
generation_config=stream_config,
|
1297 |
+
logits_processor=logits_processor,
|
1298 |
+
seed=-1,
|
1299 |
+
**kwargs):
|
1300 |
+
outputs.append(token.item())
|
1301 |
+
yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')
|
1302 |
+
|
1303 |
+
return stream_generator()
|
1304 |
+
|
1305 |
+
def generate(
|
1306 |
+
self,
|
1307 |
+
inputs: Optional[torch.Tensor] = None,
|
1308 |
+
generation_config: Optional[GenerationConfig] = None,
|
1309 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
1310 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
1311 |
+
prefix_allowed_tokens_fn: Optional[
|
1312 |
+
Callable[[int, torch.Tensor], List[int]]
|
1313 |
+
] = None,
|
1314 |
+
synced_gpus: Optional[bool] = None,
|
1315 |
+
assistant_model: Optional["PreTrainedModel"] = None,
|
1316 |
+
streamer: Optional["BaseStreamer"] = None,
|
1317 |
+
**kwargs,
|
1318 |
+
) -> Union[GenerateOutput, torch.LongTensor]:
|
1319 |
+
generation_config = generation_config if generation_config is not None else self.generation_config
|
1320 |
+
|
1321 |
+
# Process stop_words_ids.
|
1322 |
+
stop_words_ids = kwargs.pop("stop_words_ids", None)
|
1323 |
+
if stop_words_ids is None and generation_config is not None:
|
1324 |
+
stop_words_ids = getattr(generation_config, "stop_words_ids", None)
|
1325 |
+
if stop_words_ids is None:
|
1326 |
+
stop_words_ids = getattr(generation_config, "stop_words_ids", None)
|
1327 |
+
|
1328 |
+
if stop_words_ids is not None:
|
1329 |
+
stop_words_logits_processor = StopWordsLogitsProcessor(
|
1330 |
+
stop_words_ids=stop_words_ids,
|
1331 |
+
eos_token_id=generation_config.eos_token_id,
|
1332 |
+
)
|
1333 |
+
if logits_processor is None:
|
1334 |
+
logits_processor = LogitsProcessorList([stop_words_logits_processor])
|
1335 |
+
else:
|
1336 |
+
logits_processor.append(stop_words_logits_processor)
|
1337 |
+
|
1338 |
+
return super().generate(
|
1339 |
+
inputs,
|
1340 |
+
generation_config=generation_config,
|
1341 |
+
logits_processor=logits_processor,
|
1342 |
+
stopping_criteria=stopping_criteria,
|
1343 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
1344 |
+
synced_gpus=synced_gpus,
|
1345 |
+
assistant_model=assistant_model,
|
1346 |
+
streamer=streamer,
|
1347 |
+
**kwargs,
|
1348 |
+
)
|
1349 |
+
|
1350 |
+
|
1351 |
+
class RotaryEmbedding(torch.nn.Module):
|
1352 |
+
def __init__(self, dim, base=10000):
|
1353 |
+
super().__init__()
|
1354 |
+
self.dim = dim
|
1355 |
+
self.base = base
|
1356 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
1357 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
1358 |
+
if importlib.util.find_spec("einops") is None:
|
1359 |
+
raise RuntimeError("einops is required for Rotary Embedding")
|
1360 |
+
|
1361 |
+
self._rotary_pos_emb_cache = None
|
1362 |
+
self._seq_len_cached = 0
|
1363 |
+
self._ntk_alpha_cached = 1.0
|
1364 |
+
self._ntk_alpha_cached_list = [1.0]
|
1365 |
+
|
1366 |
+
def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
|
1367 |
+
seqlen = max_seq_len + offset
|
1368 |
+
if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
|
1369 |
+
#计算新的base。ntk_alpha=1时,base不变;ntk_alpha>1时,base变大
|
1370 |
+
base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
|
1371 |
+
#波长=2*pi*base^(2d/D),即频率的倒数。此处算出了每个维度对应的频率。由于每两个维度对应一个频率,所以频率的个数为dim/2
|
1372 |
+
self.inv_freq = 1.0 / (
|
1373 |
+
base
|
1374 |
+
** (
|
1375 |
+
torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
|
1376 |
+
/ self.dim
|
1377 |
+
)
|
1378 |
+
)
|
1379 |
+
self._seq_len_cached = max(seqlen+512, 16)
|
1380 |
+
self._ntk_alpha_cached = ntk_alpha
|
1381 |
+
seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
|
1382 |
+
freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq) #做外积,获得seq_len*(dim/2)的矩阵
|
1383 |
+
|
1384 |
+
emb = torch.cat((freqs, freqs), dim=-1) #获得(seq_len*2)*dim的矩阵
|
1385 |
+
from einops import rearrange
|
1386 |
+
|
1387 |
+
emb = rearrange(emb, "n d -> 1 n 1 d") #获得1*(seq_len*2)*1*dim的矩阵
|
1388 |
+
|
1389 |
+
cos, sin = emb.cos(), emb.sin()
|
1390 |
+
self._rotary_pos_emb_cache = [cos, sin]
|
1391 |
+
|
1392 |
+
def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
|
1393 |
+
self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
|
1394 |
+
cos, sin = self._rotary_pos_emb_cache
|
1395 |
+
return [cos[:, offset : offset + max_seq_len], sin[:, offset : offset + max_seq_len]]
|
1396 |
+
|
1397 |
+
|
1398 |
+
class YaRNRotaryEmbedding(RotaryEmbedding):
|
1399 |
+
def __init__(self, dim, base=10000,interleaved=False,extrapolation_factor=1,
|
1400 |
+
attn_factor=1, beta_fast=32, beta_slow=1,original_max_position_embeddings=2048):
|
1401 |
+
"""
|
1402 |
+
interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
|
1403 |
+
of 1st half and 2nd half (GPT-NeoX style).
|
1404 |
+
pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32,
|
1405 |
+
otherwise they might be in lower precision.
|
1406 |
+
This option was added because previously (before 2023-07-02), when we construct
|
1407 |
+
the position indices, we use the dtype of self.inv_freq. In most cases this would
|
1408 |
+
be fp32, but if the model is trained in pure bf16 (not mixed precision), then
|
1409 |
+
self.inv_freq would be bf16, and the position indices are also in bf16.
|
1410 |
+
Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
|
1411 |
+
embeddings for some positions will coincide.
|
1412 |
+
To maintain compatibility with models previously trained in pure bf16,
|
1413 |
+
we add this option.
|
1414 |
+
scaling_factor: RotaryEmbedding extended with YaRN scaling.
|
1415 |
+
"""
|
1416 |
+
super().__init__(dim, base)
|
1417 |
+
self.interleaved = interleaved
|
1418 |
+
self.extrapolation_factor = extrapolation_factor
|
1419 |
+
self.attn_factor = attn_factor
|
1420 |
+
self.beta_fast = beta_fast
|
1421 |
+
self.beta_slow = beta_slow
|
1422 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
1423 |
+
|
1424 |
+
def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
|
1425 |
+
seqlen = max_seq_len + offset
|
1426 |
+
if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
|
1427 |
+
#波长=2*pi*base^(2d/D),即频率的倒数。此处算出了每个维度对应的频率。由于每两个维度对应一个频率,所以频率的个数为dim/2
|
1428 |
+
self._compute_inv_freq(ntk_alpha, device=self.inv_freq.device)
|
1429 |
+
self.mscale = float(_yarn_get_mscale(ntk_alpha) * self.attn_factor)
|
1430 |
+
|
1431 |
+
self._seq_len_cached = max(seqlen+512, 16)
|
1432 |
+
self._ntk_alpha_cached = ntk_alpha
|
1433 |
+
seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
|
1434 |
+
freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq) #seq和逆频率做外积,获得seq_len*(dim/2)的矩阵
|
1435 |
+
|
1436 |
+
emb = torch.cat((freqs, freqs), dim=-1) #获得(seq_len*2)*dim的矩阵
|
1437 |
+
from einops import rearrange
|
1438 |
+
|
1439 |
+
emb = rearrange(emb, "n d -> 1 n 1 d") #获得1*(seq_len*2)*1*dim的矩阵
|
1440 |
+
|
1441 |
+
cos, sin = emb.cos() * self.mscale, emb.sin() * self.mscale
|
1442 |
+
self._rotary_pos_emb_cache = [cos, sin]
|
1443 |
+
|
1444 |
+
def _compute_inv_freq(self, scaling_factor, device=None):
|
1445 |
+
pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
1446 |
+
inv_freq_extrapolation = 1.0 / pos_freqs
|
1447 |
+
inv_freq_interpolation = 1.0 / (scaling_factor * pos_freqs)
|
1448 |
+
|
1449 |
+
low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
|
1450 |
+
inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
|
1451 |
+
inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
|
1452 |
+
inv_freq=inv_freq.float()
|
1453 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
1454 |
+
|
1455 |
+
# Inverse dim formula to find dim based on number of rotations
|
1456 |
+
def _yarn_find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
|
1457 |
+
return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
|
1458 |
+
|
1459 |
+
# Find dim range bounds based on rotations
|
1460 |
+
def _yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
|
1461 |
+
low = math.floor(_yarn_find_correction_dim(
|
1462 |
+
low_rot, dim, base, max_position_embeddings))
|
1463 |
+
high = math.ceil(_yarn_find_correction_dim(
|
1464 |
+
high_rot, dim, base, max_position_embeddings))
|
1465 |
+
return max(low, 0), min(high, dim-1) # Clamp values just in case
|
1466 |
+
|
1467 |
+
def _yarn_linear_ramp_mask(min, max, dim):
|
1468 |
+
if min == max:
|
1469 |
+
max += 0.001 # Prevent singularity
|
1470 |
+
|
1471 |
+
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
|
1472 |
+
ramp_func = torch.clamp(linear_func, 0, 1)
|
1473 |
+
return ramp_func
|
1474 |
+
|
1475 |
+
def _yarn_get_mscale(scale=1):
|
1476 |
+
if scale <= 1:
|
1477 |
+
return 1.0
|
1478 |
+
return 0.1 * math.log(scale) + 1.0
|
1479 |
+
|
1480 |
+
|
1481 |
+
|
1482 |
+
def _rotate_half(x):
|
1483 |
+
from einops import rearrange
|
1484 |
+
|
1485 |
+
x = rearrange(x, "... (j d) -> ... j d", j=2)
|
1486 |
+
x1, x2 = x.unbind(dim=-2)
|
1487 |
+
return torch.cat((-x2, x1), dim=-1)
|
1488 |
+
|
1489 |
+
|
1490 |
+
def apply_rotary_pos_emb(t, freqs):
|
1491 |
+
cos, sin = freqs
|
1492 |
+
if apply_rotary_emb_func is not None and t.is_cuda:
|
1493 |
+
t_ = t.float()
|
1494 |
+
cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2]
|
1495 |
+
sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2]
|
1496 |
+
output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
|
1497 |
+
return output
|
1498 |
+
else:
|
1499 |
+
rot_dim = freqs[0].shape[-1]
|
1500 |
+
cos, sin = freqs
|
1501 |
+
t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
|
1502 |
+
t_ = t_.float()
|
1503 |
+
t_pass_ = t_pass_.float()
|
1504 |
+
t_ = (t_ * cos) + (_rotate_half(t_) * sin)
|
1505 |
+
return torch.cat((t_, t_pass_), dim=-1).type_as(t)
|
1506 |
+
|
1507 |
+
|
1508 |
+
class RMSNorm(torch.nn.Module):
|
1509 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
1510 |
+
super().__init__()
|
1511 |
+
self.eps = eps
|
1512 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
1513 |
+
|
1514 |
+
def _norm(self, x):
|
1515 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
1516 |
+
|
1517 |
+
def forward(self, x):
|
1518 |
+
if rms_norm is not None and x.is_cuda:
|
1519 |
+
return rms_norm(x, self.weight, self.eps)
|
1520 |
+
else:
|
1521 |
+
output = self._norm(x.float()).type_as(x)
|
1522 |
+
return output * self.weight
|
qwen_generation_utils.py
ADDED
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Alibaba Cloud.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
"""Generation support."""
|
7 |
+
|
8 |
+
from typing import Tuple, List, Union, Iterable
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
import torch
|
12 |
+
import torch.nn.functional as F
|
13 |
+
from transformers import PreTrainedTokenizer
|
14 |
+
from transformers import logging
|
15 |
+
from transformers.generation import LogitsProcessor
|
16 |
+
|
17 |
+
logger = logging.get_logger(__name__)
|
18 |
+
|
19 |
+
# Types.
|
20 |
+
HistoryType = List[Tuple[str, str]]
|
21 |
+
TokensType = List[int]
|
22 |
+
BatchTokensType = List[List[int]]
|
23 |
+
|
24 |
+
|
25 |
+
def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
|
26 |
+
for tokens in batch:
|
27 |
+
context_length = len(tokens)
|
28 |
+
if context_length < seq_length:
|
29 |
+
tokens.extend([pad_id] * (seq_length - context_length))
|
30 |
+
return batch
|
31 |
+
|
32 |
+
|
33 |
+
def get_ltor_masks_and_position_ids(
|
34 |
+
data,
|
35 |
+
eod_token,
|
36 |
+
reset_position_ids,
|
37 |
+
reset_attention_mask,
|
38 |
+
eod_mask_loss,
|
39 |
+
):
|
40 |
+
"""Build masks and position id for left to right model."""
|
41 |
+
|
42 |
+
# Extract batch size and sequence length.
|
43 |
+
micro_batch_size, seq_length = data.size()
|
44 |
+
|
45 |
+
# Attention mask (lower triangular).
|
46 |
+
if reset_attention_mask:
|
47 |
+
att_mask_batch = micro_batch_size
|
48 |
+
else:
|
49 |
+
att_mask_batch = 1
|
50 |
+
attention_mask = torch.tril(
|
51 |
+
torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
|
52 |
+
).view(att_mask_batch, 1, seq_length, seq_length)
|
53 |
+
|
54 |
+
# Loss mask.
|
55 |
+
loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
|
56 |
+
if eod_mask_loss:
|
57 |
+
loss_mask[data == eod_token] = 0.0
|
58 |
+
|
59 |
+
# Position ids.
|
60 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
|
61 |
+
position_ids = position_ids.unsqueeze(0).expand_as(data)
|
62 |
+
# We need to clone as the ids will be modifed based on batch index.
|
63 |
+
if reset_position_ids:
|
64 |
+
position_ids = position_ids.clone()
|
65 |
+
|
66 |
+
if reset_position_ids or reset_attention_mask:
|
67 |
+
# Loop through the batches:
|
68 |
+
for b in range(micro_batch_size):
|
69 |
+
|
70 |
+
# Find indecies where EOD token is.
|
71 |
+
eod_index = position_ids[b, data[b] == eod_token]
|
72 |
+
# Detach indecies from positions if going to modify positions.
|
73 |
+
if reset_position_ids:
|
74 |
+
eod_index = eod_index.clone()
|
75 |
+
|
76 |
+
# Loop through EOD indecies:
|
77 |
+
prev_index = 0
|
78 |
+
for j in range(eod_index.size()[0]):
|
79 |
+
i = eod_index[j]
|
80 |
+
# Mask attention loss.
|
81 |
+
if reset_attention_mask:
|
82 |
+
attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
|
83 |
+
# Reset positions.
|
84 |
+
if reset_position_ids:
|
85 |
+
position_ids[b, (i + 1) :] -= i + 1 - prev_index
|
86 |
+
prev_index = i + 1
|
87 |
+
|
88 |
+
# Convert attention mask to binary:
|
89 |
+
attention_mask = attention_mask < 0.5
|
90 |
+
|
91 |
+
return attention_mask, loss_mask, position_ids
|
92 |
+
|
93 |
+
|
94 |
+
def get_batch(context_tokens: torch.LongTensor, eod_id: int):
|
95 |
+
"""Generate batch from context tokens."""
|
96 |
+
# Move to GPU.
|
97 |
+
tokens = context_tokens.contiguous().to(context_tokens.device)
|
98 |
+
# Get the attention mask and postition ids.
|
99 |
+
attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
|
100 |
+
tokens,
|
101 |
+
eod_id,
|
102 |
+
reset_position_ids=False,
|
103 |
+
reset_attention_mask=False,
|
104 |
+
eod_mask_loss=False,
|
105 |
+
)
|
106 |
+
return tokens, attention_mask, position_ids
|
107 |
+
|
108 |
+
|
109 |
+
def get_stop_words_ids(chat_format, tokenizer):
|
110 |
+
if chat_format == "raw":
|
111 |
+
stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
|
112 |
+
elif chat_format == "chatml":
|
113 |
+
stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
|
114 |
+
else:
|
115 |
+
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
116 |
+
return stop_words_ids
|
117 |
+
|
118 |
+
|
119 |
+
def make_context(
|
120 |
+
tokenizer: PreTrainedTokenizer,
|
121 |
+
query: str,
|
122 |
+
history: List[Tuple[str, str]] = None,
|
123 |
+
system: str = "",
|
124 |
+
max_window_size: int = 6144,
|
125 |
+
chat_format: str = "chatml",
|
126 |
+
):
|
127 |
+
if history is None:
|
128 |
+
history = []
|
129 |
+
|
130 |
+
if chat_format == "chatml":
|
131 |
+
im_start, im_end = "<|im_start|>", "<|im_end|>"
|
132 |
+
im_start_tokens = [tokenizer.im_start_id]
|
133 |
+
im_end_tokens = [tokenizer.im_end_id]
|
134 |
+
nl_tokens = tokenizer.encode("\n")
|
135 |
+
|
136 |
+
def _tokenize_str(role, content):
|
137 |
+
return f"{role}\n{content}", tokenizer.encode(
|
138 |
+
role, allowed_special=set()
|
139 |
+
) + nl_tokens + tokenizer.encode(content, allowed_special=set())
|
140 |
+
|
141 |
+
system_text, system_tokens_part = _tokenize_str("system", system)
|
142 |
+
system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
|
143 |
+
|
144 |
+
raw_text = ""
|
145 |
+
context_tokens = []
|
146 |
+
|
147 |
+
for turn_query, turn_response in reversed(history):
|
148 |
+
query_text, query_tokens_part = _tokenize_str("user", turn_query)
|
149 |
+
query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
|
150 |
+
response_text, response_tokens_part = _tokenize_str(
|
151 |
+
"assistant", turn_response
|
152 |
+
)
|
153 |
+
response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
|
154 |
+
|
155 |
+
next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
|
156 |
+
prev_chat = (
|
157 |
+
f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
|
158 |
+
)
|
159 |
+
|
160 |
+
current_context_size = (
|
161 |
+
len(system_tokens) + len(next_context_tokens) + len(context_tokens)
|
162 |
+
)
|
163 |
+
if current_context_size < max_window_size:
|
164 |
+
context_tokens = next_context_tokens + context_tokens
|
165 |
+
raw_text = prev_chat + raw_text
|
166 |
+
else:
|
167 |
+
break
|
168 |
+
|
169 |
+
context_tokens = system_tokens + context_tokens
|
170 |
+
raw_text = f"{im_start}{system_text}{im_end}" + raw_text
|
171 |
+
context_tokens += (
|
172 |
+
nl_tokens
|
173 |
+
+ im_start_tokens
|
174 |
+
+ _tokenize_str("user", query)[1]
|
175 |
+
+ im_end_tokens
|
176 |
+
+ nl_tokens
|
177 |
+
+ im_start_tokens
|
178 |
+
+ tokenizer.encode("assistant")
|
179 |
+
+ nl_tokens
|
180 |
+
)
|
181 |
+
raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
|
182 |
+
|
183 |
+
elif chat_format == "raw":
|
184 |
+
raw_text = query
|
185 |
+
context_tokens = tokenizer.encode(raw_text)
|
186 |
+
else:
|
187 |
+
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
188 |
+
|
189 |
+
return raw_text, context_tokens
|
190 |
+
|
191 |
+
|
192 |
+
def _decode_default(
|
193 |
+
tokens: List[int],
|
194 |
+
*,
|
195 |
+
stop_words: List[str],
|
196 |
+
eod_words: List[str],
|
197 |
+
tokenizer: PreTrainedTokenizer,
|
198 |
+
raw_text_len: int,
|
199 |
+
verbose: bool = False,
|
200 |
+
return_end_reason: bool = False,
|
201 |
+
errors: str='replace',
|
202 |
+
):
|
203 |
+
trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
|
204 |
+
if verbose:
|
205 |
+
print("\nRaw Generate: ", trim_decode_tokens)
|
206 |
+
|
207 |
+
end_reason = f"Gen length {len(tokens)}"
|
208 |
+
for stop_word in stop_words:
|
209 |
+
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
210 |
+
for eod_word in eod_words:
|
211 |
+
if eod_word in trim_decode_tokens:
|
212 |
+
end_reason = f"Gen {eod_word!r}"
|
213 |
+
trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
|
214 |
+
trim_decode_tokens = trim_decode_tokens.strip()
|
215 |
+
if verbose:
|
216 |
+
print("\nEnd Reason:", end_reason)
|
217 |
+
print("\nGenerate: ", trim_decode_tokens)
|
218 |
+
|
219 |
+
if return_end_reason:
|
220 |
+
return trim_decode_tokens, end_reason
|
221 |
+
else:
|
222 |
+
return trim_decode_tokens
|
223 |
+
|
224 |
+
|
225 |
+
def _decode_chatml(
|
226 |
+
tokens: List[int],
|
227 |
+
*,
|
228 |
+
stop_words: List[str],
|
229 |
+
eod_token_ids: List[int],
|
230 |
+
tokenizer: PreTrainedTokenizer,
|
231 |
+
raw_text_len: int,
|
232 |
+
context_length: int,
|
233 |
+
verbose: bool = False,
|
234 |
+
return_end_reason: bool = False,
|
235 |
+
errors: str='replace'
|
236 |
+
):
|
237 |
+
end_reason = f"Gen length {len(tokens)}"
|
238 |
+
eod_token_idx = context_length
|
239 |
+
for eod_token_idx in range(context_length, len(tokens)):
|
240 |
+
if tokens[eod_token_idx] in eod_token_ids:
|
241 |
+
end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
|
242 |
+
break
|
243 |
+
|
244 |
+
trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
|
245 |
+
if verbose:
|
246 |
+
print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
|
247 |
+
print("\nRaw Generate:", trim_decode_tokens)
|
248 |
+
print("\nEnd Reason:", end_reason)
|
249 |
+
for stop_word in stop_words:
|
250 |
+
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
251 |
+
trim_decode_tokens = trim_decode_tokens.strip()
|
252 |
+
if verbose:
|
253 |
+
print("\nGenerate:", trim_decode_tokens)
|
254 |
+
|
255 |
+
if return_end_reason:
|
256 |
+
return trim_decode_tokens, end_reason
|
257 |
+
else:
|
258 |
+
return trim_decode_tokens
|
259 |
+
|
260 |
+
|
261 |
+
def decode_tokens(
|
262 |
+
tokens: Union[torch.LongTensor, TokensType],
|
263 |
+
tokenizer: PreTrainedTokenizer,
|
264 |
+
raw_text_len: int,
|
265 |
+
context_length: int,
|
266 |
+
chat_format: str,
|
267 |
+
verbose: bool = False,
|
268 |
+
return_end_reason: bool = False,
|
269 |
+
errors: str="replace",
|
270 |
+
) -> str:
|
271 |
+
if torch.is_tensor(tokens):
|
272 |
+
tokens = tokens.cpu().numpy().tolist()
|
273 |
+
|
274 |
+
if chat_format == "chatml":
|
275 |
+
return _decode_chatml(
|
276 |
+
tokens,
|
277 |
+
stop_words=[],
|
278 |
+
eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
|
279 |
+
tokenizer=tokenizer,
|
280 |
+
raw_text_len=raw_text_len,
|
281 |
+
context_length=context_length,
|
282 |
+
verbose=verbose,
|
283 |
+
return_end_reason=return_end_reason,
|
284 |
+
errors=errors,
|
285 |
+
)
|
286 |
+
elif chat_format == "raw":
|
287 |
+
return _decode_default(
|
288 |
+
tokens,
|
289 |
+
stop_words=["<|endoftext|>"],
|
290 |
+
eod_words=["<|endoftext|>"],
|
291 |
+
tokenizer=tokenizer,
|
292 |
+
raw_text_len=raw_text_len,
|
293 |
+
verbose=verbose,
|
294 |
+
return_end_reason=return_end_reason,
|
295 |
+
errors=errors,
|
296 |
+
)
|
297 |
+
else:
|
298 |
+
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
299 |
+
|
300 |
+
|
301 |
+
class StopWordsLogitsProcessor(LogitsProcessor):
|
302 |
+
"""
|
303 |
+
:class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
|
304 |
+
|
305 |
+
Args:
|
306 |
+
stop_words_ids (:obj:`List[List[int]]`):
|
307 |
+
List of list of token ids of stop ids. In order to get the tokens of the words
|
308 |
+
that should not appear in the generated text, use :obj:`tokenizer(bad_word,
|
309 |
+
add_prefix_space=True).input_ids`.
|
310 |
+
eos_token_id (:obj:`int`):
|
311 |
+
The id of the `end-of-sequence` token.
|
312 |
+
"""
|
313 |
+
|
314 |
+
def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
|
315 |
+
|
316 |
+
if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
|
317 |
+
raise ValueError(
|
318 |
+
f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
|
319 |
+
)
|
320 |
+
if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
|
321 |
+
raise ValueError(
|
322 |
+
f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
|
323 |
+
)
|
324 |
+
if any(
|
325 |
+
any(
|
326 |
+
(not isinstance(token_id, (int, np.integer)) or token_id < 0)
|
327 |
+
for token_id in stop_word_ids
|
328 |
+
)
|
329 |
+
for stop_word_ids in stop_words_ids
|
330 |
+
):
|
331 |
+
raise ValueError(
|
332 |
+
f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
|
333 |
+
)
|
334 |
+
|
335 |
+
self.stop_words_ids = list(
|
336 |
+
filter(
|
337 |
+
lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
|
338 |
+
)
|
339 |
+
)
|
340 |
+
self.eos_token_id = eos_token_id
|
341 |
+
for stop_token_seq in self.stop_words_ids:
|
342 |
+
assert (
|
343 |
+
len(stop_token_seq) > 0
|
344 |
+
), "Stop words token sequences {} cannot have an empty list".format(
|
345 |
+
stop_words_ids
|
346 |
+
)
|
347 |
+
|
348 |
+
def __call__(
|
349 |
+
self, input_ids: torch.LongTensor, scores: torch.FloatTensor
|
350 |
+
) -> torch.FloatTensor:
|
351 |
+
stopped_samples = self._calc_stopped_samples(input_ids)
|
352 |
+
for i, should_stop in enumerate(stopped_samples):
|
353 |
+
if should_stop:
|
354 |
+
scores[i, self.eos_token_id] = float(2**15)
|
355 |
+
return scores
|
356 |
+
|
357 |
+
def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
|
358 |
+
if len(tokens) == 0:
|
359 |
+
# if bad word tokens is just one token always ban it
|
360 |
+
return True
|
361 |
+
elif len(tokens) > len(prev_tokens):
|
362 |
+
# if bad word tokens are longer then prev input_ids they can't be equal
|
363 |
+
return False
|
364 |
+
elif prev_tokens[-len(tokens) :].tolist() == tokens:
|
365 |
+
# if tokens match
|
366 |
+
return True
|
367 |
+
else:
|
368 |
+
return False
|
369 |
+
|
370 |
+
def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
|
371 |
+
stopped_samples = []
|
372 |
+
for prev_input_ids_slice in prev_input_ids:
|
373 |
+
match = False
|
374 |
+
for stop_token_seq in self.stop_words_ids:
|
375 |
+
if self._tokens_match(prev_input_ids_slice, stop_token_seq):
|
376 |
+
# if tokens do not match continue
|
377 |
+
match = True
|
378 |
+
break
|
379 |
+
stopped_samples.append(match)
|
380 |
+
|
381 |
+
return stopped_samples
|
382 |
+
|
383 |
+
|
384 |
+
def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
|
385 |
+
"""This function has been mostly taken from huggingface conversational
|
386 |
+
ai code at
|
387 |
+
https://medium.com/huggingface/how-to-build-a-state-of-the-art-
|
388 |
+
conversational-ai-with-transfer-learning-2d818ac26313"""
|
389 |
+
|
390 |
+
if top_k > 0:
|
391 |
+
# Remove all tokens with a probability less than the
|
392 |
+
# last token of the top-k
|
393 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
394 |
+
logits[indices_to_remove] = filter_value
|
395 |
+
|
396 |
+
if top_p > 0.0:
|
397 |
+
# Cconvert to 1D
|
398 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
399 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
400 |
+
|
401 |
+
# Remove tokens with cumulative probability above the threshold
|
402 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
403 |
+
# Shift the indices to the right to keep also the first token
|
404 |
+
# above the threshold
|
405 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
406 |
+
sorted_indices_to_remove[..., 0] = 0
|
407 |
+
for i in range(sorted_indices.size(0)):
|
408 |
+
indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
|
409 |
+
logits[i][indices_to_remove] = filter_value
|
410 |
+
|
411 |
+
return logits
|
412 |
+
|
413 |
+
|
414 |
+
def switch(val1, val2, boolean):
|
415 |
+
boolean = boolean.type_as(val1)
|
416 |
+
return (1 - boolean) * val1 + boolean * val2
|
tokenization_qwen.py
ADDED
@@ -0,0 +1,276 @@
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Alibaba Cloud.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
"""Tokenization classes for QWen."""
|
7 |
+
|
8 |
+
import base64
|
9 |
+
import logging
|
10 |
+
import os
|
11 |
+
import unicodedata
|
12 |
+
from typing import Collection, Dict, List, Set, Tuple, Union
|
13 |
+
|
14 |
+
import tiktoken
|
15 |
+
from transformers import PreTrainedTokenizer, AddedToken
|
16 |
+
|
17 |
+
logger = logging.getLogger(__name__)
|
18 |
+
|
19 |
+
|
20 |
+
VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
|
21 |
+
|
22 |
+
PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
23 |
+
ENDOFTEXT = "<|endoftext|>"
|
24 |
+
IMSTART = "<|im_start|>"
|
25 |
+
IMEND = "<|im_end|>"
|
26 |
+
# as the default behavior is changed to allow special tokens in
|
27 |
+
# regular texts, the surface forms of special tokens need to be
|
28 |
+
# as different as possible to minimize the impact
|
29 |
+
EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
|
30 |
+
# changed to use actual index to avoid misconfiguration with vocabulary expansion
|
31 |
+
SPECIAL_START_ID = 151643
|
32 |
+
SPECIAL_TOKENS = tuple(
|
33 |
+
enumerate(
|
34 |
+
(
|
35 |
+
(
|
36 |
+
ENDOFTEXT,
|
37 |
+
IMSTART,
|
38 |
+
IMEND,
|
39 |
+
)
|
40 |
+
+ EXTRAS
|
41 |
+
),
|
42 |
+
start=SPECIAL_START_ID,
|
43 |
+
)
|
44 |
+
)
|
45 |
+
SPECIAL_TOKENS_SET = set(t for i, t in SPECIAL_TOKENS)
|
46 |
+
|
47 |
+
|
48 |
+
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
|
49 |
+
with open(tiktoken_bpe_file, "rb") as f:
|
50 |
+
contents = f.read()
|
51 |
+
return {
|
52 |
+
base64.b64decode(token): int(rank)
|
53 |
+
for token, rank in (line.split() for line in contents.splitlines() if line)
|
54 |
+
}
|
55 |
+
|
56 |
+
|
57 |
+
class QWenTokenizer(PreTrainedTokenizer):
|
58 |
+
"""QWen tokenizer."""
|
59 |
+
|
60 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
61 |
+
|
62 |
+
def __init__(
|
63 |
+
self,
|
64 |
+
vocab_file,
|
65 |
+
errors="replace",
|
66 |
+
extra_vocab_file=None,
|
67 |
+
**kwargs,
|
68 |
+
):
|
69 |
+
super().__init__(**kwargs)
|
70 |
+
|
71 |
+
# how to handle errors in decoding UTF-8 byte sequences
|
72 |
+
# use ignore if you are in streaming inference
|
73 |
+
self.errors = errors
|
74 |
+
|
75 |
+
self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
|
76 |
+
self.special_tokens = {
|
77 |
+
token: index
|
78 |
+
for index, token in SPECIAL_TOKENS
|
79 |
+
}
|
80 |
+
|
81 |
+
# try load extra vocab from file
|
82 |
+
if extra_vocab_file is not None:
|
83 |
+
used_ids = set(self.mergeable_ranks.values()) | set(self.special_tokens.values())
|
84 |
+
extra_mergeable_ranks = _load_tiktoken_bpe(extra_vocab_file)
|
85 |
+
for token, index in extra_mergeable_ranks.items():
|
86 |
+
if token in self.mergeable_ranks:
|
87 |
+
logger.info(f"extra token {token} exists, skipping")
|
88 |
+
continue
|
89 |
+
if index in used_ids:
|
90 |
+
logger.info(f'the index {index} for extra token {token} exists, skipping')
|
91 |
+
continue
|
92 |
+
self.mergeable_ranks[token] = index
|
93 |
+
# the index may be sparse after this, but don't worry tiktoken.Encoding will handle this
|
94 |
+
|
95 |
+
enc = tiktoken.Encoding(
|
96 |
+
"Qwen",
|
97 |
+
pat_str=PAT_STR,
|
98 |
+
mergeable_ranks=self.mergeable_ranks,
|
99 |
+
special_tokens=self.special_tokens,
|
100 |
+
)
|
101 |
+
assert (
|
102 |
+
len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
|
103 |
+
), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
|
104 |
+
|
105 |
+
self.decoder = {
|
106 |
+
v: k for k, v in self.mergeable_ranks.items()
|
107 |
+
} # type: dict[int, bytes|str]
|
108 |
+
self.decoder.update({v: k for k, v in self.special_tokens.items()})
|
109 |
+
|
110 |
+
self.tokenizer = enc # type: tiktoken.Encoding
|
111 |
+
|
112 |
+
self.eod_id = self.tokenizer.eot_token
|
113 |
+
self.im_start_id = self.special_tokens[IMSTART]
|
114 |
+
self.im_end_id = self.special_tokens[IMEND]
|
115 |
+
|
116 |
+
def __getstate__(self):
|
117 |
+
# for pickle lovers
|
118 |
+
state = self.__dict__.copy()
|
119 |
+
del state["tokenizer"]
|
120 |
+
return state
|
121 |
+
|
122 |
+
def __setstate__(self, state):
|
123 |
+
# tokenizer is not python native; don't pass it; rebuild it
|
124 |
+
self.__dict__.update(state)
|
125 |
+
enc = tiktoken.Encoding(
|
126 |
+
"Qwen",
|
127 |
+
pat_str=PAT_STR,
|
128 |
+
mergeable_ranks=self.mergeable_ranks,
|
129 |
+
special_tokens=self.special_tokens,
|
130 |
+
)
|
131 |
+
self.tokenizer = enc
|
132 |
+
|
133 |
+
def __len__(self) -> int:
|
134 |
+
return self.tokenizer.n_vocab
|
135 |
+
|
136 |
+
def get_vocab(self) -> Dict[bytes, int]:
|
137 |
+
return self.mergeable_ranks
|
138 |
+
|
139 |
+
def convert_tokens_to_ids(
|
140 |
+
self, tokens: Union[bytes, str, List[Union[bytes, str]]]
|
141 |
+
) -> List[int]:
|
142 |
+
ids = []
|
143 |
+
if isinstance(tokens, (str, bytes)):
|
144 |
+
if tokens in self.special_tokens:
|
145 |
+
return self.special_tokens[tokens]
|
146 |
+
else:
|
147 |
+
return self.mergeable_ranks.get(tokens)
|
148 |
+
for token in tokens:
|
149 |
+
if token in self.special_tokens:
|
150 |
+
ids.append(self.special_tokens[token])
|
151 |
+
else:
|
152 |
+
ids.append(self.mergeable_ranks.get(token))
|
153 |
+
return ids
|
154 |
+
|
155 |
+
def _add_tokens(
|
156 |
+
self,
|
157 |
+
new_tokens: Union[List[str], List[AddedToken]],
|
158 |
+
special_tokens: bool = False,
|
159 |
+
) -> int:
|
160 |
+
if not special_tokens and new_tokens:
|
161 |
+
raise ValueError("Adding regular tokens is not supported")
|
162 |
+
for token in new_tokens:
|
163 |
+
surface_form = token.content if isinstance(token, AddedToken) else token
|
164 |
+
if surface_form not in SPECIAL_TOKENS_SET:
|
165 |
+
raise ValueError("Adding unknown special tokens is not supported")
|
166 |
+
return 0
|
167 |
+
|
168 |
+
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
|
169 |
+
"""
|
170 |
+
Save only the vocabulary of the tokenizer (vocabulary).
|
171 |
+
|
172 |
+
Returns:
|
173 |
+
`Tuple(str)`: Paths to the files saved.
|
174 |
+
"""
|
175 |
+
file_path = os.path.join(save_directory, "qwen.tiktoken")
|
176 |
+
with open(file_path, "w", encoding="utf8") as w:
|
177 |
+
for k, v in self.mergeable_ranks.items():
|
178 |
+
line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
|
179 |
+
w.write(line)
|
180 |
+
return (file_path,)
|
181 |
+
|
182 |
+
def tokenize(
|
183 |
+
self,
|
184 |
+
text: str,
|
185 |
+
allowed_special: Union[Set, str] = "all",
|
186 |
+
disallowed_special: Union[Collection, str] = (),
|
187 |
+
**kwargs,
|
188 |
+
) -> List[Union[bytes, str]]:
|
189 |
+
"""
|
190 |
+
Converts a string in a sequence of tokens.
|
191 |
+
|
192 |
+
Args:
|
193 |
+
text (`str`):
|
194 |
+
The sequence to be encoded.
|
195 |
+
allowed_special (`Literal["all"]` or `set`):
|
196 |
+
The surface forms of the tokens to be encoded as special tokens in regular texts.
|
197 |
+
Default to "all".
|
198 |
+
disallowed_special (`Literal["all"]` or `Collection`):
|
199 |
+
The surface forms of the tokens that should not be in regular texts and trigger errors.
|
200 |
+
Default to an empty tuple.
|
201 |
+
|
202 |
+
kwargs (additional keyword arguments, *optional*):
|
203 |
+
Will be passed to the underlying model specific encode method.
|
204 |
+
|
205 |
+
Returns:
|
206 |
+
`List[bytes|str]`: The list of tokens.
|
207 |
+
"""
|
208 |
+
tokens = []
|
209 |
+
text = unicodedata.normalize("NFC", text)
|
210 |
+
|
211 |
+
# this implementation takes a detour: text -> token id -> token surface forms
|
212 |
+
for t in self.tokenizer.encode(
|
213 |
+
text, allowed_special=allowed_special, disallowed_special=disallowed_special
|
214 |
+
):
|
215 |
+
tokens.append(self.decoder[t])
|
216 |
+
return tokens
|
217 |
+
|
218 |
+
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
|
219 |
+
"""
|
220 |
+
Converts a sequence of tokens in a single string.
|
221 |
+
"""
|
222 |
+
text = ""
|
223 |
+
temp = b""
|
224 |
+
for t in tokens:
|
225 |
+
if isinstance(t, str):
|
226 |
+
if temp:
|
227 |
+
text += temp.decode("utf-8", errors=self.errors)
|
228 |
+
temp = b""
|
229 |
+
text += t
|
230 |
+
elif isinstance(t, bytes):
|
231 |
+
temp += t
|
232 |
+
else:
|
233 |
+
raise TypeError("token should only be of type types or str")
|
234 |
+
if temp:
|
235 |
+
text += temp.decode("utf-8", errors=self.errors)
|
236 |
+
return text
|
237 |
+
|
238 |
+
@property
|
239 |
+
def vocab_size(self):
|
240 |
+
return self.tokenizer.n_vocab
|
241 |
+
|
242 |
+
def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
|
243 |
+
"""Converts an id to a token, special tokens included"""
|
244 |
+
if index in self.decoder:
|
245 |
+
return self.decoder[index]
|
246 |
+
raise ValueError("unknown ids")
|
247 |
+
|
248 |
+
def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
|
249 |
+
"""Converts a token to an id using the vocab, special tokens included"""
|
250 |
+
if token in self.special_tokens:
|
251 |
+
return self.special_tokens[token]
|
252 |
+
if token in self.mergeable_ranks:
|
253 |
+
return self.mergeable_ranks[token]
|
254 |
+
raise ValueError("unknown token")
|
255 |
+
|
256 |
+
def _tokenize(self, text: str, **kwargs):
|
257 |
+
"""
|
258 |
+
Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
|
259 |
+
vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
|
260 |
+
|
261 |
+
Do NOT take care of added tokens.
|
262 |
+
"""
|
263 |
+
raise NotImplementedError
|
264 |
+
|
265 |
+
def _decode(
|
266 |
+
self,
|
267 |
+
token_ids: Union[int, List[int]],
|
268 |
+
skip_special_tokens: bool = False,
|
269 |
+
errors: str = None,
|
270 |
+
**kwargs,
|
271 |
+
) -> str:
|
272 |
+
if isinstance(token_ids, int):
|
273 |
+
token_ids = [token_ids]
|
274 |
+
if skip_special_tokens:
|
275 |
+
token_ids = [i for i in token_ids if i < self.eod_id]
|
276 |
+
return self.tokenizer.decode(token_ids, errors=errors or self.errors)
|