TheBloke commited on
Commit
36c11fc
1 Parent(s): 46aa8e7

Initial GPTQ model commit

Browse files
Files changed (1) hide show
  1. modeling_baichuan.py +826 -0
modeling_baichuan.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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
170
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
171
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
172
+
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
+
208
+ if not output_attentions:
209
+ attn_weights = None
210
+
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)
242
+
243
+ # Self Attention
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,
250
+ )
251
+ hidden_states = residual + hidden_states
252
+
253
+ # Fully Connected
254
+ residual = hidden_states
255
+ hidden_states = self.post_attention_layernorm(hidden_states)
256
+ hidden_states = self.mlp(hidden_states)
257
+ hidden_states = residual + hidden_states
258
+
259
+ outputs = (hidden_states,)
260
+
261
+ if use_cache:
262
+ outputs += (present_key_value,)
263
+
264
+ return outputs
265
+
266
+
267
+ class BaichuanPreTrainedModel(PreTrainedModel):
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_()
284
+
285
+ def _set_gradient_checkpointing(self, module, value=False):
286
+ if isinstance(module, BaichuanModel):
287
+ module.gradient_checkpointing = value
288
+
289
+
290
+ class BaichuanModel(BaichuanPreTrainedModel):
291
+ def __init__(self, config: BaichuanConfig):
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
312
+
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
+
431
+ if self.gradient_checkpointing and self.training:
432
+ if use_cache:
433
+ logger.warning_once(
434
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
435
+ )
436
+ use_cache = False
437
+
438
+ # decoder layers
439
+ all_hidden_states = () if output_hidden_states else None
440
+ all_self_attns = () if output_attentions else None
441
+ next_decoder_cache = () if use_cache else None
442
+
443
+ for idx, decoder_layer in enumerate(self.layers):
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
+
453
+ def create_custom_forward(module):
454
+ def custom_forward(*inputs):
455
+ # None for past_key_value
456
+ return module(*inputs, output_attentions, None)
457
+
458
+ return custom_forward
459
+
460
+ layer_outputs = torch.utils.checkpoint.checkpoint(
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,
473
+ )
474
+
475
+ hidden_states = layer_outputs[0]
476
+
477
+ if use_cache:
478
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
479
+
480
+ if output_attentions:
481
+ all_self_attns += (layer_outputs[1],)
482
+
483
+ hidden_states = self.norm(hidden_states)
484
+
485
+ # add hidden states from the last decoder layer
486
+ if output_hidden_states:
487
+ all_hidden_states += (hidden_states,)
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,
499
+ hidden_states=all_hidden_states,
500
+ attentions=all_self_attns,
501
+ )
502
+
503
+
504
+ class NormHead(nn.Module):
505
+ def __init__(self, hidden_size, vocab_size, bias=False):
506
+ super().__init__()
507
+ self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
508
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
509
+ self.first_flag = True
510
+
511
+ def forward(self, hidden_states):
512
+ if self.training:
513
+ norm_weight = nn.functional.normalize(self.weight)
514
+ elif self.first_flag:
515
+ self.first_flag = False
516
+ self.weight = nn.Parameter(nn.functional.normalize(self.weight))
517
+ norm_weight = self.weight
518
+ else:
519
+ norm_weight = self.weight
520
+ return nn.functional.linear(hidden_states, norm_weight)
521
+
522
+ _init_weights = True
523
+ @contextmanager
524
+ def no_init_weights(_enable=True):
525
+ global _init_weights
526
+ old_init_weights = _init_weights
527
+ if _enable:
528
+ _init_weights = False
529
+ try:
530
+ yield
531
+ finally:
532
+ _init_weights = old_init_weights
533
+
534
+
535
+ class BaichuanForCausalLM(BaichuanPreTrainedModel):
536
+ def __init__(self, config, *model_args, **model_kwargs):
537
+ super().__init__(config, *model_args, **model_kwargs)
538
+ self.model = BaichuanModel(config)
539
+ self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
540
+ #if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
541
+ if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
542
+ try:
543
+ from .quantizer import quantize_offline, init_model_weight_int4
544
+ except ImportError:
545
+ raise ImportError(f"Needs quantize_offline to run quantize.")
546
+ quantize_offline(self, 4)
547
+ # Initialize weights and apply final processing
548
+ self.post_init()
549
+
550
+ def get_input_embeddings(self):
551
+ return self.model.embed_tokens
552
+
553
+ def set_input_embeddings(self, value):
554
+ self.model.embed_tokens = value
555
+
556
+ def get_output_embeddings(self):
557
+ return self.lm_head
558
+
559
+ def set_output_embeddings(self, new_embeddings):
560
+ self.lm_head = new_embeddings
561
+
562
+ def set_decoder(self, decoder):
563
+ self.model = decoder
564
+
565
+ def get_decoder(self):
566
+ return self.model
567
+
568
+ @classmethod
569
+ def from_pretrained(
570
+ cls,
571
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
572
+ *model_args,
573
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
574
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
575
+ ignore_mismatched_sizes: bool = False,
576
+ force_download: bool = False,
577
+ local_files_only: bool = False,
578
+ token: Optional[Union[str, bool]] = None,
579
+ revision: str = "main",
580
+ use_safetensors: bool = None,
581
+ **kwargs,
582
+ ):
583
+
584
+ # Load config if we don't provide a configuration
585
+ if not isinstance(config, PretrainedConfig):
586
+ config_path = config if config is not None else pretrained_model_name_or_path
587
+ config, model_kwargs = cls.config_class.from_pretrained(
588
+ config_path,
589
+ cache_dir=cache_dir,
590
+ return_unused_kwargs=True,
591
+ force_download=force_download,
592
+ resume_download=False,
593
+ proxies=None,
594
+ local_files_only=local_files_only,
595
+ token=token,
596
+ revision=revision,
597
+ subfolder="",
598
+ _from_auto=False,
599
+ _from_pipeline=None,
600
+ **kwargs,
601
+ )
602
+ else:
603
+ model_kwargs = kwargs
604
+
605
+ if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
606
+ try:
607
+ from .quantizer import init_model_weight_int4
608
+ from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
609
+ from accelerate.utils import CustomDtype
610
+ from accelerate.utils import get_balanced_memory
611
+ except ImportError:
612
+ raise ImportError(f"Needs import model weight init func to run quantize.")
613
+ # Instantiate model.
614
+ init_contexts = [no_init_weights(_enable=True)]
615
+ init_contexts.append(init_empty_weights())
616
+ with ContextManagers(init_contexts):
617
+ model = cls(config)
618
+
619
+ model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
620
+ state_dict = torch.load(model_file, map_location="cpu")
621
+ model.is_quantized = True
622
+
623
+ device_map = kwargs.pop("device_map", None)
624
+ torch_dtype = kwargs.pop("torch_dtype", None)
625
+ if device_map is not None:
626
+ kwargs = {"no_split_module_classes": model._no_split_modules}
627
+ target_dtype = CustomDtype.INT4
628
+ max_memory = get_balanced_memory(
629
+ model,
630
+ dtype=target_dtype,
631
+ low_zero=(device_map == "balanced_low_0"),
632
+ max_memory=None,
633
+ **kwargs,
634
+ )
635
+ kwargs["max_memory"] = max_memory
636
+ device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
637
+ model = init_model_weight_int4(config, model, state_dict)
638
+
639
+ # Set model in evaluation mode to deactivate DropOut modules by default
640
+ model.eval()
641
+ # If it is a model with generation capabilities, attempt to load the generation config
642
+ if model.can_generate():
643
+ try:
644
+ model.generation_config = GenerationConfig.from_pretrained(
645
+ pretrained_model_name_or_path,
646
+ cache_dir=cache_dir,
647
+ force_download=force_download,
648
+ resume_download=False,
649
+ proxies=None,
650
+ local_files_only=local_files_only,
651
+ token=token,
652
+ revision=revision,
653
+ subfolder="",
654
+ _from_auto=False,
655
+ _from_pipeline=None,
656
+ **kwargs,
657
+ )
658
+ except (OSError, TypeError):
659
+ logger.info(
660
+ "Generation config file not found, using a generation config created from the model config."
661
+ )
662
+ pass
663
+
664
+ if device_map is not None:
665
+ dispatch_model(model, device_map=device_map)
666
+
667
+ return model
668
+
669
+ return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
670
+ config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
671
+ force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
672
+ use_safetensors=use_safetensors, **kwargs)
673
+
674
+ def forward(
675
+ self,
676
+ input_ids: torch.LongTensor = None,
677
+ attention_mask: Optional[torch.Tensor] = None,
678
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
679
+ inputs_embeds: Optional[torch.FloatTensor] = None,
680
+ labels: Optional[torch.LongTensor] = None,
681
+ use_cache: Optional[bool] = None,
682
+ output_attentions: Optional[bool] = False,
683
+ output_hidden_states: Optional[bool] = False,
684
+ return_dict: Optional[bool] = True,
685
+ **kwargs,
686
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
687
+ return_dict = (
688
+ return_dict if return_dict is not None else self.config.use_return_dict
689
+ )
690
+
691
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
692
+ outputs = self.model(
693
+ input_ids=input_ids,
694
+ attention_mask=attention_mask,
695
+ past_key_values=past_key_values,
696
+ inputs_embeds=inputs_embeds,
697
+ use_cache=use_cache,
698
+ output_attentions=output_attentions,
699
+ output_hidden_states=output_hidden_states,
700
+ return_dict=return_dict,
701
+ )
702
+
703
+ hidden_states = outputs[0]
704
+ logits = self.lm_head(hidden_states)
705
+ loss = None
706
+ if labels is not None:
707
+ # Shift so that tokens < n predict n
708
+ shift_logits = logits[..., :-1, :].contiguous()
709
+ shift_labels = labels[..., 1:].contiguous()
710
+ # Flatten the tokens
711
+ loss_fct = CrossEntropyLoss()
712
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
713
+ shift_labels = shift_labels.view(-1)
714
+ softmax_normalizer = shift_logits.max(-1).values ** 2
715
+ z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
716
+ # Enable model parallelism
717
+ shift_labels = shift_labels.to(shift_logits.device)
718
+ loss = loss_fct(shift_logits, shift_labels) + z_loss
719
+
720
+ if not return_dict:
721
+ output = (logits,) + outputs[1:]
722
+ return (loss,) + output if loss is not None else output
723
+
724
+ return CausalLMOutputWithPast(
725
+ loss=loss,
726
+ logits=logits,
727
+ past_key_values=outputs.past_key_values,
728
+ hidden_states=outputs.hidden_states,
729
+ attentions=outputs.attentions,
730
+ )
731
+
732
+ def quantize(self, bits: int):
733
+ try:
734
+ from .quantizer import quantize_online
735
+ except ImportError:
736
+ raise ImportError(f"Needs QLinear to run quantize.")
737
+ return quantize_online(self, bits)
738
+
739
+ def prepare_inputs_for_generation(
740
+ self,
741
+ input_ids: torch.LongTensor,
742
+ past_key_values: Optional[torch.Tensor] = None,
743
+ attention_mask: Optional[torch.Tensor] = None,
744
+ inputs_embeds: Optional[torch.Tensor] = None,
745
+ **kwargs,
746
+ ):
747
+ if past_key_values:
748
+ input_ids = input_ids[:, -1:]
749
+
750
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
751
+ if inputs_embeds is not None and past_key_values is None:
752
+ model_inputs = {"inputs_embeds": inputs_embeds}
753
+ else:
754
+ model_inputs = {"input_ids": input_ids}
755
+
756
+ model_inputs.update(
757
+ {
758
+ "past_key_values": past_key_values,
759
+ "use_cache": kwargs.get("use_cache"),
760
+ "attention_mask": attention_mask,
761
+ }
762
+ )
763
+ return model_inputs
764
+
765
+ @staticmethod
766
+ def _reorder_cache(past_key_values, beam_idx):
767
+ return tuple(
768
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past)
769
+ for layer_past in past_key_values
770
+ )
771
+
772
+ def _build_chat_input(
773
+ self, tokenizer, messages: List[dict], max_new_tokens: int = 0
774
+ ):
775
+ max_new_tokens = max_new_tokens or self.generation_config.max_new_tokens
776
+ max_input_tokens = self.config.model_max_length - max_new_tokens
777
+ max_input_tokens = max(self.config.model_max_length // 2, max_input_tokens)
778
+ total_input, round_input = [], []
779
+ for i, message in enumerate(messages[::-1]):
780
+ content_tokens = tokenizer.encode(message["content"])
781
+ if message["role"] == "user":
782
+ round_input = (
783
+ [self.generation_config.user_token_id]
784
+ + content_tokens
785
+ + round_input
786
+ )
787
+ if (
788
+ total_input
789
+ and len(total_input) + len(round_input) > max_input_tokens
790
+ ):
791
+ break
792
+ else:
793
+ total_input = round_input + total_input
794
+ if len(total_input) >= max_input_tokens:
795
+ break
796
+ else:
797
+ round_input = []
798
+ elif message["role"] == "assistant":
799
+ round_input = (
800
+ [self.generation_config.assistant_token_id]
801
+ + content_tokens
802
+ + [self.generation_config.eos_token_id]
803
+ + round_input
804
+ )
805
+ else:
806
+ raise ValueError(f"message role not supported yet: {message['role']}")
807
+ total_input = total_input[-max_input_tokens:] # truncate left
808
+ total_input.append(self.generation_config.assistant_token_id)
809
+ total_input = torch.LongTensor([total_input]).to(self.device)
810
+ return total_input
811
+
812
+ def chat(self, tokenizer, messages: List[dict], stream=False,
813
+ generation_config: Optional[GenerationConfig]=None):
814
+ generation_config = generation_config or self.generation_config
815
+ input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
816
+ if stream:
817
+ streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
818
+ Thread(target=self.generate, kwargs=dict(
819
+ inputs=input_ids, streamer=streamer,
820
+ generation_config=generation_config,
821
+ )).start()
822
+ return streamer
823
+ else:
824
+ outputs = self.generate(input_ids, generation_config=generation_config)
825
+ response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
826
+ return response