update
Browse files- config.json +1 -1
- generation_utils.py +0 -45
- modeling_baichuan.py +401 -277
config.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
{
|
2 |
"_from_model_config": true,
|
3 |
-
"_name_or_path": "
|
4 |
"architectures": [
|
5 |
"BaichuanForCausalLM"
|
6 |
],
|
|
|
1 |
{
|
2 |
"_from_model_config": true,
|
3 |
+
"_name_or_path": "HuatuoGPT2-13B",
|
4 |
"architectures": [
|
5 |
"BaichuanForCausalLM"
|
6 |
],
|
generation_utils.py
CHANGED
@@ -3,51 +3,6 @@ from queue import Queue
|
|
3 |
|
4 |
import torch
|
5 |
|
6 |
-
|
7 |
-
# def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
8 |
-
# def _parse_messages(messages, split_role="user"):
|
9 |
-
# system, rounds = "", []
|
10 |
-
# round = []
|
11 |
-
# for i, message in enumerate(messages):
|
12 |
-
# if message["role"] == "system":
|
13 |
-
# assert i == 0
|
14 |
-
# system = message["content"]
|
15 |
-
# continue
|
16 |
-
# if message["role"] == split_role and round:
|
17 |
-
# rounds.append(round)
|
18 |
-
# round = []
|
19 |
-
# round.append(message)
|
20 |
-
# if round:
|
21 |
-
# rounds.append(round)
|
22 |
-
# return system, rounds
|
23 |
-
|
24 |
-
# max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
|
25 |
-
# max_input_tokens = model.config.model_max_length - max_new_tokens
|
26 |
-
# system, rounds = _parse_messages(messages, split_role="user")
|
27 |
-
# system_tokens = tokenizer.encode(system)
|
28 |
-
# max_history_tokens = max_input_tokens - len(system_tokens)
|
29 |
-
|
30 |
-
# history_tokens = []
|
31 |
-
# for round in rounds[::-1]:
|
32 |
-
# round_tokens = []
|
33 |
-
# for message in round:
|
34 |
-
# if message["role"] == "user":
|
35 |
-
# round_tokens.append(model.generation_config.user_token_id)
|
36 |
-
# else:
|
37 |
-
# round_tokens.append(model.generation_config.assistant_token_id)
|
38 |
-
# round_tokens.extend(tokenizer.encode(message["content"]))
|
39 |
-
# if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
|
40 |
-
# history_tokens = round_tokens + history_tokens # concat left
|
41 |
-
# if len(history_tokens) < max_history_tokens:
|
42 |
-
# continue
|
43 |
-
# break
|
44 |
-
|
45 |
-
# input_tokens = system_tokens + history_tokens
|
46 |
-
# if messages[-1]["role"] != "assistant":
|
47 |
-
# input_tokens.append(model.generation_config.assistant_token_id)
|
48 |
-
# input_tokens = input_tokens[-max_input_tokens:] # truncate left
|
49 |
-
# return torch.LongTensor([input_tokens]).to(model.device)
|
50 |
-
|
51 |
# for HuatuoGPT2
|
52 |
def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
53 |
def _parse_messages(messages, split_role="user"):
|
|
|
3 |
|
4 |
import torch
|
5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
# for HuatuoGPT2
|
7 |
def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
8 |
def _parse_messages(messages, split_role="user"):
|
modeling_baichuan.py
CHANGED
@@ -1,45 +1,26 @@
|
|
1 |
-
# Copyright 2023 Baichuan
|
2 |
-
|
3 |
-
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
-
#
|
5 |
-
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
-
# and OPT implementations in this library. It has been modified from its
|
7 |
-
# original forms to accommodate minor architectural differences compared
|
8 |
-
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
-
#
|
10 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
-
# you may not use this file except in compliance with the License.
|
12 |
-
# You may obtain a copy of the License at
|
13 |
-
#
|
14 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
-
#
|
16 |
-
# Unless required by applicable law or agreed to in writing, software
|
17 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
-
# See the License for the specific language governing permissions and
|
20 |
-
# limitations under the License.
|
21 |
-
|
22 |
|
23 |
from .configuration_baichuan import BaichuanConfig
|
24 |
from .generation_utils import build_chat_input, TextIterStreamer
|
25 |
|
26 |
import math
|
27 |
-
from typing import List, Optional, Tuple, Union
|
28 |
from threading import Thread
|
|
|
29 |
|
30 |
import torch
|
31 |
-
import torch.utils.checkpoint
|
32 |
from torch import nn
|
33 |
-
from torch.nn import
|
34 |
from torch.nn import functional as F
|
35 |
from transformers import PreTrainedModel, PretrainedConfig
|
36 |
from transformers.activations import ACT2FN
|
37 |
-
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
38 |
from transformers.generation.utils import GenerationConfig
|
|
|
39 |
from transformers.utils import logging, ContextManagers
|
40 |
|
41 |
import os
|
42 |
from contextlib import contextmanager
|
|
|
|
|
43 |
logger = logging.get_logger(__name__)
|
44 |
|
45 |
try:
|
@@ -51,169 +32,138 @@ except ImportError:
|
|
51 |
)
|
52 |
|
53 |
|
54 |
-
|
55 |
-
def
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
63 |
-
mask_cond = torch.arange(mask.size(-1), device=device)
|
64 |
-
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
65 |
-
mask = mask.to(dtype)
|
66 |
-
|
67 |
-
if past_key_values_length > 0:
|
68 |
-
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
69 |
-
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
70 |
-
|
71 |
-
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
72 |
-
"""
|
73 |
-
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
74 |
-
"""
|
75 |
-
if len(mask.size()) == 3:
|
76 |
-
bsz, src_len, _ = mask.size()
|
77 |
-
tgt_len = tgt_len if tgt_len is not None else src_len
|
78 |
-
expanded_mask = mask[:,None,:,:].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
79 |
else:
|
80 |
-
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
RMSNorm is equivalent to T5LayerNorm
|
93 |
-
"""
|
94 |
super().__init__()
|
95 |
-
self.weight = nn.Parameter(torch.
|
96 |
-
self.
|
97 |
|
98 |
def forward(self, hidden_states):
|
99 |
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
100 |
-
hidden_states = hidden_states * torch.rsqrt(variance + self.
|
101 |
|
102 |
-
# convert into half-precision
|
103 |
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
104 |
hidden_states = hidden_states.to(self.weight.dtype)
|
105 |
|
106 |
return self.weight * hidden_states
|
107 |
|
108 |
|
109 |
-
class
|
110 |
-
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
111 |
-
super().__init__()
|
112 |
-
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
113 |
-
self.max_seq_len_cached = max_position_embeddings
|
114 |
-
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
115 |
-
freqs = torch.outer(t, self.inv_freq)
|
116 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
117 |
-
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32)
|
118 |
-
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32)
|
119 |
-
def forward(self, x, seq_len=None):
|
120 |
-
# x: [bs, num_attention_heads, seq_len, head_size]
|
121 |
-
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
122 |
-
if seq_len > self.max_seq_len_cached:
|
123 |
-
self.max_seq_len_cached = seq_len
|
124 |
-
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
125 |
-
freqs = torch.outer(t, self.inv_freq)
|
126 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
127 |
-
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32).to(x.device)
|
128 |
-
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32).to(x.device)
|
129 |
-
elif self.cos_cached.device != x.device:
|
130 |
-
self.cos_cached = self.cos_cached.to(x.device)
|
131 |
-
self.sin_cached = self.sin_cached.to(x.device)
|
132 |
-
return (
|
133 |
-
self.cos_cached[:, :, :seq_len, ...],
|
134 |
-
self.sin_cached[:, :, :seq_len, ...],
|
135 |
-
)
|
136 |
-
|
137 |
-
|
138 |
-
def rotate_half(x):
|
139 |
-
"""Rotates half the hidden dims of the input."""
|
140 |
-
x1 = x[..., : x.shape[-1] // 2]
|
141 |
-
x2 = x[..., x.shape[-1] // 2:]
|
142 |
-
return torch.cat((-x2, x1), dim=-1)
|
143 |
-
|
144 |
-
|
145 |
-
def apply_rotary_pos_emb(q, k, cos_, sin_, position_ids):
|
146 |
-
cos = cos_.squeeze(1).squeeze(0) # [seq_len, dim]
|
147 |
-
sin = sin_.squeeze(1).squeeze(0) # [seq_len, dim]
|
148 |
-
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
149 |
-
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
150 |
-
q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
|
151 |
-
k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
|
152 |
-
return q_embed.to(q.dtype), k_embed.to(k.dtype)
|
153 |
-
|
154 |
-
|
155 |
-
class MLP(nn.Module):
|
156 |
def __init__(
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
):
|
162 |
super().__init__()
|
163 |
-
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
164 |
-
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
165 |
-
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
166 |
self.act_fn = ACT2FN[hidden_act]
|
167 |
|
168 |
def forward(self, x):
|
169 |
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
170 |
|
171 |
|
172 |
-
class
|
173 |
-
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
174 |
def __init__(self, config: BaichuanConfig):
|
175 |
super().__init__()
|
176 |
self.config = config
|
177 |
self.hidden_size = config.hidden_size
|
178 |
self.num_heads = config.num_attention_heads
|
179 |
self.head_dim = self.hidden_size // self.num_heads
|
180 |
-
self.max_position_embeddings = config.
|
181 |
|
182 |
if (self.head_dim * self.num_heads) != self.hidden_size:
|
183 |
raise ValueError(
|
184 |
-
f"hidden_size
|
185 |
-
f" and `num_heads`: {self.num_heads})."
|
186 |
)
|
187 |
-
self.W_pack = nn.Linear(
|
188 |
-
|
189 |
-
|
|
|
|
|
|
|
190 |
|
191 |
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
192 |
-
return
|
|
|
|
|
|
|
|
|
193 |
|
194 |
def forward(
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
use_cache: bool = False,
|
202 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
203 |
bsz, q_len, _ = hidden_states.size()
|
204 |
|
205 |
proj = self.W_pack(hidden_states)
|
206 |
-
proj =
|
207 |
-
|
208 |
-
|
209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
|
211 |
kv_seq_len = key_states.shape[-2]
|
212 |
if past_key_value is not None:
|
213 |
kv_seq_len += past_key_value[0].shape[-2]
|
214 |
-
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
215 |
-
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
216 |
-
# [bsz, nh, t, hd]
|
217 |
|
218 |
if past_key_value is not None:
|
219 |
# reuse k, v, self_attention
|
@@ -223,16 +173,35 @@ class Attention(nn.Module):
|
|
223 |
past_key_value = (key_states, value_states) if use_cache else None
|
224 |
if xops is not None and self.training:
|
225 |
attn_weights = None
|
226 |
-
query_states = query_states.transpose(1, 2)
|
227 |
-
key_states = key_states.transpose(1, 2)
|
228 |
-
value_states = value_states.transpose(1, 2)
|
229 |
-
attn_output = xops.memory_efficient_attention(
|
230 |
-
|
231 |
-
)
|
232 |
-
else:
|
233 |
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
234 |
attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
|
235 |
attn_output = attn_output.transpose(1, 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
236 |
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
237 |
attn_output = self.o_proj(attn_output)
|
238 |
|
@@ -242,29 +211,31 @@ class Attention(nn.Module):
|
|
242 |
return attn_output, attn_weights, past_key_value
|
243 |
|
244 |
|
245 |
-
class
|
246 |
def __init__(self, config: BaichuanConfig):
|
247 |
super().__init__()
|
248 |
self.hidden_size = config.hidden_size
|
249 |
-
self.self_attn =
|
250 |
self.mlp = MLP(
|
251 |
hidden_size=self.hidden_size,
|
252 |
intermediate_size=config.intermediate_size,
|
253 |
hidden_act=config.hidden_act,
|
254 |
)
|
255 |
-
self.input_layernorm = RMSNorm(config.hidden_size,
|
256 |
-
self.post_attention_layernorm = RMSNorm(
|
|
|
|
|
257 |
|
258 |
def forward(
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
residual = hidden_states
|
269 |
|
270 |
hidden_states = self.input_layernorm(hidden_states)
|
@@ -273,7 +244,6 @@ class DecoderLayer(nn.Module):
|
|
273 |
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
274 |
hidden_states=hidden_states,
|
275 |
attention_mask=attention_mask,
|
276 |
-
position_ids=position_ids,
|
277 |
past_key_value=past_key_value,
|
278 |
output_attentions=output_attentions,
|
279 |
use_cache=use_cache,
|
@@ -288,9 +258,6 @@ class DecoderLayer(nn.Module):
|
|
288 |
|
289 |
outputs = (hidden_states,)
|
290 |
|
291 |
-
if output_attentions:
|
292 |
-
outputs += (self_attn_weights,)
|
293 |
-
|
294 |
if use_cache:
|
295 |
outputs += (present_key_value,)
|
296 |
|
@@ -301,16 +268,16 @@ class BaichuanPreTrainedModel(PreTrainedModel):
|
|
301 |
config_class = BaichuanConfig
|
302 |
base_model_prefix = "model"
|
303 |
supports_gradient_checkpointing = True
|
304 |
-
_no_split_modules = ["
|
305 |
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
306 |
|
307 |
def _init_weights(self, module):
|
308 |
std = self.config.initializer_range
|
309 |
-
if isinstance(module, nn.Linear):
|
310 |
module.weight.data.normal_(mean=0.0, std=std)
|
311 |
if module.bias is not None:
|
312 |
module.bias.data.zero_()
|
313 |
-
elif isinstance(module, nn.Embedding):
|
314 |
module.weight.data.normal_(mean=0.0, std=std)
|
315 |
if module.padding_idx is not None:
|
316 |
module.weight.data[module.padding_idx].zero_()
|
@@ -325,14 +292,20 @@ class BaichuanModel(BaichuanPreTrainedModel):
|
|
325 |
super().__init__(config)
|
326 |
self.padding_idx = config.pad_token_id
|
327 |
self.vocab_size = config.vocab_size
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
328 |
|
329 |
-
self.
|
330 |
-
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
331 |
-
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
332 |
-
|
333 |
-
self.gradient_checkpointing = False
|
334 |
-
# Initialize weights and apply final processing
|
335 |
self.post_init()
|
|
|
|
|
|
|
336 |
|
337 |
def get_input_embeddings(self):
|
338 |
return self.embed_tokens
|
@@ -340,86 +313,118 @@ class BaichuanModel(BaichuanPreTrainedModel):
|
|
340 |
def set_input_embeddings(self, value):
|
341 |
self.embed_tokens = value
|
342 |
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
if input_shape[-1] > 1:
|
349 |
-
combined_attention_mask = _make_causal_mask(
|
350 |
-
input_shape,
|
351 |
-
inputs_embeds.dtype,
|
352 |
-
device=inputs_embeds.device,
|
353 |
-
past_key_values_length=past_key_values_length,
|
354 |
)
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
inputs_embeds.device
|
360 |
)
|
361 |
-
|
362 |
-
|
|
|
363 |
)
|
364 |
-
|
365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
366 |
|
367 |
def forward(
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
return_dict: Optional[bool] = None,
|
378 |
) -> Union[Tuple, BaseModelOutputWithPast]:
|
379 |
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
380 |
-
output_hidden_states = (
|
381 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
382 |
-
)
|
383 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
384 |
-
|
385 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
386 |
-
|
387 |
-
# retrieve input_ids and inputs_embeds
|
388 |
if input_ids is not None and inputs_embeds is not None:
|
389 |
-
raise ValueError(
|
|
|
|
|
390 |
elif input_ids is not None:
|
391 |
batch_size, seq_length = input_ids.shape
|
392 |
elif inputs_embeds is not None:
|
393 |
batch_size, seq_length, _ = inputs_embeds.shape
|
394 |
else:
|
395 |
-
raise ValueError("You
|
|
|
|
|
|
|
|
|
396 |
|
397 |
seq_length_with_past = seq_length
|
398 |
-
past_key_values_length = 0
|
399 |
|
400 |
if past_key_values is not None:
|
401 |
past_key_values_length = past_key_values[0][0].shape[2]
|
402 |
seq_length_with_past = seq_length_with_past + past_key_values_length
|
403 |
|
404 |
-
if position_ids is None:
|
405 |
-
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
406 |
-
position_ids = torch.arange(
|
407 |
-
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
408 |
-
)
|
409 |
-
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
410 |
-
else:
|
411 |
-
position_ids = position_ids.view(-1, seq_length).long()
|
412 |
-
|
413 |
if inputs_embeds is None:
|
414 |
inputs_embeds = self.embed_tokens(input_ids)
|
415 |
-
|
416 |
-
if
|
417 |
-
|
418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
419 |
)
|
420 |
-
|
421 |
-
|
422 |
-
|
|
|
|
|
|
|
|
|
423 |
|
424 |
hidden_states = inputs_embeds
|
425 |
|
@@ -439,7 +444,9 @@ class BaichuanModel(BaichuanPreTrainedModel):
|
|
439 |
if output_hidden_states:
|
440 |
all_hidden_states += (hidden_states,)
|
441 |
|
442 |
-
past_key_value =
|
|
|
|
|
443 |
|
444 |
if self.gradient_checkpointing and self.training:
|
445 |
|
@@ -454,14 +461,12 @@ class BaichuanModel(BaichuanPreTrainedModel):
|
|
454 |
create_custom_forward(decoder_layer),
|
455 |
hidden_states,
|
456 |
attention_mask,
|
457 |
-
position_ids,
|
458 |
None,
|
459 |
)
|
460 |
else:
|
461 |
layer_outputs = decoder_layer(
|
462 |
hidden_states,
|
463 |
attention_mask=attention_mask,
|
464 |
-
position_ids=position_ids,
|
465 |
past_key_value=past_key_value,
|
466 |
output_attentions=output_attentions,
|
467 |
use_cache=use_cache,
|
@@ -483,7 +488,11 @@ class BaichuanModel(BaichuanPreTrainedModel):
|
|
483 |
|
484 |
next_cache = next_decoder_cache if use_cache else None
|
485 |
if not return_dict:
|
486 |
-
return tuple(
|
|
|
|
|
|
|
|
|
487 |
return BaseModelOutputWithPast(
|
488 |
last_hidden_state=hidden_states,
|
489 |
past_key_values=next_cache,
|
@@ -505,7 +514,7 @@ class NormHead(nn.Module):
|
|
505 |
self.first_flag = True
|
506 |
elif self.first_flag:
|
507 |
self.first_flag = False
|
508 |
-
self.weight
|
509 |
norm_weight = self.weight
|
510 |
else:
|
511 |
norm_weight = self.weight
|
@@ -523,17 +532,18 @@ def no_init_weights(_enable=True):
|
|
523 |
finally:
|
524 |
_init_weights = old_init_weights
|
525 |
|
|
|
526 |
class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
527 |
def __init__(self, config, *model_args, **model_kwargs):
|
528 |
super().__init__(config, *model_args, **model_kwargs)
|
529 |
self.model = BaichuanModel(config)
|
530 |
-
|
531 |
self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
|
|
|
532 |
if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
|
533 |
try:
|
534 |
from .quantizer import quantize_offline, init_model_weight_int4
|
535 |
except ImportError:
|
536 |
-
raise ImportError(f"Needs
|
537 |
quantize_offline(self, 4)
|
538 |
# Initialize weights and apply final processing
|
539 |
self.post_init()
|
@@ -571,6 +581,7 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
|
571 |
use_safetensors: bool = None,
|
572 |
**kwargs,
|
573 |
):
|
|
|
574 |
# Load config if we don't provide a configuration
|
575 |
if not isinstance(config, PretrainedConfig):
|
576 |
config_path = config if config is not None else pretrained_model_name_or_path
|
@@ -591,36 +602,97 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
|
591 |
)
|
592 |
else:
|
593 |
model_kwargs = kwargs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
594 |
return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
|
595 |
config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
|
596 |
force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
|
597 |
-
use_safetensors=use_safetensors, **kwargs)
|
598 |
|
599 |
def forward(
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
) -> Union[Tuple, CausalLMOutputWithPast]:
|
612 |
-
|
613 |
-
|
614 |
-
output_hidden_states = (
|
615 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
616 |
)
|
617 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
618 |
|
619 |
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
620 |
outputs = self.model(
|
621 |
input_ids=input_ids,
|
622 |
attention_mask=attention_mask,
|
623 |
-
position_ids=position_ids,
|
624 |
past_key_values=past_key_values,
|
625 |
inputs_embeds=inputs_embeds,
|
626 |
use_cache=use_cache,
|
@@ -658,20 +730,24 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
|
658 |
attentions=outputs.attentions,
|
659 |
)
|
660 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
661 |
def prepare_inputs_for_generation(
|
662 |
-
|
|
|
|
|
|
|
|
|
|
|
663 |
):
|
664 |
if past_key_values:
|
665 |
input_ids = input_ids[:, -1:]
|
666 |
|
667 |
-
position_ids = kwargs.get("position_ids", None)
|
668 |
-
if attention_mask is not None and position_ids is None:
|
669 |
-
# create position_ids on the fly for batch generation
|
670 |
-
position_ids = attention_mask.long().cumsum(-1) - 1
|
671 |
-
position_ids.masked_fill_(attention_mask == 0, 1)
|
672 |
-
if past_key_values:
|
673 |
-
position_ids = position_ids[:, -1].unsqueeze(-1)
|
674 |
-
|
675 |
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
676 |
if inputs_embeds is not None and past_key_values is None:
|
677 |
model_inputs = {"inputs_embeds": inputs_embeds}
|
@@ -680,7 +756,6 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
|
680 |
|
681 |
model_inputs.update(
|
682 |
{
|
683 |
-
"position_ids": position_ids,
|
684 |
"past_key_values": past_key_values,
|
685 |
"use_cache": kwargs.get("use_cache"),
|
686 |
"attention_mask": attention_mask,
|
@@ -690,22 +765,71 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
|
690 |
|
691 |
@staticmethod
|
692 |
def _reorder_cache(past_key_values, beam_idx):
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
|
698 |
-
def
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
704 |
|
705 |
def chat(self, tokenizer, messages: List[dict], stream=False,
|
706 |
generation_config: Optional[GenerationConfig]=None):
|
707 |
generation_config = generation_config or self.generation_config
|
708 |
input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
709 |
if stream:
|
710 |
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
711 |
Thread(target=self.generate, kwargs=dict(
|
|
|
1 |
+
# Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
from .configuration_baichuan import BaichuanConfig
|
4 |
from .generation_utils import build_chat_input, TextIterStreamer
|
5 |
|
6 |
import math
|
|
|
7 |
from threading import Thread
|
8 |
+
from typing import List, Optional, Tuple, Union
|
9 |
|
10 |
import torch
|
|
|
11 |
from torch import nn
|
12 |
+
from torch.nn import CrossEntropyLoss
|
13 |
from torch.nn import functional as F
|
14 |
from transformers import PreTrainedModel, PretrainedConfig
|
15 |
from transformers.activations import ACT2FN
|
|
|
16 |
from transformers.generation.utils import GenerationConfig
|
17 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
18 |
from transformers.utils import logging, ContextManagers
|
19 |
|
20 |
import os
|
21 |
from contextlib import contextmanager
|
22 |
+
from accelerate import init_empty_weights
|
23 |
+
|
24 |
logger = logging.get_logger(__name__)
|
25 |
|
26 |
try:
|
|
|
32 |
)
|
33 |
|
34 |
|
35 |
+
def _get_interleave(n):
|
36 |
+
def _get_interleave_power_of_2(n):
|
37 |
+
start = 2 ** (-(2 ** -(math.log2(n) - 3)))
|
38 |
+
ratio = start
|
39 |
+
return [start * ratio**i for i in range(n)]
|
40 |
+
|
41 |
+
if math.log2(n).is_integer():
|
42 |
+
return _get_interleave_power_of_2(n)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
else:
|
44 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(n))
|
45 |
+
return (
|
46 |
+
_get_interleave_power_of_2(closest_power_of_2)
|
47 |
+
+ _get_interleave(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
|
48 |
+
)
|
49 |
+
|
50 |
+
|
51 |
+
def _fill_with_neg_inf(t):
|
52 |
+
"""FP16-compatible function that fills a tensor with -inf."""
|
53 |
+
return t.float().fill_(float("-inf")).type_as(t)
|
54 |
+
|
55 |
|
56 |
+
def _buffered_future_mask(tensor, maxpos, alibi, attn_heads):
|
57 |
+
_future_mask = torch.triu(_fill_with_neg_inf(torch.zeros([maxpos, maxpos])), 1)
|
58 |
+
_future_mask = _future_mask.unsqueeze(0) + alibi
|
59 |
+
new_future_mask = _future_mask.to(tensor)
|
60 |
+
return new_future_mask[: tensor.shape[0] * attn_heads, :maxpos, :maxpos]
|
61 |
|
|
|
62 |
|
63 |
+
def _gen_alibi_mask(tensor, n_head, max_pos):
|
64 |
+
slopes = torch.Tensor(_get_interleave(n_head))
|
65 |
+
position_point = torch.arange(max_pos) - max_pos + 1
|
66 |
+
position_point = position_point.unsqueeze(0).unsqueeze(0).expand(n_head, -1, -1)
|
67 |
+
diag = torch.diag(position_point[0])
|
68 |
+
position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(-1, -2)
|
69 |
+
alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
|
70 |
+
alibi = alibi.view(n_head, 1, max_pos)
|
71 |
+
alibi_mask = torch.triu(_fill_with_neg_inf(torch.zeros([max_pos, max_pos])), 1)
|
72 |
+
alibi_mask = alibi_mask.unsqueeze(0) + alibi
|
73 |
+
return alibi_mask
|
74 |
|
75 |
+
|
76 |
+
class RMSNorm(torch.nn.Module):
|
77 |
+
def __init__(self, hidden_size, epsilon=1e-6):
|
|
|
|
|
78 |
super().__init__()
|
79 |
+
self.weight = torch.nn.Parameter(torch.empty(hidden_size))
|
80 |
+
self.epsilon = epsilon
|
81 |
|
82 |
def forward(self, hidden_states):
|
83 |
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
84 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.epsilon)
|
85 |
|
86 |
+
# convert into half-precision
|
87 |
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
88 |
hidden_states = hidden_states.to(self.weight.dtype)
|
89 |
|
90 |
return self.weight * hidden_states
|
91 |
|
92 |
|
93 |
+
class MLP(torch.nn.Module):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
def __init__(
|
95 |
+
self,
|
96 |
+
hidden_size: int,
|
97 |
+
intermediate_size: int,
|
98 |
+
hidden_act: str,
|
99 |
):
|
100 |
super().__init__()
|
101 |
+
self.gate_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
|
102 |
+
self.down_proj = torch.nn.Linear(intermediate_size, hidden_size, bias=False)
|
103 |
+
self.up_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
|
104 |
self.act_fn = ACT2FN[hidden_act]
|
105 |
|
106 |
def forward(self, x):
|
107 |
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
108 |
|
109 |
|
110 |
+
class BaichuanAttention(torch.nn.Module):
|
|
|
111 |
def __init__(self, config: BaichuanConfig):
|
112 |
super().__init__()
|
113 |
self.config = config
|
114 |
self.hidden_size = config.hidden_size
|
115 |
self.num_heads = config.num_attention_heads
|
116 |
self.head_dim = self.hidden_size // self.num_heads
|
117 |
+
self.max_position_embeddings = config.model_max_length
|
118 |
|
119 |
if (self.head_dim * self.num_heads) != self.hidden_size:
|
120 |
raise ValueError(
|
121 |
+
f"hidden_size {self.hidden_size} is not divisible by num_heads {self.num_heads}"
|
|
|
122 |
)
|
123 |
+
self.W_pack = torch.nn.Linear(
|
124 |
+
self.hidden_size, 3 * self.hidden_size, bias=False
|
125 |
+
)
|
126 |
+
self.o_proj = torch.nn.Linear(
|
127 |
+
self.num_heads * self.head_dim, self.hidden_size, bias=False
|
128 |
+
)
|
129 |
|
130 |
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
131 |
+
return (
|
132 |
+
tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
|
133 |
+
.transpose(1, 2)
|
134 |
+
.contiguous()
|
135 |
+
)
|
136 |
|
137 |
def forward(
|
138 |
+
self,
|
139 |
+
hidden_states: torch.Tensor,
|
140 |
+
attention_mask: Optional[torch.Tensor] = None,
|
141 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
142 |
+
output_attentions: bool = False,
|
143 |
+
use_cache: bool = False,
|
|
|
144 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
145 |
bsz, q_len, _ = hidden_states.size()
|
146 |
|
147 |
proj = self.W_pack(hidden_states)
|
148 |
+
proj = (
|
149 |
+
proj.unflatten(-1, (3, self.hidden_size))
|
150 |
+
.unsqueeze(0)
|
151 |
+
.transpose(0, -2)
|
152 |
+
.squeeze(-2)
|
153 |
+
)
|
154 |
+
query_states = (
|
155 |
+
proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
156 |
+
)
|
157 |
+
key_states = (
|
158 |
+
proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
159 |
+
)
|
160 |
+
value_states = (
|
161 |
+
proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
162 |
+
)
|
163 |
|
164 |
kv_seq_len = key_states.shape[-2]
|
165 |
if past_key_value is not None:
|
166 |
kv_seq_len += past_key_value[0].shape[-2]
|
|
|
|
|
|
|
167 |
|
168 |
if past_key_value is not None:
|
169 |
# reuse k, v, self_attention
|
|
|
173 |
past_key_value = (key_states, value_states) if use_cache else None
|
174 |
if xops is not None and self.training:
|
175 |
attn_weights = None
|
176 |
+
# query_states = query_states.transpose(1, 2)
|
177 |
+
# key_states = key_states.transpose(1, 2)
|
178 |
+
# value_states = value_states.transpose(1, 2)
|
179 |
+
# attn_output = xops.memory_efficient_attention(
|
180 |
+
# query_states, key_states, value_states, attn_bias=attention_mask
|
181 |
+
# )
|
|
|
182 |
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
183 |
attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
|
184 |
attn_output = attn_output.transpose(1, 2)
|
185 |
+
else:
|
186 |
+
attn_weights = torch.matmul(
|
187 |
+
query_states, key_states.transpose(2, 3)
|
188 |
+
) / math.sqrt(self.head_dim)
|
189 |
+
|
190 |
+
if attention_mask is not None:
|
191 |
+
if q_len == 1: # inference with cache
|
192 |
+
if len(attention_mask.size()) == 4:
|
193 |
+
attention_mask = attention_mask[:, :, -1:, :]
|
194 |
+
else:
|
195 |
+
attention_mask = attention_mask[:, -1:, :]
|
196 |
+
attn_weights = attn_weights + attention_mask
|
197 |
+
attn_weights = torch.max(
|
198 |
+
attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
|
199 |
+
)
|
200 |
+
|
201 |
+
attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
|
202 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
203 |
+
|
204 |
+
attn_output = attn_output.transpose(1, 2)
|
205 |
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
206 |
attn_output = self.o_proj(attn_output)
|
207 |
|
|
|
211 |
return attn_output, attn_weights, past_key_value
|
212 |
|
213 |
|
214 |
+
class BaichuanLayer(torch.nn.Module):
|
215 |
def __init__(self, config: BaichuanConfig):
|
216 |
super().__init__()
|
217 |
self.hidden_size = config.hidden_size
|
218 |
+
self.self_attn = BaichuanAttention(config=config)
|
219 |
self.mlp = MLP(
|
220 |
hidden_size=self.hidden_size,
|
221 |
intermediate_size=config.intermediate_size,
|
222 |
hidden_act=config.hidden_act,
|
223 |
)
|
224 |
+
self.input_layernorm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
|
225 |
+
self.post_attention_layernorm = RMSNorm(
|
226 |
+
config.hidden_size, epsilon=config.rms_norm_eps
|
227 |
+
)
|
228 |
|
229 |
def forward(
|
230 |
+
self,
|
231 |
+
hidden_states: torch.Tensor,
|
232 |
+
attention_mask: Optional[torch.Tensor] = None,
|
233 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
234 |
+
output_attentions: Optional[bool] = False,
|
235 |
+
use_cache: Optional[bool] = False,
|
236 |
+
) -> Tuple[
|
237 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
238 |
+
]:
|
239 |
residual = hidden_states
|
240 |
|
241 |
hidden_states = self.input_layernorm(hidden_states)
|
|
|
244 |
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
245 |
hidden_states=hidden_states,
|
246 |
attention_mask=attention_mask,
|
|
|
247 |
past_key_value=past_key_value,
|
248 |
output_attentions=output_attentions,
|
249 |
use_cache=use_cache,
|
|
|
258 |
|
259 |
outputs = (hidden_states,)
|
260 |
|
|
|
|
|
|
|
261 |
if use_cache:
|
262 |
outputs += (present_key_value,)
|
263 |
|
|
|
268 |
config_class = BaichuanConfig
|
269 |
base_model_prefix = "model"
|
270 |
supports_gradient_checkpointing = True
|
271 |
+
_no_split_modules = ["BaichuanLayer"]
|
272 |
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
273 |
|
274 |
def _init_weights(self, module):
|
275 |
std = self.config.initializer_range
|
276 |
+
if isinstance(module, torch.nn.Linear):
|
277 |
module.weight.data.normal_(mean=0.0, std=std)
|
278 |
if module.bias is not None:
|
279 |
module.bias.data.zero_()
|
280 |
+
elif isinstance(module, torch.nn.Embedding):
|
281 |
module.weight.data.normal_(mean=0.0, std=std)
|
282 |
if module.padding_idx is not None:
|
283 |
module.weight.data[module.padding_idx].zero_()
|
|
|
292 |
super().__init__(config)
|
293 |
self.padding_idx = config.pad_token_id
|
294 |
self.vocab_size = config.vocab_size
|
295 |
+
self.n_head = config.num_attention_heads
|
296 |
+
self.embed_tokens = torch.nn.Embedding(
|
297 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
298 |
+
)
|
299 |
+
self.layers = torch.nn.ModuleList(
|
300 |
+
[BaichuanLayer(config) for _ in range(config.num_hidden_layers)]
|
301 |
+
)
|
302 |
+
self.norm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
|
303 |
|
304 |
+
self.gradient_checkpointing = config.gradient_checkpointing
|
|
|
|
|
|
|
|
|
|
|
305 |
self.post_init()
|
306 |
+
self.max_cache_pos = config.model_max_length
|
307 |
+
self.first_run = True
|
308 |
+
self.alibi_mask = None
|
309 |
|
310 |
def get_input_embeddings(self):
|
311 |
return self.embed_tokens
|
|
|
313 |
def set_input_embeddings(self, value):
|
314 |
self.embed_tokens = value
|
315 |
|
316 |
+
def get_alibi_mask(self, tensor, seq_length_with_past):
|
317 |
+
if self.training:
|
318 |
+
slopes = torch.Tensor(_get_interleave(self.n_head))
|
319 |
+
position_point = (
|
320 |
+
torch.arange(seq_length_with_past) - seq_length_with_past + 1
|
|
|
|
|
|
|
|
|
|
|
|
|
321 |
)
|
322 |
+
position_point = (
|
323 |
+
position_point.unsqueeze(0)
|
324 |
+
.unsqueeze(0)
|
325 |
+
.expand(self.n_head, seq_length_with_past, -1)
|
|
|
326 |
)
|
327 |
+
diag = torch.diag(position_point[0])
|
328 |
+
position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(
|
329 |
+
-1, -2
|
330 |
)
|
331 |
+
alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
|
332 |
+
mask = _buffered_future_mask(
|
333 |
+
tensor, seq_length_with_past, alibi, self.n_head
|
334 |
+
)
|
335 |
+
else:
|
336 |
+
if self.first_run:
|
337 |
+
self.first_run = False
|
338 |
+
self.register_buffer(
|
339 |
+
"future_mask",
|
340 |
+
_gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
|
341 |
+
tensor
|
342 |
+
),
|
343 |
+
persistent=False,
|
344 |
+
)
|
345 |
+
if seq_length_with_past > self.max_cache_pos:
|
346 |
+
self.max_cache_pos = seq_length_with_past
|
347 |
+
self.register_buffer(
|
348 |
+
"future_mask",
|
349 |
+
_gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
|
350 |
+
tensor
|
351 |
+
),
|
352 |
+
persistent=False,
|
353 |
+
)
|
354 |
+
mask = self.future_mask[
|
355 |
+
: self.n_head, :seq_length_with_past, :seq_length_with_past
|
356 |
+
]
|
357 |
+
return mask
|
358 |
|
359 |
def forward(
|
360 |
+
self,
|
361 |
+
input_ids: torch.LongTensor = None,
|
362 |
+
attention_mask: Optional[torch.Tensor] = None,
|
363 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
364 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
365 |
+
use_cache: Optional[bool] = False,
|
366 |
+
output_attentions: Optional[bool] = False,
|
367 |
+
output_hidden_states: Optional[bool] = False,
|
368 |
+
return_dict: Optional[bool] = True,
|
|
|
369 |
) -> Union[Tuple, BaseModelOutputWithPast]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
370 |
if input_ids is not None and inputs_embeds is not None:
|
371 |
+
raise ValueError(
|
372 |
+
"You cannot provide both input_ids and inputs_embeds simultaneously"
|
373 |
+
)
|
374 |
elif input_ids is not None:
|
375 |
batch_size, seq_length = input_ids.shape
|
376 |
elif inputs_embeds is not None:
|
377 |
batch_size, seq_length, _ = inputs_embeds.shape
|
378 |
else:
|
379 |
+
raise ValueError("You need to provide input_ids or inputs_embeds")
|
380 |
+
|
381 |
+
return_dict = (
|
382 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
383 |
+
)
|
384 |
|
385 |
seq_length_with_past = seq_length
|
|
|
386 |
|
387 |
if past_key_values is not None:
|
388 |
past_key_values_length = past_key_values[0][0].shape[2]
|
389 |
seq_length_with_past = seq_length_with_past + past_key_values_length
|
390 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
391 |
if inputs_embeds is None:
|
392 |
inputs_embeds = self.embed_tokens(input_ids)
|
393 |
+
|
394 |
+
if self.training:
|
395 |
+
if (
|
396 |
+
self.alibi_mask is None
|
397 |
+
or self.alibi_mask.shape[-1] != seq_length_with_past
|
398 |
+
):
|
399 |
+
self.alibi_mask = self.get_alibi_mask(
|
400 |
+
inputs_embeds, seq_length_with_past
|
401 |
+
)
|
402 |
+
alibi_mask = self.alibi_mask
|
403 |
+
else:
|
404 |
+
alibi_mask = self.get_alibi_mask(inputs_embeds, seq_length_with_past)
|
405 |
+
|
406 |
+
if attention_mask is not None:
|
407 |
+
if len(attention_mask.shape) == 2:
|
408 |
+
expanded_mask = attention_mask.to(alibi_mask.dtype)
|
409 |
+
expanded_mask = torch.tril(
|
410 |
+
torch.gt(expanded_mask[:, :, None] * expanded_mask[:, None, :], 0)
|
411 |
+
) * torch.eq(expanded_mask[:, :, None] - expanded_mask[:, None, :], 0)
|
412 |
+
else:
|
413 |
+
expanded_mask = attention_mask
|
414 |
+
bsz = inputs_embeds.size(0)
|
415 |
+
src_len, tgt_len = alibi_mask.size()[-2:]
|
416 |
+
expanded_mask = (
|
417 |
+
expanded_mask.unsqueeze(1)
|
418 |
+
.expand(bsz, 1, src_len, tgt_len)
|
419 |
+
.to(alibi_mask.dtype)
|
420 |
)
|
421 |
+
inverted_mask = 1.0 - expanded_mask
|
422 |
+
inverted_mask = inverted_mask.masked_fill(
|
423 |
+
inverted_mask.to(torch.bool), torch.finfo(alibi_mask.dtype).min
|
424 |
+
)
|
425 |
+
attention_mask = inverted_mask + alibi_mask.unsqueeze(0)
|
426 |
+
else:
|
427 |
+
attention_mask = alibi_mask
|
428 |
|
429 |
hidden_states = inputs_embeds
|
430 |
|
|
|
444 |
if output_hidden_states:
|
445 |
all_hidden_states += (hidden_states,)
|
446 |
|
447 |
+
past_key_value = (
|
448 |
+
past_key_values[idx] if past_key_values is not None else None
|
449 |
+
)
|
450 |
|
451 |
if self.gradient_checkpointing and self.training:
|
452 |
|
|
|
461 |
create_custom_forward(decoder_layer),
|
462 |
hidden_states,
|
463 |
attention_mask,
|
|
|
464 |
None,
|
465 |
)
|
466 |
else:
|
467 |
layer_outputs = decoder_layer(
|
468 |
hidden_states,
|
469 |
attention_mask=attention_mask,
|
|
|
470 |
past_key_value=past_key_value,
|
471 |
output_attentions=output_attentions,
|
472 |
use_cache=use_cache,
|
|
|
488 |
|
489 |
next_cache = next_decoder_cache if use_cache else None
|
490 |
if not return_dict:
|
491 |
+
return tuple(
|
492 |
+
v
|
493 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
494 |
+
if v is not None
|
495 |
+
)
|
496 |
return BaseModelOutputWithPast(
|
497 |
last_hidden_state=hidden_states,
|
498 |
past_key_values=next_cache,
|
|
|
514 |
self.first_flag = True
|
515 |
elif self.first_flag:
|
516 |
self.first_flag = False
|
517 |
+
self.weight = nn.Parameter(nn.functional.normalize(self.weight))
|
518 |
norm_weight = self.weight
|
519 |
else:
|
520 |
norm_weight = self.weight
|
|
|
532 |
finally:
|
533 |
_init_weights = old_init_weights
|
534 |
|
535 |
+
|
536 |
class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
537 |
def __init__(self, config, *model_args, **model_kwargs):
|
538 |
super().__init__(config, *model_args, **model_kwargs)
|
539 |
self.model = BaichuanModel(config)
|
|
|
540 |
self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
|
541 |
+
#if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
|
542 |
if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
|
543 |
try:
|
544 |
from .quantizer import quantize_offline, init_model_weight_int4
|
545 |
except ImportError:
|
546 |
+
raise ImportError(f"Needs quantize_offline to run quantize.")
|
547 |
quantize_offline(self, 4)
|
548 |
# Initialize weights and apply final processing
|
549 |
self.post_init()
|
|
|
581 |
use_safetensors: bool = None,
|
582 |
**kwargs,
|
583 |
):
|
584 |
+
|
585 |
# Load config if we don't provide a configuration
|
586 |
if not isinstance(config, PretrainedConfig):
|
587 |
config_path = config if config is not None else pretrained_model_name_or_path
|
|
|
602 |
)
|
603 |
else:
|
604 |
model_kwargs = kwargs
|
605 |
+
|
606 |
+
if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
|
607 |
+
try:
|
608 |
+
from .quantizer import init_model_weight_int4
|
609 |
+
from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
|
610 |
+
from accelerate.utils import CustomDtype
|
611 |
+
from accelerate.utils import get_balanced_memory
|
612 |
+
except ImportError:
|
613 |
+
raise ImportError(f"Needs import model weight init func to run quantize.")
|
614 |
+
# Instantiate model.
|
615 |
+
init_contexts = [no_init_weights(_enable=True)]
|
616 |
+
init_contexts.append(init_empty_weights())
|
617 |
+
with ContextManagers(init_contexts):
|
618 |
+
model = cls(config)
|
619 |
+
|
620 |
+
model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
|
621 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
622 |
+
model.is_quantized = True
|
623 |
+
|
624 |
+
device_map = kwargs.pop("device_map", None)
|
625 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
626 |
+
if device_map is not None:
|
627 |
+
kwargs = {"no_split_module_classes": model._no_split_modules}
|
628 |
+
target_dtype = CustomDtype.INT4
|
629 |
+
max_memory = get_balanced_memory(
|
630 |
+
model,
|
631 |
+
dtype=target_dtype,
|
632 |
+
low_zero=(device_map == "balanced_low_0"),
|
633 |
+
max_memory=None,
|
634 |
+
**kwargs,
|
635 |
+
)
|
636 |
+
kwargs["max_memory"] = max_memory
|
637 |
+
device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
|
638 |
+
model = init_model_weight_int4(config, model, state_dict)
|
639 |
+
|
640 |
+
# Set model in evaluation mode to deactivate DropOut modules by default
|
641 |
+
model.eval()
|
642 |
+
# If it is a model with generation capabilities, attempt to load the generation config
|
643 |
+
if model.can_generate():
|
644 |
+
try:
|
645 |
+
model.generation_config = GenerationConfig.from_pretrained(
|
646 |
+
pretrained_model_name_or_path,
|
647 |
+
cache_dir=cache_dir,
|
648 |
+
force_download=force_download,
|
649 |
+
resume_download=False,
|
650 |
+
proxies=None,
|
651 |
+
local_files_only=local_files_only,
|
652 |
+
token=token,
|
653 |
+
revision=revision,
|
654 |
+
subfolder="",
|
655 |
+
_from_auto=False,
|
656 |
+
_from_pipeline=None,
|
657 |
+
**kwargs,
|
658 |
+
)
|
659 |
+
except (OSError, TypeError):
|
660 |
+
logger.info(
|
661 |
+
"Generation config file not found, using a generation config created from the model config."
|
662 |
+
)
|
663 |
+
pass
|
664 |
+
|
665 |
+
if device_map is not None:
|
666 |
+
dispatch_model(model, device_map=device_map)
|
667 |
+
|
668 |
+
return model
|
669 |
+
|
670 |
return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
|
671 |
config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
|
672 |
force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
|
673 |
+
use_safetensors=use_safetensors, **kwargs)
|
674 |
|
675 |
def forward(
|
676 |
+
self,
|
677 |
+
input_ids: torch.LongTensor = None,
|
678 |
+
attention_mask: Optional[torch.Tensor] = None,
|
679 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
680 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
681 |
+
labels: Optional[torch.LongTensor] = None,
|
682 |
+
use_cache: Optional[bool] = None,
|
683 |
+
output_attentions: Optional[bool] = False,
|
684 |
+
output_hidden_states: Optional[bool] = False,
|
685 |
+
return_dict: Optional[bool] = True,
|
686 |
+
**kwargs,
|
687 |
) -> Union[Tuple, CausalLMOutputWithPast]:
|
688 |
+
return_dict = (
|
689 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
|
|
|
|
690 |
)
|
|
|
691 |
|
692 |
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
693 |
outputs = self.model(
|
694 |
input_ids=input_ids,
|
695 |
attention_mask=attention_mask,
|
|
|
696 |
past_key_values=past_key_values,
|
697 |
inputs_embeds=inputs_embeds,
|
698 |
use_cache=use_cache,
|
|
|
730 |
attentions=outputs.attentions,
|
731 |
)
|
732 |
|
733 |
+
def quantize(self, bits: int):
|
734 |
+
try:
|
735 |
+
from .quantizer import quantize_online
|
736 |
+
except ImportError:
|
737 |
+
raise ImportError(f"Needs QLinear to run quantize.")
|
738 |
+
return quantize_online(self, bits)
|
739 |
+
|
740 |
def prepare_inputs_for_generation(
|
741 |
+
self,
|
742 |
+
input_ids: torch.LongTensor,
|
743 |
+
past_key_values: Optional[torch.Tensor] = None,
|
744 |
+
attention_mask: Optional[torch.Tensor] = None,
|
745 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
746 |
+
**kwargs,
|
747 |
):
|
748 |
if past_key_values:
|
749 |
input_ids = input_ids[:, -1:]
|
750 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
751 |
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
752 |
if inputs_embeds is not None and past_key_values is None:
|
753 |
model_inputs = {"inputs_embeds": inputs_embeds}
|
|
|
756 |
|
757 |
model_inputs.update(
|
758 |
{
|
|
|
759 |
"past_key_values": past_key_values,
|
760 |
"use_cache": kwargs.get("use_cache"),
|
761 |
"attention_mask": attention_mask,
|
|
|
765 |
|
766 |
@staticmethod
|
767 |
def _reorder_cache(past_key_values, beam_idx):
|
768 |
+
return tuple(
|
769 |
+
tuple(past_state.index_select(0, beam_idx) for past_state in layer_past)
|
770 |
+
for layer_past in past_key_values
|
771 |
+
)
|
772 |
|
773 |
+
def _build_chat_input(
|
774 |
+
self, tokenizer, messages: List[dict], max_new_tokens: int = 0
|
775 |
+
):
|
776 |
+
max_new_tokens = max_new_tokens or self.generation_config.max_new_tokens
|
777 |
+
max_input_tokens = self.config.model_max_length - max_new_tokens
|
778 |
+
max_input_tokens = max(self.config.model_max_length // 2, max_input_tokens)
|
779 |
+
total_input, round_input = [], []
|
780 |
+
for i, message in enumerate(messages[::-1]):
|
781 |
+
content_tokens = tokenizer.encode(message["content"])
|
782 |
+
if message["role"] == "user":
|
783 |
+
round_input = (
|
784 |
+
[self.generation_config.user_token_id]
|
785 |
+
+ content_tokens
|
786 |
+
+ round_input
|
787 |
+
)
|
788 |
+
if (
|
789 |
+
total_input
|
790 |
+
and len(total_input) + len(round_input) > max_input_tokens
|
791 |
+
):
|
792 |
+
break
|
793 |
+
else:
|
794 |
+
total_input = round_input + total_input
|
795 |
+
if len(total_input) >= max_input_tokens:
|
796 |
+
break
|
797 |
+
else:
|
798 |
+
round_input = []
|
799 |
+
elif message["role"] == "assistant":
|
800 |
+
round_input = (
|
801 |
+
[self.generation_config.assistant_token_id]
|
802 |
+
+ content_tokens
|
803 |
+
+ [self.generation_config.eos_token_id]
|
804 |
+
+ round_input
|
805 |
+
)
|
806 |
+
else:
|
807 |
+
raise ValueError(f"message role not supported yet: {message['role']}")
|
808 |
+
total_input = total_input[-max_input_tokens:] # truncate left
|
809 |
+
total_input.append(self.generation_config.assistant_token_id)
|
810 |
+
total_input = torch.LongTensor([total_input]).to(self.device)
|
811 |
+
return total_input
|
812 |
|
813 |
def chat(self, tokenizer, messages: List[dict], stream=False,
|
814 |
generation_config: Optional[GenerationConfig]=None):
|
815 |
generation_config = generation_config or self.generation_config
|
816 |
input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
|
817 |
+
if stream:
|
818 |
+
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
819 |
+
Thread(target=self.generate, kwargs=dict(
|
820 |
+
inputs=input_ids, streamer=streamer,
|
821 |
+
generation_config=generation_config,
|
822 |
+
)).start()
|
823 |
+
return streamer
|
824 |
+
else:
|
825 |
+
outputs = self.generate(input_ids, generation_config=generation_config)
|
826 |
+
response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
|
827 |
+
return response
|
828 |
+
|
829 |
+
def HuatuoChat(self, tokenizer, messages: List[dict], stream=False,
|
830 |
+
generation_config: Optional[GenerationConfig]=None):
|
831 |
+
generation_config = generation_config or self.generation_config
|
832 |
+
input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
|
833 |
if stream:
|
834 |
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
835 |
Thread(target=self.generate, kwargs=dict(
|