larryvrh commited on
Commit
0aa029b
1 Parent(s): 5bd07c6

Upload 2 files

Browse files
Files changed (2) hide show
  1. baichuan_reformat.py +24 -0
  2. modeling_baichuan.py +819 -0
baichuan_reformat.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ from collections import OrderedDict
3
+ import torch
4
+
5
+ model_path = 'model_path'
6
+ out_path = 'out_path'
7
+
8
+ model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, torch_dtype=torch.bfloat16)
9
+
10
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, trust_remote_code=True)
11
+
12
+ new_dict = OrderedDict()
13
+ for k,v in model.state_dict().items():
14
+ if not 'self_attn.W_pack' in k:
15
+ new_dict[k] = v
16
+ continue
17
+ name_base = k[:k.find('W_pack.weight')]
18
+ q,k,v = [v[model.config.hidden_size*i:model.config.hidden_size*(i+1),:] for i in range(3)]
19
+ new_dict[name_base + 'q_proj.weight'] = q
20
+ new_dict[name_base + 'k_proj.weight'] = k
21
+ new_dict[name_base + 'v_proj.weight'] = v
22
+
23
+ model.save_pretrained(out_path, state_dict=new_dict)
24
+ tokenizer.save_pretrained(out_path)
modeling_baichuan.py ADDED
@@ -0,0 +1,819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
27
+ from xformers import ops as xops
28
+ except ImportError:
29
+ xops = None
30
+ logger.warning(
31
+ "Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers."
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.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
124
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
125
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
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
+ query_states = (
148
+ self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
149
+ )
150
+ key_states = (
151
+ self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
152
+ )
153
+ value_states = (
154
+ self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
155
+ )
156
+
157
+ kv_seq_len = key_states.shape[-2]
158
+ if past_key_value is not None:
159
+ kv_seq_len += past_key_value[0].shape[-2]
160
+
161
+ if past_key_value is not None:
162
+ # reuse k, v, self_attention
163
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
164
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
165
+
166
+ past_key_value = (key_states, value_states) if use_cache else None
167
+ if xops is not None and self.training:
168
+ attn_weights = None
169
+ # query_states = query_states.transpose(1, 2)
170
+ # key_states = key_states.transpose(1, 2)
171
+ # value_states = value_states.transpose(1, 2)
172
+ # attn_output = xops.memory_efficient_attention(
173
+ # query_states, key_states, value_states, attn_bias=attention_mask
174
+ # )
175
+ with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
176
+ attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
177
+ attn_output = attn_output.transpose(1, 2)
178
+ else:
179
+ attn_weights = torch.matmul(
180
+ query_states, key_states.transpose(2, 3)
181
+ ) / math.sqrt(self.head_dim)
182
+
183
+ if attention_mask is not None:
184
+ if q_len == 1: # inference with cache
185
+ if len(attention_mask.size()) == 4:
186
+ attention_mask = attention_mask[:, :, -1:, :]
187
+ else:
188
+ attention_mask = attention_mask[:, -1:, :]
189
+ attn_weights = attn_weights + attention_mask
190
+ attn_weights = torch.max(
191
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
192
+ )
193
+
194
+ attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
195
+ attn_output = torch.matmul(attn_weights, value_states)
196
+
197
+ attn_output = attn_output.transpose(1, 2)
198
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
199
+ attn_output = self.o_proj(attn_output)
200
+
201
+ if not output_attentions:
202
+ attn_weights = None
203
+
204
+ return attn_output, attn_weights, past_key_value
205
+
206
+
207
+ class BaichuanLayer(torch.nn.Module):
208
+ def __init__(self, config: BaichuanConfig):
209
+ super().__init__()
210
+ self.hidden_size = config.hidden_size
211
+ self.self_attn = BaichuanAttention(config=config)
212
+ self.mlp = MLP(
213
+ hidden_size=self.hidden_size,
214
+ intermediate_size=config.intermediate_size,
215
+ hidden_act=config.hidden_act,
216
+ )
217
+ self.input_layernorm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
218
+ self.post_attention_layernorm = RMSNorm(
219
+ config.hidden_size, epsilon=config.rms_norm_eps
220
+ )
221
+
222
+ def forward(
223
+ self,
224
+ hidden_states: torch.Tensor,
225
+ attention_mask: Optional[torch.Tensor] = None,
226
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
227
+ output_attentions: Optional[bool] = False,
228
+ use_cache: Optional[bool] = False,
229
+ ) -> Tuple[
230
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
231
+ ]:
232
+ residual = hidden_states
233
+
234
+ hidden_states = self.input_layernorm(hidden_states)
235
+
236
+ # Self Attention
237
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
238
+ hidden_states=hidden_states,
239
+ attention_mask=attention_mask,
240
+ past_key_value=past_key_value,
241
+ output_attentions=output_attentions,
242
+ use_cache=use_cache,
243
+ )
244
+ hidden_states = residual + hidden_states
245
+
246
+ # Fully Connected
247
+ residual = hidden_states
248
+ hidden_states = self.post_attention_layernorm(hidden_states)
249
+ hidden_states = self.mlp(hidden_states)
250
+ hidden_states = residual + hidden_states
251
+
252
+ outputs = (hidden_states,)
253
+
254
+ if use_cache:
255
+ outputs += (present_key_value,)
256
+
257
+ return outputs
258
+
259
+
260
+ class BaichuanPreTrainedModel(PreTrainedModel):
261
+ config_class = BaichuanConfig
262
+ base_model_prefix = "model"
263
+ supports_gradient_checkpointing = True
264
+ _no_split_modules = ["BaichuanLayer"]
265
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
266
+
267
+ def _init_weights(self, module):
268
+ std = self.config.initializer_range
269
+ if isinstance(module, torch.nn.Linear):
270
+ module.weight.data.normal_(mean=0.0, std=std)
271
+ if module.bias is not None:
272
+ module.bias.data.zero_()
273
+ elif isinstance(module, torch.nn.Embedding):
274
+ module.weight.data.normal_(mean=0.0, std=std)
275
+ if module.padding_idx is not None:
276
+ module.weight.data[module.padding_idx].zero_()
277
+
278
+ def _set_gradient_checkpointing(self, module, value=False):
279
+ if isinstance(module, BaichuanModel):
280
+ module.gradient_checkpointing = value
281
+
282
+
283
+ class BaichuanModel(BaichuanPreTrainedModel):
284
+ def __init__(self, config: BaichuanConfig):
285
+ super().__init__(config)
286
+ self.padding_idx = config.pad_token_id
287
+ self.vocab_size = config.vocab_size
288
+ self.n_head = config.num_attention_heads
289
+ self.embed_tokens = torch.nn.Embedding(
290
+ config.vocab_size, config.hidden_size, self.padding_idx
291
+ )
292
+ self.layers = torch.nn.ModuleList(
293
+ [BaichuanLayer(config) for _ in range(config.num_hidden_layers)]
294
+ )
295
+ self.norm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
296
+
297
+ self.gradient_checkpointing = config.gradient_checkpointing
298
+ self.post_init()
299
+ self.max_cache_pos = config.model_max_length
300
+ self.first_run = True
301
+ self.alibi_mask = None
302
+
303
+ def get_input_embeddings(self):
304
+ return self.embed_tokens
305
+
306
+ def set_input_embeddings(self, value):
307
+ self.embed_tokens = value
308
+
309
+ def get_alibi_mask(self, tensor, seq_length_with_past):
310
+ if self.training:
311
+ slopes = torch.Tensor(_get_interleave(self.n_head))
312
+ position_point = (
313
+ torch.arange(seq_length_with_past) - seq_length_with_past + 1
314
+ )
315
+ position_point = (
316
+ position_point.unsqueeze(0)
317
+ .unsqueeze(0)
318
+ .expand(self.n_head, seq_length_with_past, -1)
319
+ )
320
+ diag = torch.diag(position_point[0])
321
+ position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(
322
+ -1, -2
323
+ )
324
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
325
+ mask = _buffered_future_mask(
326
+ tensor, seq_length_with_past, alibi, self.n_head
327
+ )
328
+ else:
329
+ if self.first_run:
330
+ self.first_run = False
331
+ self.register_buffer(
332
+ "future_mask",
333
+ _gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
334
+ tensor
335
+ ),
336
+ persistent=False,
337
+ )
338
+ if seq_length_with_past > self.max_cache_pos:
339
+ self.max_cache_pos = seq_length_with_past
340
+ self.register_buffer(
341
+ "future_mask",
342
+ _gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
343
+ tensor
344
+ ),
345
+ persistent=False,
346
+ )
347
+ mask = self.future_mask[
348
+ : self.n_head, :seq_length_with_past, :seq_length_with_past
349
+ ]
350
+ return mask
351
+
352
+ def forward(
353
+ self,
354
+ input_ids: torch.LongTensor = None,
355
+ attention_mask: Optional[torch.Tensor] = None,
356
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
357
+ inputs_embeds: Optional[torch.FloatTensor] = None,
358
+ use_cache: Optional[bool] = False,
359
+ output_attentions: Optional[bool] = False,
360
+ output_hidden_states: Optional[bool] = False,
361
+ return_dict: Optional[bool] = True,
362
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
363
+ if input_ids is not None and inputs_embeds is not None:
364
+ raise ValueError(
365
+ "You cannot provide both input_ids and inputs_embeds simultaneously"
366
+ )
367
+ elif input_ids is not None:
368
+ batch_size, seq_length = input_ids.shape
369
+ elif inputs_embeds is not None:
370
+ batch_size, seq_length, _ = inputs_embeds.shape
371
+ else:
372
+ raise ValueError("You need to provide input_ids or inputs_embeds")
373
+
374
+ return_dict = (
375
+ return_dict if return_dict is not None else self.config.use_return_dict
376
+ )
377
+
378
+ seq_length_with_past = seq_length
379
+
380
+ if past_key_values is not None:
381
+ past_key_values_length = past_key_values[0][0].shape[2]
382
+ seq_length_with_past = seq_length_with_past + past_key_values_length
383
+
384
+ if inputs_embeds is None:
385
+ inputs_embeds = self.embed_tokens(input_ids)
386
+
387
+ if self.training:
388
+ if (
389
+ self.alibi_mask is None
390
+ or self.alibi_mask.shape[-1] != seq_length_with_past
391
+ ):
392
+ self.alibi_mask = self.get_alibi_mask(
393
+ inputs_embeds, seq_length_with_past
394
+ )
395
+ alibi_mask = self.alibi_mask
396
+ else:
397
+ alibi_mask = self.get_alibi_mask(inputs_embeds, seq_length_with_past)
398
+
399
+ if attention_mask is not None:
400
+ if len(attention_mask.shape) == 2:
401
+ expanded_mask = attention_mask.to(alibi_mask.dtype)
402
+ expanded_mask = torch.tril(
403
+ torch.gt(expanded_mask[:, :, None] * expanded_mask[:, None, :], 0)
404
+ ) * torch.eq(expanded_mask[:, :, None] - expanded_mask[:, None, :], 0)
405
+ else:
406
+ expanded_mask = attention_mask
407
+ bsz = inputs_embeds.size(0)
408
+ src_len, tgt_len = alibi_mask.size()[-2:]
409
+ expanded_mask = (
410
+ expanded_mask.unsqueeze(1)
411
+ .expand(bsz, 1, src_len, tgt_len)
412
+ .to(alibi_mask.dtype)
413
+ )
414
+ inverted_mask = 1.0 - expanded_mask
415
+ inverted_mask = inverted_mask.masked_fill(
416
+ inverted_mask.to(torch.bool), torch.finfo(alibi_mask.dtype).min
417
+ )
418
+ attention_mask = inverted_mask + alibi_mask.unsqueeze(0)
419
+ else:
420
+ attention_mask = alibi_mask
421
+
422
+ hidden_states = inputs_embeds
423
+
424
+ if self.gradient_checkpointing and self.training:
425
+ if use_cache:
426
+ logger.warning_once(
427
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
428
+ )
429
+ use_cache = False
430
+
431
+ # decoder layers
432
+ all_hidden_states = () if output_hidden_states else None
433
+ all_self_attns = () if output_attentions else None
434
+ next_decoder_cache = () if use_cache else None
435
+
436
+ for idx, decoder_layer in enumerate(self.layers):
437
+ if output_hidden_states:
438
+ all_hidden_states += (hidden_states,)
439
+
440
+ past_key_value = (
441
+ past_key_values[idx] if past_key_values is not None else None
442
+ )
443
+
444
+ if self.gradient_checkpointing and self.training:
445
+
446
+ def create_custom_forward(module):
447
+ def custom_forward(*inputs):
448
+ # None for past_key_value
449
+ return module(*inputs, output_attentions, None)
450
+
451
+ return custom_forward
452
+
453
+ layer_outputs = torch.utils.checkpoint.checkpoint(
454
+ create_custom_forward(decoder_layer),
455
+ hidden_states,
456
+ attention_mask,
457
+ None,
458
+ )
459
+ else:
460
+ layer_outputs = decoder_layer(
461
+ hidden_states,
462
+ attention_mask=attention_mask,
463
+ past_key_value=past_key_value,
464
+ output_attentions=output_attentions,
465
+ use_cache=use_cache,
466
+ )
467
+
468
+ hidden_states = layer_outputs[0]
469
+
470
+ if use_cache:
471
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
472
+
473
+ if output_attentions:
474
+ all_self_attns += (layer_outputs[1],)
475
+
476
+ hidden_states = self.norm(hidden_states)
477
+
478
+ # add hidden states from the last decoder layer
479
+ if output_hidden_states:
480
+ all_hidden_states += (hidden_states,)
481
+
482
+ next_cache = next_decoder_cache if use_cache else None
483
+ if not return_dict:
484
+ return tuple(
485
+ v
486
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
487
+ if v is not None
488
+ )
489
+ return BaseModelOutputWithPast(
490
+ last_hidden_state=hidden_states,
491
+ past_key_values=next_cache,
492
+ hidden_states=all_hidden_states,
493
+ attentions=all_self_attns,
494
+ )
495
+
496
+
497
+ class NormHead(nn.Module):
498
+ def __init__(self, hidden_size, vocab_size, bias=False):
499
+ super().__init__()
500
+ self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
501
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
502
+ self.first_flag = True
503
+
504
+ def forward(self, hidden_states):
505
+ if self.training:
506
+ norm_weight = nn.functional.normalize(self.weight)
507
+ elif self.first_flag:
508
+ self.first_flag = False
509
+ self.weight = nn.Parameter(nn.functional.normalize(self.weight))
510
+ norm_weight = self.weight
511
+ else:
512
+ norm_weight = self.weight
513
+ return nn.functional.linear(hidden_states, norm_weight)
514
+
515
+ _init_weights = True
516
+ @contextmanager
517
+ def no_init_weights(_enable=True):
518
+ global _init_weights
519
+ old_init_weights = _init_weights
520
+ if _enable:
521
+ _init_weights = False
522
+ try:
523
+ yield
524
+ finally:
525
+ _init_weights = old_init_weights
526
+
527
+
528
+ class BaichuanForCausalLM(BaichuanPreTrainedModel):
529
+ def __init__(self, config, *model_args, **model_kwargs):
530
+ super().__init__(config, *model_args, **model_kwargs)
531
+ self.model = BaichuanModel(config)
532
+ self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
533
+ #if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
534
+ if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
535
+ try:
536
+ from .quantizer import quantize_offline, init_model_weight_int4
537
+ except ImportError:
538
+ raise ImportError(f"Needs quantize_offline to run quantize.")
539
+ quantize_offline(self, 4)
540
+ # Initialize weights and apply final processing
541
+ self.post_init()
542
+
543
+ def get_input_embeddings(self):
544
+ return self.model.embed_tokens
545
+
546
+ def set_input_embeddings(self, value):
547
+ self.model.embed_tokens = value
548
+
549
+ def get_output_embeddings(self):
550
+ return self.lm_head
551
+
552
+ def set_output_embeddings(self, new_embeddings):
553
+ self.lm_head = new_embeddings
554
+
555
+ def set_decoder(self, decoder):
556
+ self.model = decoder
557
+
558
+ def get_decoder(self):
559
+ return self.model
560
+
561
+ @classmethod
562
+ def from_pretrained(
563
+ cls,
564
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
565
+ *model_args,
566
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
567
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
568
+ ignore_mismatched_sizes: bool = False,
569
+ force_download: bool = False,
570
+ local_files_only: bool = False,
571
+ token: Optional[Union[str, bool]] = None,
572
+ revision: str = "main",
573
+ use_safetensors: bool = None,
574
+ **kwargs,
575
+ ):
576
+
577
+ # Load config if we don't provide a configuration
578
+ if not isinstance(config, PretrainedConfig):
579
+ config_path = config if config is not None else pretrained_model_name_or_path
580
+ config, model_kwargs = cls.config_class.from_pretrained(
581
+ config_path,
582
+ cache_dir=cache_dir,
583
+ return_unused_kwargs=True,
584
+ force_download=force_download,
585
+ resume_download=False,
586
+ proxies=None,
587
+ local_files_only=local_files_only,
588
+ token=token,
589
+ revision=revision,
590
+ subfolder="",
591
+ _from_auto=False,
592
+ _from_pipeline=None,
593
+ **kwargs,
594
+ )
595
+ else:
596
+ model_kwargs = kwargs
597
+
598
+ if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
599
+ try:
600
+ from .quantizer import init_model_weight_int4
601
+ from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
602
+ from accelerate.utils import CustomDtype
603
+ from accelerate.utils import get_balanced_memory
604
+ except ImportError:
605
+ raise ImportError(f"Needs import model weight init func to run quantize.")
606
+ # Instantiate model.
607
+ init_contexts = [no_init_weights(_enable=True)]
608
+ init_contexts.append(init_empty_weights())
609
+ with ContextManagers(init_contexts):
610
+ model = cls(config)
611
+
612
+ model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
613
+ state_dict = torch.load(model_file, map_location="cpu")
614
+ model.is_quantized = True
615
+
616
+ device_map = kwargs.pop("device_map", None)
617
+ torch_dtype = kwargs.pop("torch_dtype", None)
618
+ if device_map is not None:
619
+ kwargs = {"no_split_module_classes": model._no_split_modules}
620
+ target_dtype = CustomDtype.INT4
621
+ max_memory = get_balanced_memory(
622
+ model,
623
+ dtype=target_dtype,
624
+ low_zero=(device_map == "balanced_low_0"),
625
+ max_memory=None,
626
+ **kwargs,
627
+ )
628
+ kwargs["max_memory"] = max_memory
629
+ device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
630
+ model = init_model_weight_int4(config, model, state_dict)
631
+
632
+ # Set model in evaluation mode to deactivate DropOut modules by default
633
+ model.eval()
634
+ # If it is a model with generation capabilities, attempt to load the generation config
635
+ if model.can_generate():
636
+ try:
637
+ model.generation_config = GenerationConfig.from_pretrained(
638
+ pretrained_model_name_or_path,
639
+ cache_dir=cache_dir,
640
+ force_download=force_download,
641
+ resume_download=False,
642
+ proxies=None,
643
+ local_files_only=local_files_only,
644
+ token=token,
645
+ revision=revision,
646
+ subfolder="",
647
+ _from_auto=False,
648
+ _from_pipeline=None,
649
+ **kwargs,
650
+ )
651
+ except (OSError, TypeError):
652
+ logger.info(
653
+ "Generation config file not found, using a generation config created from the model config."
654
+ )
655
+ pass
656
+
657
+ if device_map is not None:
658
+ dispatch_model(model, device_map=device_map)
659
+
660
+ return model
661
+
662
+ return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
663
+ config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
664
+ force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
665
+ use_safetensors=use_safetensors, **kwargs)
666
+
667
+ def forward(
668
+ self,
669
+ input_ids: torch.LongTensor = None,
670
+ attention_mask: Optional[torch.Tensor] = None,
671
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
672
+ inputs_embeds: Optional[torch.FloatTensor] = None,
673
+ labels: Optional[torch.LongTensor] = None,
674
+ use_cache: Optional[bool] = None,
675
+ output_attentions: Optional[bool] = False,
676
+ output_hidden_states: Optional[bool] = False,
677
+ return_dict: Optional[bool] = True,
678
+ **kwargs,
679
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
680
+ return_dict = (
681
+ return_dict if return_dict is not None else self.config.use_return_dict
682
+ )
683
+
684
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
685
+ outputs = self.model(
686
+ input_ids=input_ids,
687
+ attention_mask=attention_mask,
688
+ past_key_values=past_key_values,
689
+ inputs_embeds=inputs_embeds,
690
+ use_cache=use_cache,
691
+ output_attentions=output_attentions,
692
+ output_hidden_states=output_hidden_states,
693
+ return_dict=return_dict,
694
+ )
695
+
696
+ hidden_states = outputs[0]
697
+ logits = self.lm_head(hidden_states)
698
+ loss = None
699
+ if labels is not None:
700
+ # Shift so that tokens < n predict n
701
+ shift_logits = logits[..., :-1, :].contiguous()
702
+ shift_labels = labels[..., 1:].contiguous()
703
+ # Flatten the tokens
704
+ loss_fct = CrossEntropyLoss()
705
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
706
+ shift_labels = shift_labels.view(-1)
707
+ softmax_normalizer = shift_logits.max(-1).values ** 2
708
+ z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
709
+ # Enable model parallelism
710
+ shift_labels = shift_labels.to(shift_logits.device)
711
+ loss = loss_fct(shift_logits, shift_labels) + z_loss
712
+
713
+ if not return_dict:
714
+ output = (logits,) + outputs[1:]
715
+ return (loss,) + output if loss is not None else output
716
+
717
+ return CausalLMOutputWithPast(
718
+ loss=loss,
719
+ logits=logits,
720
+ past_key_values=outputs.past_key_values,
721
+ hidden_states=outputs.hidden_states,
722
+ attentions=outputs.attentions,
723
+ )
724
+
725
+ def quantize(self, bits: int):
726
+ try:
727
+ from .quantizer import quantize_online
728
+ except ImportError:
729
+ raise ImportError(f"Needs QLinear to run quantize.")
730
+ return quantize_online(self, bits)
731
+
732
+ def prepare_inputs_for_generation(
733
+ self,
734
+ input_ids: torch.LongTensor,
735
+ past_key_values: Optional[torch.Tensor] = None,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ inputs_embeds: Optional[torch.Tensor] = None,
738
+ **kwargs,
739
+ ):
740
+ if past_key_values:
741
+ input_ids = input_ids[:, -1:]
742
+
743
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
744
+ if inputs_embeds is not None and past_key_values is None:
745
+ model_inputs = {"inputs_embeds": inputs_embeds}
746
+ else:
747
+ model_inputs = {"input_ids": input_ids}
748
+
749
+ model_inputs.update(
750
+ {
751
+ "past_key_values": past_key_values,
752
+ "use_cache": kwargs.get("use_cache"),
753
+ "attention_mask": attention_mask,
754
+ }
755
+ )
756
+ return model_inputs
757
+
758
+ @staticmethod
759
+ def _reorder_cache(past_key_values, beam_idx):
760
+ return tuple(
761
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past)
762
+ for layer_past in past_key_values
763
+ )
764
+
765
+ def _build_chat_input(
766
+ self, tokenizer, messages: List[dict], max_new_tokens: int = 0
767
+ ):
768
+ max_new_tokens = max_new_tokens or self.generation_config.max_new_tokens
769
+ max_input_tokens = self.config.model_max_length - max_new_tokens
770
+ max_input_tokens = max(self.config.model_max_length // 2, max_input_tokens)
771
+ total_input, round_input = [], []
772
+ for i, message in enumerate(messages[::-1]):
773
+ content_tokens = tokenizer.encode(message["content"])
774
+ if message["role"] == "user":
775
+ round_input = (
776
+ [self.generation_config.user_token_id]
777
+ + content_tokens
778
+ + round_input
779
+ )
780
+ if (
781
+ total_input
782
+ and len(total_input) + len(round_input) > max_input_tokens
783
+ ):
784
+ break
785
+ else:
786
+ total_input = round_input + total_input
787
+ if len(total_input) >= max_input_tokens:
788
+ break
789
+ else:
790
+ round_input = []
791
+ elif message["role"] == "assistant":
792
+ round_input = (
793
+ [self.generation_config.assistant_token_id]
794
+ + content_tokens
795
+ + [self.generation_config.eos_token_id]
796
+ + round_input
797
+ )
798
+ else:
799
+ raise ValueError(f"message role not supported yet: {message['role']}")
800
+ total_input = total_input[-max_input_tokens:] # truncate left
801
+ total_input.append(self.generation_config.assistant_token_id)
802
+ total_input = torch.LongTensor([total_input]).to(self.device)
803
+ return total_input
804
+
805
+ def chat(self, tokenizer, messages: List[dict], stream=False,
806
+ generation_config: Optional[GenerationConfig]=None):
807
+ generation_config = generation_config or self.generation_config
808
+ input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
809
+ if stream:
810
+ streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
811
+ Thread(target=self.generate, kwargs=dict(
812
+ inputs=input_ids, streamer=streamer,
813
+ generation_config=generation_config,
814
+ )).start()
815
+ return streamer
816
+ else:
817
+ outputs = self.generate(input_ids, generation_config=generation_config)
818
+ response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
819
+ return response