DuJinHua commited on
Commit
f1e4ebb
·
1 Parent(s): 76af7a5

Upload 11 files

Browse files
config.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "_from_model_config": true,
3
- "_name_or_path": "./merged-pt-baichuan-v2-gpu-a1002",
4
  "architectures": [
5
  "BaichuanForCausalLM"
6
  ],
@@ -21,8 +21,10 @@
21
  "pad_token_id": 0,
22
  "rms_norm_eps": 1e-06,
23
  "tie_word_embeddings": false,
 
24
  "torch_dtype": "float16",
25
- "transformers_version": "4.32.1",
26
  "use_cache": true,
27
- "vocab_size": 64000
 
28
  }
 
1
  {
2
  "_from_model_config": true,
3
+ "_name_or_path": "Baichuan2-13B-Chat",
4
  "architectures": [
5
  "BaichuanForCausalLM"
6
  ],
 
21
  "pad_token_id": 0,
22
  "rms_norm_eps": 1e-06,
23
  "tie_word_embeddings": false,
24
+ "tokenizer_class": "BaichuanTokenizer",
25
  "torch_dtype": "float16",
26
+ "transformers_version": "4.33.1",
27
  "use_cache": true,
28
+ "vocab_size": 125696,
29
+ "z_loss_weight": 0
30
  }
configuration_baichuan.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  from transformers.configuration_utils import PretrainedConfig
4
 
 
5
  class BaichuanConfig(PretrainedConfig):
6
  model_type = "baichuan"
7
  keys_to_ignore_at_inference = ["past_key_values"]
@@ -23,6 +24,7 @@ class BaichuanConfig(PretrainedConfig):
23
  eos_token_id=2,
24
  tie_word_embeddings=False,
25
  gradient_checkpointing=False,
 
26
  **kwargs,
27
  ):
28
  self.vocab_size = vocab_size
@@ -35,7 +37,8 @@ class BaichuanConfig(PretrainedConfig):
35
  self.initializer_range = initializer_range
36
  self.rms_norm_eps = rms_norm_eps
37
  self.use_cache = use_cache
38
- self.gradient_checkpointing = gradient_checkpointing,
 
39
  super().__init__(
40
  pad_token_id=pad_token_id,
41
  bos_token_id=bos_token_id,
@@ -43,4 +46,3 @@ class BaichuanConfig(PretrainedConfig):
43
  tie_word_embeddings=tie_word_embeddings,
44
  **kwargs,
45
  )
46
-
 
2
 
3
  from transformers.configuration_utils import PretrainedConfig
4
 
5
+
6
  class BaichuanConfig(PretrainedConfig):
7
  model_type = "baichuan"
8
  keys_to_ignore_at_inference = ["past_key_values"]
 
24
  eos_token_id=2,
25
  tie_word_embeddings=False,
26
  gradient_checkpointing=False,
27
+ z_loss_weight=0,
28
  **kwargs,
29
  ):
30
  self.vocab_size = vocab_size
 
37
  self.initializer_range = initializer_range
38
  self.rms_norm_eps = rms_norm_eps
39
  self.use_cache = use_cache
40
+ self.z_loss_weight = z_loss_weight
41
+ self.gradient_checkpointing = (gradient_checkpointing,)
42
  super().__init__(
43
  pad_token_id=pad_token_id,
44
  bos_token_id=bos_token_id,
 
46
  tie_word_embeddings=tie_word_embeddings,
47
  **kwargs,
48
  )
 
generation_config.json CHANGED
@@ -5,10 +5,10 @@
5
  "eos_token_id": 2,
6
  "max_new_tokens": 2048,
7
  "pad_token_id": 0,
8
- "repetition_penalty": 1.1,
9
  "temperature": 0.3,
10
  "top_k": 5,
11
  "top_p": 0.85,
12
- "transformers_version": "4.32.1",
13
  "user_token_id": 195
14
  }
 
5
  "eos_token_id": 2,
6
  "max_new_tokens": 2048,
7
  "pad_token_id": 0,
8
+ "repetition_penalty": 1.05,
9
  "temperature": 0.3,
10
  "top_k": 5,
11
  "top_p": 0.85,
12
+ "transformers_version": "4.33.1",
13
  "user_token_id": 195
14
  }
generation_utils.py CHANGED
@@ -80,3 +80,4 @@ class TextIterStreamer:
80
  raise StopIteration()
81
  else:
82
  return value
 
 
80
  raise StopIteration()
81
  else:
82
  return value
83
+
modeling_baichuan.py CHANGED
@@ -1,63 +1,77 @@
1
  # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
 
 
 
 
3
  import math
4
  from threading import Thread
5
  from typing import List, Optional, Tuple, Union
6
 
7
  import torch
8
- import torch.utils.checkpoint
9
  from torch.nn import CrossEntropyLoss
10
- from transformers import PreTrainedModel
 
11
  from transformers.activations import ACT2FN
12
- from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
- from transformers.utils import logging
14
  from transformers.generation.utils import GenerationConfig
 
 
15
 
16
- from .configuration_baichuan import BaichuanConfig
17
- from .generation_utils import build_chat_input, TextIterStreamer
 
18
 
19
  logger = logging.get_logger(__name__)
20
 
 
 
 
 
 
 
 
 
21
 
22
  def _get_interleave(n):
23
  def _get_interleave_power_of_2(n):
24
- start = (2 ** (-2 ** -(math.log2(n) - 3)))
25
  ratio = start
26
- return [start * ratio ** i for i in range(n)]
27
 
28
  if math.log2(n).is_integer():
29
  return _get_interleave_power_of_2(n)
30
  else:
31
  closest_power_of_2 = 2 ** math.floor(math.log2(n))
32
- return _get_interleave_power_of_2(closest_power_of_2) + \
33
- _get_interleave(2 * closest_power_of_2)[0::2][:n - closest_power_of_2]
 
 
 
34
 
35
  def _fill_with_neg_inf(t):
36
  """FP16-compatible function that fills a tensor with -inf."""
37
  return t.float().fill_(float("-inf")).type_as(t)
38
 
39
- def _gen_alibi_mask(n_head, max_pos):
40
- """used in inference only"""
 
 
 
 
 
 
 
41
  slopes = torch.Tensor(_get_interleave(n_head))
42
- alibi = slopes.unsqueeze(1).unsqueeze(1) * torch.arange(max_pos).unsqueeze(0).unsqueeze(0).expand(
43
- n_head, -1, -1)
 
 
 
44
  alibi = alibi.view(n_head, 1, max_pos)
45
- alibi_mask = torch.triu(
46
- _fill_with_neg_inf(torch.zeros([max_pos, max_pos])), 1
47
- )
48
  alibi_mask = alibi_mask.unsqueeze(0) + alibi
49
  return alibi_mask
50
 
51
- def _buffered_future_mask(tensor, maxpos, alibi, attn_heads):
52
- """used in training only"""
53
- dim = tensor.size(1)
54
- _future_mask = torch.triu(
55
- _fill_with_neg_inf(torch.zeros([maxpos, maxpos])), 1
56
- )
57
- _future_mask = _future_mask.unsqueeze(0) + alibi
58
- _future_mask = _future_mask.to(tensor)
59
- return _future_mask[:tensor.shape[0] * attn_heads, :maxpos, :maxpos]
60
-
61
 
62
  class RMSNorm(torch.nn.Module):
63
  def __init__(self, hidden_size, epsilon=1e-6):
@@ -78,10 +92,10 @@ class RMSNorm(torch.nn.Module):
78
 
79
  class MLP(torch.nn.Module):
80
  def __init__(
81
- self,
82
- hidden_size: int,
83
- intermediate_size: int,
84
- hidden_act: str,
85
  ):
86
  super().__init__()
87
  self.gate_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
@@ -106,28 +120,46 @@ class BaichuanAttention(torch.nn.Module):
106
  raise ValueError(
107
  f"hidden_size {self.hidden_size} is not divisible by num_heads {self.num_heads}"
108
  )
109
- self.W_pack = torch.nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
110
- self.o_proj = torch.nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
 
 
 
 
111
 
112
  def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
113
- return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
 
 
 
 
114
 
115
  def forward(
116
- self,
117
- hidden_states: torch.Tensor,
118
- attention_mask: Optional[torch.Tensor] = None,
119
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
120
- output_attentions: bool = False,
121
- use_cache: bool = False,
122
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
123
-
124
  bsz, q_len, _ = hidden_states.size()
125
 
126
  proj = self.W_pack(hidden_states)
127
- proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2)
128
- query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
129
- key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
130
- value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  kv_seq_len = key_states.shape[-2]
133
  if past_key_value is not None:
@@ -139,23 +171,37 @@ class BaichuanAttention(torch.nn.Module):
139
  value_states = torch.cat([past_key_value[1], value_states], dim=2)
140
 
141
  past_key_value = (key_states, value_states) if use_cache else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
144
-
145
- if attention_mask is not None:
146
- if q_len == 1: # inference with cache
147
- if len(attention_mask.size()) == 4:
148
- attention_mask = attention_mask[:, :, -1:, :]
149
- else:
150
- attention_mask = attention_mask[:, -1:, :]
151
- attn_weights = attn_weights + attention_mask
152
- attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
153
-
154
- attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
155
-
156
- attn_output = torch.matmul(attn_weights, value_states)
157
 
158
- attn_output = attn_output.transpose(1, 2)
159
  attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
160
  attn_output = self.o_proj(attn_output)
161
 
@@ -176,17 +222,20 @@ class BaichuanLayer(torch.nn.Module):
176
  hidden_act=config.hidden_act,
177
  )
178
  self.input_layernorm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
179
- self.post_attention_layernorm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
 
 
180
 
181
  def forward(
182
- self,
183
- hidden_states: torch.Tensor,
184
- attention_mask: Optional[torch.Tensor] = None,
185
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
186
- output_attentions: Optional[bool] = False,
187
- use_cache: Optional[bool] = False,
188
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
189
-
 
190
  residual = hidden_states
191
 
192
  hidden_states = self.input_layernorm(hidden_states)
@@ -244,8 +293,12 @@ class BaichuanModel(BaichuanPreTrainedModel):
244
  self.padding_idx = config.pad_token_id
245
  self.vocab_size = config.vocab_size
246
  self.n_head = config.num_attention_heads
247
- self.embed_tokens = torch.nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
248
- self.layers = torch.nn.ModuleList([BaichuanLayer(config) for _ in range(config.num_hidden_layers)])
 
 
 
 
249
  self.norm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
250
 
251
  self.gradient_checkpointing = config.gradient_checkpointing
@@ -263,35 +316,61 @@ class BaichuanModel(BaichuanPreTrainedModel):
263
  def get_alibi_mask(self, tensor, seq_length_with_past):
264
  if self.training:
265
  slopes = torch.Tensor(_get_interleave(self.n_head))
266
- alibi = slopes.unsqueeze(1).unsqueeze(1) * torch.arange(seq_length_with_past).unsqueeze(0).unsqueeze(0).expand(
267
- self.n_head,
268
- -1, -1)
269
- alibi = alibi.view(self.n_head, 1, seq_length_with_past)
270
- mask = _buffered_future_mask(tensor, seq_length_with_past, alibi, self.n_head)
 
 
 
 
 
 
 
 
 
 
 
271
  else:
272
  if self.first_run:
273
  self.first_run = False
274
- self.register_buffer("future_mask", _gen_alibi_mask(self.n_head, self.max_cache_pos).to(tensor), persistent=False)
 
 
 
 
 
 
275
  if seq_length_with_past > self.max_cache_pos:
276
  self.max_cache_pos = seq_length_with_past
277
- self.register_buffer("future_mask", _gen_alibi_mask(self.n_head, self.max_cache_pos).to(tensor), persistent=False)
278
- mask = self.future_mask[:self.n_head, :seq_length_with_past, :seq_length_with_past]
 
 
 
 
 
 
 
 
279
  return mask
280
 
281
  def forward(
282
- self,
283
- input_ids: torch.LongTensor = None,
284
- attention_mask: Optional[torch.Tensor] = None,
285
- past_key_values: Optional[List[torch.FloatTensor]] = None,
286
- inputs_embeds: Optional[torch.FloatTensor] = None,
287
- use_cache: Optional[bool] = False,
288
- output_attentions: Optional[bool] = False,
289
- output_hidden_states: Optional[bool] = False,
290
- return_dict: Optional[bool] = True,
291
  ) -> Union[Tuple, BaseModelOutputWithPast]:
292
-
293
  if input_ids is not None and inputs_embeds is not None:
294
- raise ValueError("You cannot provide both input_ids and inputs_embeds simultaneously")
 
 
295
  elif input_ids is not None:
296
  batch_size, seq_length = input_ids.shape
297
  elif inputs_embeds is not None:
@@ -299,7 +378,9 @@ class BaichuanModel(BaichuanPreTrainedModel):
299
  else:
300
  raise ValueError("You need to provide input_ids or inputs_embeds")
301
 
302
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
 
 
303
 
304
  seq_length_with_past = seq_length
305
 
@@ -311,8 +392,13 @@ class BaichuanModel(BaichuanPreTrainedModel):
311
  inputs_embeds = self.embed_tokens(input_ids)
312
 
313
  if self.training:
314
- if self.alibi_mask is None or self.alibi_mask.shape[-1] != seq_length_with_past:
315
- self.alibi_mask = self.get_alibi_mask(inputs_embeds, seq_length_with_past)
 
 
 
 
 
316
  alibi_mask = self.alibi_mask
317
  else:
318
  alibi_mask = self.get_alibi_mask(inputs_embeds, seq_length_with_past)
@@ -320,15 +406,22 @@ class BaichuanModel(BaichuanPreTrainedModel):
320
  if attention_mask is not None:
321
  if len(attention_mask.shape) == 2:
322
  expanded_mask = attention_mask.to(alibi_mask.dtype)
323
- expanded_mask = torch.tril(torch.gt(expanded_mask[:, :, None] * expanded_mask[:, None, :], 0)
324
- ) * torch.eq(expanded_mask[:, :, None] - expanded_mask[:, None, :], 0)
 
325
  else:
326
- expanded_mask = attention_mask
327
  bsz = inputs_embeds.size(0)
328
  src_len, tgt_len = alibi_mask.size()[-2:]
329
- expanded_mask = expanded_mask.unsqueeze(1).expand(bsz, 1, src_len, tgt_len).to(alibi_mask.dtype)
 
 
 
 
330
  inverted_mask = 1.0 - expanded_mask
331
- inverted_mask = inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(alibi_mask.dtype).min)
 
 
332
  attention_mask = inverted_mask + alibi_mask.unsqueeze(0)
333
  else:
334
  attention_mask = alibi_mask
@@ -351,7 +444,9 @@ class BaichuanModel(BaichuanPreTrainedModel):
351
  if output_hidden_states:
352
  all_hidden_states += (hidden_states,)
353
 
354
- past_key_value = past_key_values[idx] if past_key_values is not None else None
 
 
355
 
356
  if self.gradient_checkpointing and self.training:
357
 
@@ -393,7 +488,11 @@ class BaichuanModel(BaichuanPreTrainedModel):
393
 
394
  next_cache = next_decoder_cache if use_cache else None
395
  if not return_dict:
396
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
 
 
 
 
397
  return BaseModelOutputWithPast(
398
  last_hidden_state=hidden_states,
399
  past_key_values=next_cache,
@@ -402,12 +501,50 @@ class BaichuanModel(BaichuanPreTrainedModel):
402
  )
403
 
404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  class BaichuanForCausalLM(BaichuanPreTrainedModel):
406
- def __init__(self, config):
407
- super().__init__(config)
408
  self.model = BaichuanModel(config)
409
- self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False)
410
-
 
 
 
 
 
 
411
  # Initialize weights and apply final processing
412
  self.post_init()
413
 
@@ -428,23 +565,130 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
428
 
429
  def get_decoder(self):
430
  return self.model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431
 
432
  def forward(
433
- self,
434
- input_ids: torch.LongTensor = None,
435
- attention_mask: Optional[torch.Tensor] = None,
436
- past_key_values: Optional[List[torch.FloatTensor]] = None,
437
- inputs_embeds: Optional[torch.FloatTensor] = None,
438
- labels: Optional[torch.LongTensor] = None,
439
- use_cache: Optional[bool] = None,
440
- output_attentions: Optional[bool] = False,
441
- output_hidden_states: Optional[bool] = False,
442
- return_dict: Optional[bool] = True,
443
- **kwargs
444
  ) -> Union[Tuple, CausalLMOutputWithPast]:
 
 
 
445
 
446
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
447
-
448
  # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
449
  outputs = self.model(
450
  input_ids=input_ids,
@@ -459,7 +703,6 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
459
 
460
  hidden_states = outputs[0]
461
  logits = self.lm_head(hidden_states)
462
-
463
  loss = None
464
  if labels is not None:
465
  # Shift so that tokens < n predict n
@@ -469,9 +712,11 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
469
  loss_fct = CrossEntropyLoss()
470
  shift_logits = shift_logits.view(-1, self.config.vocab_size)
471
  shift_labels = shift_labels.view(-1)
 
 
472
  # Enable model parallelism
473
  shift_labels = shift_labels.to(shift_logits.device)
474
- loss = loss_fct(shift_logits, shift_labels)
475
 
476
  if not return_dict:
477
  output = (logits,) + outputs[1:]
@@ -485,13 +730,20 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
485
  attentions=outputs.attentions,
486
  )
487
 
 
 
 
 
 
 
 
488
  def prepare_inputs_for_generation(
489
- self,
490
- input_ids: torch.LongTensor,
491
- past_key_values: Optional[torch.Tensor] = None,
492
- attention_mask: Optional[torch.Tensor] = None,
493
- inputs_embeds: Optional[torch.Tensor] = None,
494
- **kwargs
495
  ):
496
  if past_key_values:
497
  input_ids = input_ids[:, -1:]
@@ -506,7 +758,7 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
506
  {
507
  "past_key_values": past_key_values,
508
  "use_cache": kwargs.get("use_cache"),
509
- "attention_mask": attention_mask
510
  }
511
  )
512
  return model_inputs
@@ -518,43 +770,46 @@ class BaichuanForCausalLM(BaichuanPreTrainedModel):
518
  for layer_past in past_key_values
519
  )
520
 
521
- def quantize(self, bits: int):
522
- try:
523
- from .quantizer import QLinear
524
- except ImportError:
525
- raise ImportError(
526
- f"Needs QLinear to run quantize."
527
- )
528
-
529
- for layer in self.model.layers:
530
- layer.self_attn.W_pack = QLinear(
531
- bits=bits,
532
- weight=layer.self_attn.W_pack.weight,
533
- bias = None,
534
- )
535
- layer.self_attn.o_proj = QLinear(
536
- bits=bits,
537
- weight=layer.self_attn.o_proj.weight,
538
- bias = None,
539
- )
540
- layer.mlp.gate_proj = QLinear(
541
- bits=bits,
542
- weight=layer.mlp.gate_proj.weight,
543
- bias = None,
544
- )
545
- layer.mlp.down_proj = QLinear(
546
- bits=bits,
547
- weight=layer.mlp.down_proj.weight,
548
- bias = None,
549
- )
550
- layer.mlp.up_proj = QLinear(
551
- bits=bits,
552
- weight=layer.mlp.up_proj.weight,
553
- bias = None,
554
- )
555
- return self
 
 
 
 
556
 
557
- @torch.no_grad()
558
  def chat(self, tokenizer, messages: List[dict], stream=False,
559
  generation_config: Optional[GenerationConfig]=None):
560
  generation_config = generation_config or self.generation_config
 
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):
 
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)
 
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:
 
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
 
 
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)
 
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
 
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:
 
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
 
 
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)
 
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
 
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
 
 
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,
 
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
+ self.first_flag = True
515
+ elif self.first_flag:
516
+ self.first_flag = False
517
+ self.weight.data = nn.functional.normalize(self.weight)
518
+ norm_weight = self.weight
519
+ else:
520
+ norm_weight = self.weight
521
+ return nn.functional.linear(hidden_states, norm_weight)
522
+
523
+ _init_weights = True
524
+ @contextmanager
525
+ def no_init_weights(_enable=True):
526
+ global _init_weights
527
+ old_init_weights = _init_weights
528
+ if _enable:
529
+ _init_weights = False
530
+ try:
531
+ yield
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()
550
 
 
565
 
566
  def get_decoder(self):
567
  return self.model
568
+
569
+ @classmethod
570
+ def from_pretrained(
571
+ cls,
572
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
573
+ *model_args,
574
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
575
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
576
+ ignore_mismatched_sizes: bool = False,
577
+ force_download: bool = False,
578
+ local_files_only: bool = False,
579
+ token: Optional[Union[str, bool]] = None,
580
+ revision: str = "main",
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
588
+ config, model_kwargs = cls.config_class.from_pretrained(
589
+ config_path,
590
+ cache_dir=cache_dir,
591
+ return_unused_kwargs=True,
592
+ force_download=force_download,
593
+ resume_download=False,
594
+ proxies=None,
595
+ local_files_only=local_files_only,
596
+ token=token,
597
+ revision=revision,
598
+ subfolder="",
599
+ _from_auto=False,
600
+ _from_pipeline=None,
601
+ **kwargs,
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,
 
703
 
704
  hidden_states = outputs[0]
705
  logits = self.lm_head(hidden_states)
 
706
  loss = None
707
  if labels is not None:
708
  # Shift so that tokens < n predict n
 
712
  loss_fct = CrossEntropyLoss()
713
  shift_logits = shift_logits.view(-1, self.config.vocab_size)
714
  shift_labels = shift_labels.view(-1)
715
+ softmax_normalizer = shift_logits.max(-1).values ** 2
716
+ z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
717
  # Enable model parallelism
718
  shift_labels = shift_labels.to(shift_logits.device)
719
+ loss = loss_fct(shift_logits, shift_labels) + z_loss
720
 
721
  if not return_dict:
722
  output = (logits,) + outputs[1:]
 
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:]
 
758
  {
759
  "past_key_values": past_key_values,
760
  "use_cache": kwargs.get("use_cache"),
761
+ "attention_mask": attention_mask,
762
  }
763
  )
764
  return model_inputs
 
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
pytorch_model.bin.index.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "metadata": {
3
- "total_size": 26529802240
4
  },
5
  "weight_map": {
6
  "lm_head.weight": "pytorch_model-00003-of-00003.bin",
@@ -40,20 +40,20 @@
40
  "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
41
  "model.layers.12.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
42
  "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
43
- "model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
44
  "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
45
  "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
46
- "model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
47
- "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
48
  "model.layers.13.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
49
  "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
50
  "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
51
- "model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
52
- "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
53
  "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
54
  "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
55
- "model.layers.14.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
56
- "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
57
  "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
58
  "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
59
  "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
@@ -159,11 +159,11 @@
159
  "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
160
  "model.layers.28.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
161
  "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
162
- "model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
163
- "model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
164
  "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
165
- "model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
166
- "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
167
  "model.layers.29.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
168
  "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
169
  "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
@@ -175,11 +175,11 @@
175
  "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
176
  "model.layers.30.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
177
  "model.layers.30.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
178
- "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
179
  "model.layers.30.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
180
  "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
181
- "model.layers.30.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
182
- "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
183
  "model.layers.31.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
184
  "model.layers.31.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
185
  "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
 
1
  {
2
  "metadata": {
3
+ "total_size": 27793336320
4
  },
5
  "weight_map": {
6
  "lm_head.weight": "pytorch_model-00003-of-00003.bin",
 
40
  "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
41
  "model.layers.12.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
42
  "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
43
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
44
  "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
45
  "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
46
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
47
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
48
  "model.layers.13.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
49
  "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
50
  "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
51
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
52
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
53
  "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
54
  "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
55
+ "model.layers.14.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
56
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
57
  "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
58
  "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
59
  "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
 
159
  "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
160
  "model.layers.28.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
161
  "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
162
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
163
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
164
  "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
165
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
166
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
167
  "model.layers.29.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
168
  "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
169
  "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
 
175
  "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
176
  "model.layers.30.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
177
  "model.layers.30.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
178
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
179
  "model.layers.30.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
180
  "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
181
+ "model.layers.30.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
182
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
183
  "model.layers.31.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
184
  "model.layers.31.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
185
  "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
quantizer.py CHANGED
@@ -1,123 +1,211 @@
1
- # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
-
3
- import torch
4
- from typing import List
5
- import bz2
6
- import base64
7
- import ctypes
8
- from transformers.utils import logging
9
- logger = logging.get_logger(__name__)
10
-
11
- try:
12
- from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
13
-
14
- class Kernel:
15
- def __init__(self, code: bytes, function_names: List[str]):
16
- self.code = code
17
- self._function_names = function_names
18
- self._cmodule = LazyKernelCModule(self.code)
19
-
20
- for name in self._function_names:
21
- setattr(self, name, KernelFunction(self._cmodule, name))
22
- quantization_code = "QlpoOTFBWSZTWX/mUzwAK6f///////////////////////////////7f////////////4C5duvi2D0Oj1ppVCJ2zQFYbnbsxmq20pAC7kEDb3Z3nWrextY9NZbavON7nveSRqszudmzAGGgkeh0Pewk881e3Tz13kW9YO7uA9AUUiAWLNW2HHWCE005Mdz3jHs1Ic7QNCQBNGgmE000DRNoGjUYmA0mEmJjIaI9JtT0JoaaMTaQ0aMjTTI1TzKMmETwyaJ6k8p4Ke1T0wk2aE0anpPSHppqNM1HqYzVGj0MpsTTUGpoCAAEyAAAmhpPSYow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QA1FEqGKaOFgPS4YwF0qjqJ96aNghQyxO4ETMPCpx6cPhE1xsRksh7qapVjAG7QQVa6blYCqhJolWKylASeNpfutZRkWEfehrAM1hps1M6VN9y+8pnOeOL3eSrvGKkr3kEDbExtsYADtYMAhLoFzWdZo6F3T89cLurlkYDQ8iWVgjINJHQatNc/BZZPPYhX7J3dX5zJTnZ1pJIV4y+k2MF25BTUhIvz2okmED6ax7KgYdJtMkMMjHiBpMVmJIippQbqyHkJreoQDGrZe8QH4qNpIBqEHFpVTrJVwkLCu5ds3+pbccosPAGFjP4J0AB15EXRr4rcAbXmibqr2600yb4dM8VbMHACFOCBZhZIxpWCMkDUZIBUQoKpooWCkAnBzOK5na/LqSSLTATYIaabQCteZkFlqs0bDPpuWAcNiRn6GWSnwrsatNVFIK0+WUGVX3p1UghXmamW9amFzoPHfP2Z3WLhW9ZEaq0DQiqOJyRC17MYwQA84eUDjyR/GOBNpNoO1pV6NwwsBZoAgBWz+M+YS5GC+Su1IEB0A5in0LwPQxXq7joeDPBdd3DzF6z96RTojxR29u8vE3GnO6jAa0MBmCuoxyYl/SDsbSpYIlMINttOUZndGWJ2JgBs8s7bw1GhnALOxFBnZayRRjt4bSvH+Ma9WNZSaKBoUDtDEQNIMt5XAZJIvEFZSahWUgL7ADIBAjZYJVAK8NHljSCRbLZdxbuCkFfrZVirL+GkBWYaJFCoglTaEWtiguhCVZNjj+c9eMUMbOVJQmcHOmKmRIKboAMkAbohUflNANgubKuhTXDGSlSKY0PetmdL+7bQoIJCVRY+osfasgH1NADQYBBoYd+dccoSIhapDyYkRkhkYGAZDWCMlJReDHnRJZKAxUYiJmPGYriVoGAkdW2QI785BQQakRBFiFEknMOMGpw8jj8a7sLaWrGrZ5gDnB2Ys6AFHfczh5BvVw8R6n1P4QHEbDeIf/i7kinChIP/Mpng="
23
- kernels = Kernel(
24
- bz2.decompress(base64.b64decode(quantization_code)),
25
- [
26
- "int4_to_fp16",
27
- "fp16_to_int4",
28
- "int8_to_fp16",
29
- "fp16_to_int8",
30
- "int4_to_bf16",
31
- "bf16_to_int4",
32
- "int8_to_bf16",
33
- "bf16_to_int8",
34
- ],
35
- )
36
- except Exception as exception:
37
- kernels = None
38
- logger.warning("Failed to load kernels:" + str(exception))
39
-
40
- def quant4(weight: torch.Tensor, scale: torch.Tensor):
41
- stream = torch.cuda.current_stream()
42
- num_row = weight.size(0)
43
- num_chan_fp16 = weight.size(1)
44
- # 4bit
45
- num_chan_int = num_chan_fp16 // 8
46
- qweight = torch.zeros((num_row, num_chan_int), dtype=torch.int32, device=weight.device)
47
- intweight = torch.empty(num_row, num_chan_fp16, dtype = torch.int32)
48
- intweight = torch.clip(torch.round(weight.to(scale.dtype) / scale[:, None]),-16, 15).to(dtype=torch.int32)
49
-
50
- for j in range(num_chan_int):
51
- qweight[:, j] = ((intweight[:, j*8+7] & 0x0f) << 28) \
52
- | ((intweight[:, j*8+6] & 0x0f) << 24) \
53
- | ((intweight[:, j*8+5] & 0x0f) << 20) \
54
- | ((intweight[:, j*8+4] & 0x0f) << 16) \
55
- | ((intweight[:, j*8+3] & 0x0f) << 12) \
56
- | ((intweight[:, j*8+2] & 0x0f) << 8) \
57
- | ((intweight[:, j*8+1] & 0x0f) << 4) \
58
- | ((intweight[:, j*8] & 0x0f))
59
- return qweight
60
-
61
- def dequant4(qweight: torch.Tensor, scale: torch.Tensor, input: torch.Tensor):
62
- stream = torch.cuda.current_stream()
63
- num_row = qweight.size(0)
64
- num_chan_int = qweight.size(1)
65
- # 4bit
66
- num_chan_fp16 = num_chan_int * 8
67
-
68
- out = torch.empty((num_row, num_chan_fp16), dtype=input.dtype, device=qweight.device)
69
-
70
- blockDim = (128, 1, 1)
71
- gridDim = ((num_chan_int + blockDim[0] - 1) // blockDim[0], num_row, 1)
72
- if input.dtype == torch.bfloat16:
73
- kernels.int4_to_bf16(
74
- gridDim,
75
- blockDim,
76
- 0,
77
- stream,
78
- [ctypes.c_void_p(out.data_ptr()), ctypes.c_void_p(qweight.data_ptr()),
79
- ctypes.c_void_p(scale.data_ptr()), ctypes.c_int32(num_row), ctypes.c_int32(num_chan_int), ctypes.c_int32(num_chan_fp16)],
80
  )
81
- elif input.dtype == torch.float16:
82
- kernels.int4_to_fp16(
83
- gridDim,
84
- blockDim,
85
- 0,
86
- stream,
87
- [ctypes.c_void_p(out.data_ptr()), ctypes.c_void_p(qweight.data_ptr()),
88
- ctypes.c_void_p(scale.data_ptr()), ctypes.c_int32(num_row), ctypes.c_int32(num_chan_int), ctypes.c_int32(num_chan_fp16)],
 
 
 
 
 
 
 
 
 
 
 
 
89
  )
90
- return out
91
 
92
- class QLinear(torch.nn.Module):
93
- def __init__(self, bits: int, weight: torch.Tensor, bias=None):
 
 
 
 
 
 
 
 
 
 
 
 
94
  super().__init__()
95
- self.quant_bits = bits
96
- self.scale = weight.abs().max(dim=-1).values / ((2 ** (bits - 1)) - 1)
97
- self.scale = self.scale.to(torch.float32)
98
- if self.quant_bits == 4:
99
- self.weight = quant4(weight, self.scale)
100
- elif self.quant_bits == 8:
101
- self.weight = torch.round(weight.to(self.scale.dtype) / self.scale[:, None]).to(torch.int8)
102
- if self.quant_bits == 8:
103
- self.weight = self.weight.T
104
- self.bias = None
105
-
106
- def forward(self, input):
107
- if self.quant_bits == 4:
108
- assert(input.dtype == torch.bfloat16 or input.dtype == torch.float16)
109
-
110
- if self.weight.device != input.device:
111
- self.weight = self.weight.to(input.device)
112
- self.scale = self.scale.to(input.device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- if self.quant_bits == 4:
115
- self.scale = self.scale.to(input.dtype)
116
- rweight = dequant4(self.weight, self.scale, input).T
117
- output = torch.matmul(input, rweight)
118
- elif self.quant_bits == 8:
119
- rweight = self.weight.to(input.dtype) * self.scale.to(input.dtype)
120
- output = torch.matmul(input, rweight)
121
- if self.bias is not None:
122
- output = output + self.bias
123
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bitsandbytes as bnb
2
+ from accelerate import init_empty_weights
3
+ from bitsandbytes.nn.modules import Params4bit, Int8Params
4
+ import torch
5
+
6
+ def Params4bitCuda(self, device):
7
+ self.data = self.data.cuda(device)
8
+ self.quant_state[0] = self.quant_state[0].cuda(device)
9
+ self.quant_state[4][0] = self.quant_state[4][0].cuda(device)
10
+ self.quant_state[4][1][0] = self.quant_state[4][1][0].cuda(device)
11
+ self.quant_state[4][1][1] = self.quant_state[4][1][1].cuda(device)
12
+
13
+ self.quant_state[6] = self.quant_state[6].cuda(device)
14
+ return self
15
+
16
+ class Linear4bitOnline(torch.nn.Module):
17
+ def __init__(self, weight, bias, quant_type):
18
+ super().__init__()
19
+ self.weight = Params4bit(
20
+ weight.data, requires_grad=False, compress_statistics=True, quant_type=quant_type
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  )
22
+ self.compute_dtype = None
23
+ #self.weight.cuda(weight.device)
24
+ self.bias = bias
25
+
26
+ def forward(self, x: torch.Tensor):
27
+ # weights are cast automatically as Int8Params, but the bias has to be cast manually
28
+ if self.bias is not None and self.bias.dtype != x.dtype:
29
+ self.bias.data = self.bias.data.to(x.dtype)
30
+
31
+ if getattr(self.weight, "quant_state", None) is None:
32
+ print(
33
+ "FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first."
34
+ )
35
+ inp_dtype = x.dtype
36
+ if self.compute_dtype is not None:
37
+ x = x.to(self.compute_dtype)
38
+
39
+ bias = None if self.bias is None else self.bias.to(self.compute_dtype)
40
+ out = bnb.matmul_4bit(
41
+ x, self.weight.t(), bias=bias, quant_state=self.weight.quant_state
42
  )
 
43
 
44
+ out = out.to(inp_dtype)
45
+
46
+ return out
47
+
48
+ class Linear8bitLtOnline(torch.nn.Module):
49
+ def __init__(
50
+ self,
51
+ weight,
52
+ bias,
53
+ has_fp16_weights=True,
54
+ memory_efficient_backward=False,
55
+ threshold=0.0,
56
+ index=None,
57
+ ):
58
  super().__init__()
59
+ assert (
60
+ not memory_efficient_backward
61
+ ), "memory_efficient_backward is no longer required and the argument is deprecated in 0.37.0 and will be removed in 0.39.0"
62
+ self.state = bnb.MatmulLtState()
63
+ self.index = index
64
+
65
+ # Necessary for stacked layers
66
+ self.state.threshold = threshold
67
+ self.state.has_fp16_weights = has_fp16_weights
68
+ self.state.memory_efficient_backward = memory_efficient_backward
69
+ if threshold > 0.0 and not has_fp16_weights:
70
+ self.state.use_pool = True
71
+
72
+ self.weight = Int8Params(
73
+ weight.data,
74
+ has_fp16_weights=has_fp16_weights,
75
+ requires_grad=has_fp16_weights,
76
+ )
77
+ self.bias = bias
78
+
79
+ def init_8bit_state(self):
80
+ self.state.CB = self.weight.CB
81
+ self.state.SCB = self.weight.SCB
82
+ self.weight.CB = None
83
+ self.weight.SCB = None
84
+
85
+ def forward(self, x: torch.Tensor):
86
+ self.state.is_training = self.training
87
+ if self.weight.CB is not None:
88
+ self.init_8bit_state()
89
+
90
+ # weights are cast automatically as Int8Params, but the bias has to be cast manually
91
+ if self.bias is not None and self.bias.dtype != x.dtype:
92
+ self.bias.data = self.bias.data.to(x.dtype)
93
 
94
+ out = bnb.matmul(x, self.weight, bias=self.bias, state=self.state)
95
+
96
+ if not self.state.has_fp16_weights:
97
+ if self.state.CB is not None and self.state.CxB is not None:
98
+ # we converted 8-bit row major to turing/ampere format in the first inference pass
99
+ # we no longer need the row-major weight
100
+ del self.state.CB
101
+ self.weight.data = self.state.CxB
102
+ return out
103
+
104
+ def quantize_offline(model, bits: int):
105
+ assert (bits == 4), f'bits: {bits} is not supported'
106
+
107
+ for i, layer in enumerate(model.model.layers):
108
+ layer.self_attn.W_pack = bnb.nn.Linear4bit(
109
+ layer.self_attn.W_pack.weight.shape[1],
110
+ layer.self_attn.W_pack.weight.shape[0],
111
+ False,
112
+ torch.float16,
113
+ compress_statistics=True,
114
+ quant_type="nf4",
115
+ )
116
+ layer.self_attn.o_proj = bnb.nn.Linear4bit(
117
+ layer.self_attn.o_proj.weight.shape[1],
118
+ layer.self_attn.o_proj.weight.shape[0],
119
+ False,
120
+ torch.float16,
121
+ compress_statistics=True,
122
+ quant_type="nf4",
123
+ )
124
+
125
+ layer.mlp.gate_proj = bnb.nn.Linear4bit(
126
+ layer.mlp.gate_proj.weight.shape[1],
127
+ layer.mlp.gate_proj.weight.shape[0],
128
+ False,
129
+ torch.float16,
130
+ compress_statistics=True,
131
+ quant_type="nf4",
132
+ )
133
+ layer.mlp.down_proj = bnb.nn.Linear4bit(
134
+ layer.mlp.down_proj.weight.shape[1],
135
+ layer.mlp.down_proj.weight.shape[0],
136
+ False,
137
+ torch.float16,
138
+ compress_statistics=True,
139
+ quant_type="nf4",
140
+ )
141
+ layer.mlp.up_proj = bnb.nn.Linear4bit(
142
+ layer.mlp.up_proj.weight.shape[1],
143
+ layer.mlp.up_proj.weight.shape[0],
144
+ False,
145
+ torch.float16,
146
+ compress_statistics=True,
147
+ quant_type="nf4",
148
+ )
149
+ return model
150
+
151
+ def quantize_online(model, bits: int):
152
+ def quant(weight, bias=None):
153
+ if bits == 8:
154
+ linear = Linear8bitLtOnline(
155
+ weight,
156
+ bias,
157
+ has_fp16_weights=False,
158
+ threshold=6.0,
159
+ )
160
+ if bias is not None:
161
+ linear.bias = torch.nn.Parameter(bias)
162
+ elif bits == 4:
163
+ linear = Linear4bitOnline(
164
+ weight,
165
+ bias,
166
+ quant_type="nf4", #fp4/nf4
167
+ )
168
+ else:
169
+ raise ValueError("quantize only support 4/8 bit")
170
+ return linear
171
+
172
+ for i, layer in enumerate(model.model.layers):
173
+ layer.self_attn.W_pack = quant(layer.self_attn.W_pack.weight)
174
+ layer.self_attn.o_proj = quant(layer.self_attn.o_proj.weight)
175
+ layer.mlp.gate_proj = quant(layer.mlp.gate_proj.weight)
176
+ layer.mlp.down_proj = quant(layer.mlp.down_proj.weight)
177
+ layer.mlp.up_proj = quant(layer.mlp.up_proj.weight)
178
+ return model
179
+
180
+ def init_model_weight_int4(config, model, state_dict):
181
+ #replace Params4bit.cuda with Params4bitCuda
182
+ Params4bit.cuda = Params4bitCuda
183
+
184
+ for i in range(config.num_hidden_layers):
185
+ weight_data = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.data']
186
+ weight_quant_state = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.quant_state']
187
+ model.model.layers[i].self_attn.W_pack.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
188
+
189
+ weight_data = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.data']
190
+ weight_quant_state = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.quant_state']
191
+ model.model.layers[i].self_attn.o_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
192
+
193
+ weight_data = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.data']
194
+ weight_quant_state = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.quant_state']
195
+ model.model.layers[i].mlp.gate_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
196
+
197
+ weight_data = state_dict[f'model.layers.{i}.mlp.up_proj.weight.data']
198
+ weight_quant_state = state_dict[f'model.layers.{i}.mlp.up_proj.weight.quant_state']
199
+ model.model.layers[i].mlp.up_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
200
+
201
+ weight_data = state_dict[f'model.layers.{i}.mlp.down_proj.weight.data']
202
+ weight_quant_state = state_dict[f'model.layers.{i}.mlp.down_proj.weight.quant_state']
203
+ model.model.layers[i].mlp.down_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
204
+
205
+ model.model.layers[i].input_layernorm.weight = state_dict[f'model.layers.{i}.input_layernorm.weight']
206
+ model.model.layers[i].post_attention_layernorm.weight = state_dict[f'model.layers.{i}.post_attention_layernorm.weight']
207
+
208
+ model.model.embed_tokens.weight = state_dict['model.embed_tokens.weight']
209
+ model.model.norm.weight = state_dict['model.norm.weight']
210
+ model.lm_head.weight = state_dict['lm_head.weight']
211
+ return model
tokenization_baichuan.py CHANGED
@@ -48,10 +48,26 @@ class BaichuanTokenizer(PreTrainedTokenizer):
48
  **kwargs,
49
  ):
50
  self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
51
- bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
52
- eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
53
- unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
54
- pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  super().__init__(
56
  bos_token=bos_token,
57
  eos_token=eos_token,
@@ -122,7 +138,9 @@ class BaichuanTokenizer(PreTrainedTokenizer):
122
  out_string += self.sp_model.decode(current_sub_tokens)
123
  return out_string
124
 
125
- def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
 
 
126
  """
127
  Save the vocabulary and special tokens file to a directory.
128
 
@@ -137,10 +155,14 @@ class BaichuanTokenizer(PreTrainedTokenizer):
137
  logger.error(f"Vocabulary path ({save_directory}) should be a directory")
138
  return
139
  out_vocab_file = os.path.join(
140
- save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
 
 
141
  )
142
 
143
- if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
 
 
144
  copyfile(self.vocab_file, out_vocab_file)
145
  elif not os.path.isfile(self.vocab_file):
146
  with open(out_vocab_file, "wb") as fi:
@@ -161,7 +183,10 @@ class BaichuanTokenizer(PreTrainedTokenizer):
161
  return output
162
 
163
  def get_special_tokens_mask(
164
- self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
 
 
 
165
  ) -> List[int]:
166
  """
167
  Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
@@ -180,7 +205,9 @@ class BaichuanTokenizer(PreTrainedTokenizer):
180
  """
181
  if already_has_special_tokens:
182
  return super().get_special_tokens_mask(
183
- token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
 
 
184
  )
185
 
186
  bos_token_id = [1] if self.add_bos_token else []
@@ -229,4 +256,3 @@ class BaichuanTokenizer(PreTrainedTokenizer):
229
  output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
230
 
231
  return output
232
-
 
48
  **kwargs,
49
  ):
50
  self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
51
+ bos_token = (
52
+ AddedToken(bos_token, lstrip=False, rstrip=False)
53
+ if isinstance(bos_token, str)
54
+ else bos_token
55
+ )
56
+ eos_token = (
57
+ AddedToken(eos_token, lstrip=False, rstrip=False)
58
+ if isinstance(eos_token, str)
59
+ else eos_token
60
+ )
61
+ unk_token = (
62
+ AddedToken(unk_token, lstrip=False, rstrip=False)
63
+ if isinstance(unk_token, str)
64
+ else unk_token
65
+ )
66
+ pad_token = (
67
+ AddedToken(pad_token, lstrip=False, rstrip=False)
68
+ if isinstance(pad_token, str)
69
+ else pad_token
70
+ )
71
  super().__init__(
72
  bos_token=bos_token,
73
  eos_token=eos_token,
 
138
  out_string += self.sp_model.decode(current_sub_tokens)
139
  return out_string
140
 
141
+ def save_vocabulary(
142
+ self, save_directory, filename_prefix: Optional[str] = None
143
+ ) -> Tuple[str]:
144
  """
145
  Save the vocabulary and special tokens file to a directory.
146
 
 
155
  logger.error(f"Vocabulary path ({save_directory}) should be a directory")
156
  return
157
  out_vocab_file = os.path.join(
158
+ save_directory,
159
+ (filename_prefix + "-" if filename_prefix else "")
160
+ + VOCAB_FILES_NAMES["vocab_file"],
161
  )
162
 
163
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
164
+ out_vocab_file
165
+ ) and os.path.isfile(self.vocab_file):
166
  copyfile(self.vocab_file, out_vocab_file)
167
  elif not os.path.isfile(self.vocab_file):
168
  with open(out_vocab_file, "wb") as fi:
 
183
  return output
184
 
185
  def get_special_tokens_mask(
186
+ self,
187
+ token_ids_0: List[int],
188
+ token_ids_1: Optional[List[int]] = None,
189
+ already_has_special_tokens: bool = False,
190
  ) -> List[int]:
191
  """
192
  Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
 
205
  """
206
  if already_has_special_tokens:
207
  return super().get_special_tokens_mask(
208
+ token_ids_0=token_ids_0,
209
+ token_ids_1=token_ids_1,
210
+ already_has_special_tokens=True,
211
  )
212
 
213
  bos_token_id = [1] if self.add_bos_token else []
 
256
  output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
257
 
258
  return output
 
tokenizer.model CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f7d1ab69d25c74644af5c5e4dcd1cc6e96d33783dbd257b6bdea55b643c72813
3
- size 1136765
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79452955be6b419a65984273a9f08af86042e1c2a75ee3ba989cbf620a133cc2
3
+ size 2001107