xumingyu16 commited on
Commit
0ba944c
·
verified ·
1 Parent(s): 297709e

Upload 12 files

Browse files
__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Time : 2023/12/15 22:11
4
+ @FileName: __init__.py.py
5
+ @author: 王炳宁
6
+ @contact: [email protected]
7
+ """
8
+
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<pad>": 48000
3
+ }
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BaichuanForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_baichuan.BaiChuanConfig",
7
+ "AutoModelForCausalLM": "modeling_baichuan.BaiChuanForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2560,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 8704,
15
+ "num_kv_heads": 4,
16
+ "max_position_embeddings": 5000,
17
+ "model_max_length": 5000,
18
+ "model_type": "baichuan",
19
+ "num_attention_heads": 20,
20
+ "num_hidden_layers": 32,
21
+ "pad_token_id": 0,
22
+ "rms_norm_eps": 1e-06,
23
+ "_from_model_config": true,
24
+ "tie_word_embeddings": false,
25
+ "torch_dtype": "bfloat16",
26
+ "transformers_version": "4.29.2",
27
+ "use_cache": true,
28
+ "vocab_size": 48000
29
+ }
configuration_baichuan.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class BaiChuanConfig(PretrainedConfig):
27
+ model_type = "baichuan"
28
+ keys_to_ignore_at_inference = ["past_key_values"]
29
+
30
+ def __init__(
31
+ self,
32
+ vocab_size=64000,
33
+ hidden_size=4096,
34
+ intermediate_size=11008,
35
+ num_hidden_layers=32,
36
+ num_attention_heads=32,
37
+ hidden_act="silu",
38
+ max_position_embeddings=4096,
39
+ num_kv_heads=8,
40
+ mha_layers=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 45,
41
+ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
42
+ initializer_range=0.02,
43
+ rms_norm_eps=1e-6,
44
+ use_cache=True,
45
+ pad_token_id=0,
46
+ bos_token_id=1,
47
+ eos_token_id=2,
48
+ tie_word_embeddings=False,
49
+ **kwargs,
50
+ ):
51
+ self.mha_layers = mha_layers
52
+ self.num_kv_heads = num_kv_heads
53
+ self.vocab_size = vocab_size
54
+ self.max_position_embeddings = max_position_embeddings
55
+ self.hidden_size = hidden_size
56
+ self.intermediate_size = intermediate_size
57
+ self.num_hidden_layers = num_hidden_layers
58
+ self.num_attention_heads = num_attention_heads
59
+ self.hidden_act = hidden_act
60
+ self.initializer_range = initializer_range
61
+ self.rms_norm_eps = rms_norm_eps
62
+ self.use_cache = use_cache
63
+ super().__init__(
64
+ pad_token_id=pad_token_id,
65
+ bos_token_id=bos_token_id,
66
+ eos_token_id=eos_token_id,
67
+ tie_word_embeddings=tie_word_embeddings,
68
+ **kwargs,
69
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pad_token_id": 0,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "user_token_id": 195,
6
+ "assistant_token_id": 196,
7
+ "max_new_tokens": 2048,
8
+ "temperature": 0.3,
9
+ "top_k": 5,
10
+ "top_p": 0.85,
11
+ "repetition_penalty": 1.05,
12
+ "do_sample": false,
13
+ "transformers_version": "4.29.2"
14
+ }
generation_utils.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from queue import Queue
3
+
4
+ import torch
5
+
6
+
7
+ def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
8
+ def _parse_messages(messages, split_role="user"):
9
+ system, rounds = "", []
10
+ round = []
11
+ for i, message in enumerate(messages):
12
+ if message["role"] == "system":
13
+ assert i == 0
14
+ system = message["content"]
15
+ continue
16
+ if message["role"] == split_role and round:
17
+ rounds.append(round)
18
+ round = []
19
+ round.append(message)
20
+ if round:
21
+ rounds.append(round)
22
+ return system, rounds
23
+
24
+ max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
25
+ max_input_tokens = model.config.model_max_length - max_new_tokens
26
+ system, rounds = _parse_messages(messages, split_role="user")
27
+ system_tokens = tokenizer.encode(system)
28
+ max_history_tokens = max_input_tokens - len(system_tokens)
29
+
30
+ history_tokens = []
31
+ for round in rounds[::-1]:
32
+ round_tokens = []
33
+ for message in round:
34
+ if message["role"] == "user":
35
+ round_tokens.append(model.generation_config.user_token_id)
36
+ else:
37
+ round_tokens.append(model.generation_config.assistant_token_id)
38
+ round_tokens.extend(tokenizer.encode(message["content"]))
39
+ if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
40
+ history_tokens = round_tokens + history_tokens # concat left
41
+ if len(history_tokens) < max_history_tokens:
42
+ continue
43
+ break
44
+
45
+ input_tokens = system_tokens + history_tokens
46
+ if messages[-1]["role"] != "assistant":
47
+ input_tokens.append(model.generation_config.assistant_token_id)
48
+ input_tokens = input_tokens[-max_input_tokens:] # truncate left
49
+ return torch.LongTensor([input_tokens]).to(model.device)
50
+
51
+
52
+ class TextIterStreamer:
53
+ def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):
54
+ self.tokenizer = tokenizer
55
+ self.skip_prompt = skip_prompt
56
+ self.skip_special_tokens = skip_special_tokens
57
+ self.tokens = []
58
+ self.text_queue = Queue()
59
+ self.next_tokens_are_prompt = True
60
+
61
+ def put(self, value):
62
+ if self.skip_prompt and self.next_tokens_are_prompt:
63
+ self.next_tokens_are_prompt = False
64
+ else:
65
+ if len(value.shape) > 1:
66
+ value = value[0]
67
+ self.tokens.extend(value.tolist())
68
+ self.text_queue.put(
69
+ self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))
70
+
71
+ def end(self):
72
+ self.text_queue.put(None)
73
+
74
+ def __iter__(self):
75
+ return self
76
+
77
+ def __next__(self):
78
+ value = self.text_queue.get()
79
+ if value is None:
80
+ raise StopIteration()
81
+ else:
82
+ return value
83
+
modeling_baichuan.py ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ import math
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ from torch import nn
25
+ import torch.nn.functional as F
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+ import torch.utils.checkpoint
28
+ from transformers import PreTrainedModel, add_start_docstrings
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
31
+ from transformers.modeling_outputs import SequenceClassifierOutputWithPast
32
+ from transformers.utils import logging, add_start_docstrings_to_model_forward, replace_return_docstrings
33
+ from transformers.configuration_utils import PretrainedConfig
34
+ from einops import rearrange, repeat
35
+ from .configuration_baichuan import BaiChuanConfig
36
+
37
+ logger = logging.get_logger(__name__)
38
+ HAS_FLASH_ATTN = False
39
+ try:
40
+ from flash_attn import flash_attn_varlen_func, flash_attn_with_kvcache, flash_attn_func
41
+ from flash_attn.layers.rotary import apply_rotary_emb_func
42
+
43
+ HAS_FLASH_ATTN = True
44
+ except ImportError:
45
+ logger.warning(
46
+ "flash-attention is not installed correctly. "
47
+ )
48
+
49
+
50
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
51
+ def _make_causal_mask(
52
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
53
+ ):
54
+ """
55
+ Make causal mask used for bi-directional self-attention.
56
+ """
57
+ bsz, tgt_len = input_ids_shape
58
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
59
+ mask_cond = torch.arange(mask.size(-1), device=device)
60
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
61
+ mask = mask.to(dtype)
62
+
63
+ if past_key_values_length > 0:
64
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
65
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
66
+
67
+
68
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
69
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
70
+ """
71
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
72
+ """
73
+ bsz, src_len = mask.size()
74
+ tgt_len = tgt_len if tgt_len is not None else src_len
75
+
76
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
77
+
78
+ inverted_mask = 1.0 - expanded_mask
79
+
80
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
81
+
82
+
83
+ class RMSNorm(nn.Module):
84
+ def __init__(self, hidden_size, eps=1e-6):
85
+ """
86
+ RMSNorm is equivalent to T5LayerNorm
87
+ """
88
+ super().__init__()
89
+ self.weight = nn.Parameter(torch.ones(hidden_size))
90
+ self.variance_epsilon = eps
91
+
92
+ def forward(self, hidden_states):
93
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+
96
+ # convert into half-precision if necessary
97
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
98
+ hidden_states = hidden_states.to(self.weight.dtype)
99
+
100
+ return self.weight * hidden_states
101
+
102
+
103
+ class RotaryEmbedding(torch.nn.Module):
104
+ def __init__(self, dim, max_position_embeddings=2048, base=1e6, device=None, interleaved=False):
105
+ super().__init__()
106
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
107
+ self.base = base
108
+ self.dim = dim
109
+ # Build here to make `torch.jit.trace` work.
110
+ self.max_seq_len_cached = 0
111
+ self.interleaved = interleaved
112
+
113
+ def forward(self, q, k, seqlen_offset=None):
114
+ # x: [bs, num_attention_heads, seq_len, head_size]
115
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
116
+
117
+ seq_len = q.shape[1] + seqlen_offset
118
+ if seq_len > self.max_seq_len_cached:
119
+ self.max_seq_len_cached = seq_len
120
+ self.inv_freq = 1.0 / (
121
+ self.base ** (torch.arange(0, self.dim, 2).float().to(self.inv_freq.device) / self.dim))
122
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
123
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq) # dont use this, bug in fp16
124
+ freqs = torch.outer(t, self.inv_freq)
125
+ self.cos_cached = freqs.cos().to(q.device)
126
+ self.sin_cached = freqs.sin().to(k.device)
127
+
128
+ return apply_rotary_emb_func(
129
+ q.float(), self.cos_cached[seqlen_offset:], self.sin_cached[seqlen_offset:],
130
+ self.interleaved, True # inplace=True
131
+ ).to(q.dtype), apply_rotary_emb_func(
132
+ k.float(), self.cos_cached[seqlen_offset:], self.sin_cached[seqlen_offset:],
133
+ self.interleaved, True # inplace=True
134
+ ).to(k.dtype)
135
+
136
+
137
+ class MLP(nn.Module):
138
+ def __init__(
139
+ self,
140
+ hidden_size: int,
141
+ intermediate_size: int,
142
+ hidden_act: str,
143
+ ):
144
+ super().__init__()
145
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
146
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
147
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
148
+ self.act_fn = ACT2FN[hidden_act]
149
+
150
+ def forward(self, x):
151
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
152
+
153
+ def custom_convolution(U, K):
154
+ """
155
+ U: 输入矩阵, 形状为 (bs, seq, h, d)
156
+ K: 卷积核, 形状为 (w, h)
157
+ 返回: 输出矩阵 V, 形状为 (bs, seq, h, d)
158
+ """
159
+ h, w = K.shape
160
+ padding = (w - 1, 0)
161
+ U_padded = F.pad(U, (0, 0, 0, 0, *padding)) # 形状变为 (bs, seq+w-1, h, d)
162
+ U_unfolded = U_padded.unfold(1, w, 1) # 形状变为 (bs, seq+w-1, h, d, w)
163
+ K = K.unsqueeze(0).unsqueeze(0).unsqueeze(-2)
164
+ V_unfolded = U_unfolded * K # 形状保持为 (bs, seq, h, d, w)
165
+ V = V_unfolded.sum(dim=-1) # 形状变为 (bs, seq, h, d)
166
+ return V
167
+ class Attention(nn.Module):
168
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
169
+
170
+ def __init__(self, config: BaiChuanConfig, num_heads):
171
+ super().__init__()
172
+ self.config = config
173
+ # print(num_heads)
174
+ self.num_heads = config.num_attention_heads
175
+ self.head_dim = config.hidden_size // config.num_attention_heads
176
+ self.hidden_size = config.hidden_size
177
+ self.max_position_embeddings = config.max_position_embeddings
178
+ self.num_kv_heads = config.num_kv_heads
179
+ self.W_pack = nn.Linear(config.hidden_size, self.hidden_size + 2 * self.num_kv_heads * self.head_dim,
180
+ bias=False)
181
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
182
+ self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
183
+ self.cos, self.sin = None, None
184
+ self.window = 2
185
+ self.K = nn.Parameter(torch.softmax(torch.randn((self.num_kv_heads,self.window)),dim=-1))
186
+ self.V = nn.Parameter(torch.softmax(torch.randn((self.num_kv_heads,self.window)),dim=-1))
187
+ def forward(
188
+ self,
189
+ hidden_states: torch.Tensor,
190
+ attention_mask: Optional[torch.Tensor] = None,
191
+ position_ids: Optional[torch.LongTensor] = None,
192
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
193
+ output_attentions: bool = False,
194
+ use_cache: bool = False,
195
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
196
+
197
+ bsz, seqlen_q, _ = hidden_states.size()
198
+ past_len = 0
199
+ attn_weights = None
200
+ if past_key_value is not None:
201
+ cache_k, cache_v, past_len = past_key_value
202
+ new_len = past_len + hidden_states.size(1)
203
+ if new_len > cache_k.size(1):
204
+ cache_k = torch.cat([cache_k,
205
+ torch.empty(bsz, 256, cache_k.size(2), cache_k.size(3), dtype=cache_k.dtype,
206
+ device=cache_k.device)], 1)
207
+ cache_v = torch.cat([cache_v,
208
+ torch.empty(bsz, 256, cache_v.size(2), cache_v.size(3), dtype=cache_v.dtype,
209
+ device=cache_v.device)], 1)
210
+
211
+ proj = self.W_pack(hidden_states)
212
+
213
+ proj = rearrange(proj, 'bs seq_len (n_head head_dim) -> n_head bs seq_len head_dim', head_dim=self.head_dim)
214
+ q = rearrange(proj[:self.num_heads], 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
215
+ k = rearrange(proj[self.num_heads:self.num_heads + self.num_kv_heads],
216
+ 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
217
+ v = rearrange(proj[self.num_heads + self.num_kv_heads:],
218
+ 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
219
+
220
+ # proj = rearrange(proj, 'bs seq_len (qkv n_head head_dim) -> qkv bs seq_len n_head head_dim',
221
+ # head_dim=self.head_dim, n_head=self.num_heads)
222
+ # q, k, v = proj
223
+ if past_key_value is None:
224
+ k = custom_convolution(k, self.K)
225
+ v = custom_convolution(v, self.V)
226
+ self.last_k = k[:,-1:]
227
+ self.last_v = v[:,-1:]
228
+ else:
229
+ self.last_k,k = k, self.K[:,:1]*self.last_k + self.K[:,1:]*k
230
+ self.last_v,v = v, self.V[:,:1]*self.last_v + self.V[:,1:]*v
231
+ q, k = self.rotary_emb(q, k, seqlen_offset=past_len)
232
+
233
+ if HAS_FLASH_ATTN and q.dtype != torch.float32:
234
+ if past_key_value is not None:
235
+ attn_output = flash_attn_with_kvcache(
236
+ q,
237
+ cache_k,
238
+ cache_v,
239
+ k,
240
+ v,
241
+ causal=False,
242
+ cache_seqlens=past_len
243
+ )
244
+ else:
245
+ attn_outputs = flash_attn_func(
246
+ q,
247
+ k,
248
+ v,
249
+ causal=True,
250
+ return_attn_probs=output_attentions
251
+ )
252
+ attn_output = attn_outputs[0] if output_attentions else attn_outputs
253
+ attn_weights = attn_outputs[2] if output_attentions else None
254
+ else: # fallback to pytorch impl
255
+ if past_key_value is not None:
256
+ cache_k[:, past_len:new_len] = k
257
+ cache_v[:, past_len:new_len] = v
258
+ attn_output = F.scaled_dot_product_attention(
259
+ q.transpose(1, 2),
260
+ cache_k[:, :new_len].transpose(1, 2),
261
+ cache_v[:, :new_len].transpose(1, 2),
262
+ attn_mask=attention_mask
263
+ )
264
+ else:
265
+ attn_output = F.scaled_dot_product_attention(
266
+ q.transpose(1, 2),
267
+ k.transpose(1, 2),
268
+ v.transpose(1, 2),
269
+ attn_mask=attention_mask
270
+ )
271
+ attn_output = attn_output.transpose(1, 2)
272
+ if use_cache:
273
+ if past_key_value is not None:
274
+ past_key_value = (cache_k, cache_v, past_len + seqlen_q)
275
+ else:
276
+ past_key_value = (k, v, seqlen_q)
277
+
278
+ attn_output = attn_output.reshape(bsz, seqlen_q, self.hidden_size)
279
+ attn_output = self.o_proj(attn_output)
280
+ return attn_output, attn_weights, past_key_value
281
+
282
+
283
+ class DecoderLayer(nn.Module):
284
+ def __init__(self, config: BaiChuanConfig, num_heads):
285
+ super().__init__()
286
+ self.hidden_size = config.hidden_size
287
+ self.self_attn = Attention(config=config, num_heads=num_heads)
288
+ self.mlp = MLP(
289
+ hidden_size=self.hidden_size,
290
+ intermediate_size=config.intermediate_size,
291
+ hidden_act=config.hidden_act,
292
+ )
293
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
294
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
295
+
296
+ def forward(
297
+ self,
298
+ hidden_states: torch.Tensor,
299
+ attention_mask: Optional[torch.Tensor] = None,
300
+ position_ids: Optional[torch.LongTensor] = None,
301
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
302
+ output_attentions: Optional[bool] = False,
303
+ use_cache: Optional[bool] = False,
304
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
305
+ """
306
+ Args:
307
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
308
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
309
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
310
+ output_attentions (`bool`, *optional*):
311
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
312
+ returned tensors for more detail.
313
+ use_cache (`bool`, *optional*):
314
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
315
+ (see `past_key_values`).
316
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
317
+ """
318
+
319
+ residual = hidden_states
320
+
321
+ hidden_states = self.input_layernorm(hidden_states)
322
+
323
+ # Self Attention
324
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
325
+ hidden_states=hidden_states,
326
+ attention_mask=attention_mask,
327
+ position_ids=position_ids,
328
+ past_key_value=past_key_value,
329
+ output_attentions=output_attentions,
330
+ use_cache=use_cache,
331
+ )
332
+ hidden_states = residual + hidden_states
333
+
334
+ # Fully Connected
335
+ residual = hidden_states
336
+ hidden_states = self.post_attention_layernorm(hidden_states)
337
+ hidden_states = self.mlp(hidden_states)
338
+ hidden_states = residual + hidden_states
339
+
340
+ outputs = (hidden_states,)
341
+
342
+ if output_attentions:
343
+ outputs += (self_attn_weights,)
344
+
345
+ if use_cache:
346
+ outputs += (present_key_value,)
347
+
348
+ return outputs
349
+
350
+
351
+ class PreTrainedModel(PreTrainedModel):
352
+ config_class = BaiChuanConfig
353
+ base_model_prefix = "model"
354
+ supports_gradient_checkpointing = True
355
+ _no_split_modules = ["DecoderLayer"]
356
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
357
+
358
+ def _init_weights(self, module):
359
+ std = self.config.initializer_range
360
+ if isinstance(module, nn.Linear):
361
+ module.weight.data.normal_(mean=0.0, std=std)
362
+ if module.bias is not None:
363
+ module.bias.data.zero_()
364
+ elif isinstance(module, nn.Embedding):
365
+ module.weight.data.normal_(mean=0.0, std=std)
366
+ if module.padding_idx is not None:
367
+ module.weight.data[module.padding_idx].zero_()
368
+
369
+ def _set_gradient_checkpointing(self, module, value=False):
370
+ if isinstance(module, Model):
371
+ module.gradient_checkpointing = value
372
+
373
+
374
+ class Model(PreTrainedModel):
375
+ """
376
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DecoderLayer`]
377
+
378
+ Args:
379
+ config: BaiChuanConfig
380
+ """
381
+
382
+ def __init__(self, config: BaiChuanConfig):
383
+ super().__init__(config)
384
+ self.padding_idx = config.pad_token_id
385
+ self.vocab_size = config.vocab_size
386
+
387
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
388
+ self.layers = nn.ModuleList([DecoderLayer(config, num_heads=self.get_num_heads(layer_id)) for layer_id in
389
+ range(config.num_hidden_layers)])
390
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
391
+
392
+ self.gradient_checkpointing = False
393
+ # Initialize weights and apply final processing
394
+ self.post_init()
395
+ def get_num_heads(self, layer_index: int):
396
+ return self.config.num_attention_heads
397
+ if 0 <= layer_index < self.config.num_hidden_layers // 4 or layer_index == self.config.num_hidden_layers-1:
398
+ return 8
399
+ elif self.config.num_hidden_layers // 4 <= layer_index < self.config.num_hidden_layers // 2:
400
+ return 4
401
+ elif self.config.num_hidden_layers // 2 <= layer_index < self.config.num_hidden_layers*3 // 4:
402
+ return 2
403
+ else:
404
+ return 1
405
+ def get_input_embeddings(self):
406
+ return self.embed_tokens
407
+
408
+ def set_input_embeddings(self, value):
409
+ self.embed_tokens = value
410
+
411
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
412
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
413
+ # create causal mask
414
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
415
+ combined_attention_mask = None
416
+ if input_shape[-1] > 1:
417
+ combined_attention_mask = _make_causal_mask(
418
+ input_shape,
419
+ inputs_embeds.dtype,
420
+ device=inputs_embeds.device,
421
+ past_key_values_length=past_key_values_length,
422
+ )
423
+
424
+ if attention_mask is not None:
425
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
426
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
427
+ inputs_embeds.device
428
+ )
429
+ combined_attention_mask = (
430
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
431
+ )
432
+
433
+ return combined_attention_mask
434
+
435
+ def forward(
436
+ self,
437
+ input_ids: torch.LongTensor = None,
438
+ attention_mask: Optional[torch.Tensor] = None,
439
+ position_ids: Optional[torch.LongTensor] = None,
440
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
441
+ inputs_embeds: Optional[torch.FloatTensor] = None,
442
+ use_cache: Optional[bool] = None,
443
+ output_attentions: Optional[bool] = None,
444
+ output_hidden_states: Optional[bool] = None,
445
+ return_dict: Optional[bool] = None,
446
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
447
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
448
+ output_hidden_states = (
449
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
450
+ )
451
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
452
+
453
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
454
+
455
+ # retrieve input_ids and inputs_embeds
456
+ if input_ids is not None and inputs_embeds is not None:
457
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
458
+ elif input_ids is not None:
459
+ batch_size, seq_length = input_ids.shape
460
+ elif inputs_embeds is not None:
461
+ batch_size, seq_length, _ = inputs_embeds.shape
462
+ else:
463
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
464
+
465
+ seq_length_with_past = seq_length
466
+ past_key_values_length = 0
467
+
468
+ if past_key_values is not None:
469
+ past_key_values_length = past_key_values[0][0].shape[2]
470
+ seq_length_with_past = seq_length_with_past + past_key_values_length
471
+
472
+ if position_ids is None:
473
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
474
+ position_ids = torch.arange(
475
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
476
+ )
477
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
478
+ else:
479
+ position_ids = position_ids.view(-1, seq_length).long()
480
+
481
+ if inputs_embeds is None:
482
+ inputs_embeds = self.embed_tokens(input_ids)
483
+ # embed positions
484
+ if attention_mask is None:
485
+ attention_mask = torch.ones(
486
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
487
+ )
488
+ attention_mask = self._prepare_decoder_attention_mask(
489
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
490
+ )
491
+
492
+ hidden_states = inputs_embeds
493
+
494
+ if self.gradient_checkpointing and self.training:
495
+ if use_cache:
496
+ logger.warning_once(
497
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
498
+ )
499
+ use_cache = False
500
+
501
+ # decoder layers
502
+ all_hidden_states = () if output_hidden_states else None
503
+ all_self_attns = () if output_attentions else None
504
+ next_decoder_cache = () if use_cache else None
505
+
506
+ for idx, decoder_layer in enumerate(self.layers):
507
+ if output_hidden_states:
508
+ all_hidden_states += (hidden_states,)
509
+
510
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
511
+
512
+ if self.gradient_checkpointing and self.training:
513
+
514
+ def create_custom_forward(module):
515
+ def custom_forward(*inputs):
516
+ # None for past_key_value
517
+ return module(*inputs, output_attentions, None)
518
+
519
+ return custom_forward
520
+
521
+ layer_outputs = torch.utils.checkpoint.checkpoint(
522
+ create_custom_forward(decoder_layer),
523
+ hidden_states,
524
+ attention_mask,
525
+ position_ids,
526
+ None,
527
+ )
528
+ else:
529
+ layer_outputs = decoder_layer(
530
+ hidden_states,
531
+ attention_mask=attention_mask,
532
+ position_ids=position_ids,
533
+ past_key_value=past_key_value,
534
+ output_attentions=output_attentions,
535
+ use_cache=use_cache,
536
+ )
537
+
538
+ hidden_states = layer_outputs[0]
539
+
540
+ if use_cache:
541
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
542
+
543
+ if output_attentions:
544
+ all_self_attns += (layer_outputs[1],)
545
+
546
+ hidden_states = self.norm(hidden_states)
547
+
548
+ # add hidden states from the last decoder layer
549
+ if output_hidden_states:
550
+ all_hidden_states += (hidden_states,)
551
+
552
+ next_cache = next_decoder_cache if use_cache else None
553
+ if not return_dict:
554
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
555
+ return BaseModelOutputWithPast(
556
+ last_hidden_state=hidden_states,
557
+ past_key_values=next_cache,
558
+ hidden_states=all_hidden_states,
559
+ attentions=all_self_attns,
560
+ )
561
+
562
+
563
+ class NormHead(nn.Module):
564
+ def __init__(self, hidden_size, vocab_size, bias=False):
565
+ super().__init__()
566
+ self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
567
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
568
+
569
+ def forward(self, hidden_states):
570
+ norm_weight = nn.functional.normalize(self.weight)
571
+ return nn.functional.linear(hidden_states, norm_weight)
572
+
573
+
574
+ class BaiChuanForCausalLM(PreTrainedModel):
575
+ def __init__(self, config):
576
+ super().__init__(config)
577
+ self.model = Model(config)
578
+
579
+ # self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
580
+ self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
581
+
582
+ # Initialize weights and apply final processing
583
+ self.post_init()
584
+
585
+ def get_input_embeddings(self):
586
+ return self.model.embed_tokens
587
+
588
+ def set_input_embeddings(self, value):
589
+ self.model.embed_tokens = value
590
+
591
+ def get_output_embeddings(self):
592
+ return self.lm_head
593
+
594
+ def set_output_embeddings(self, new_embeddings):
595
+ self.lm_head = new_embeddings
596
+
597
+ def set_decoder(self, decoder):
598
+ self.model = decoder
599
+
600
+ def get_decoder(self):
601
+ return self.model
602
+
603
+ def forward(
604
+ self,
605
+ input_ids: torch.LongTensor = None,
606
+ attention_mask: Optional[torch.Tensor] = None,
607
+ position_ids: Optional[torch.LongTensor] = None,
608
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
609
+ inputs_embeds: Optional[torch.FloatTensor] = None,
610
+ labels: Optional[torch.LongTensor] = None,
611
+ use_cache: Optional[bool] = None,
612
+ output_attentions: Optional[bool] = None,
613
+ output_hidden_states: Optional[bool] = None,
614
+ return_dict: Optional[bool] = None,
615
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
616
+ r"""
617
+ Args:
618
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
619
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
620
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
621
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
622
+
623
+ Returns:
624
+
625
+ Example:
626
+
627
+ ```python
628
+ >>> from transformers import AutoTokenizer, ModelForCausalLM
629
+
630
+ >>> model = ModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
631
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
632
+
633
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
634
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
635
+
636
+ >>> # Generate
637
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
638
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
639
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
640
+ ```"""
641
+ # use_cache = False
642
+
643
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
644
+ output_hidden_states = (
645
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
646
+ )
647
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
648
+
649
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
650
+ outputs = self.model(
651
+ input_ids=input_ids,
652
+ attention_mask=attention_mask,
653
+ position_ids=position_ids,
654
+ past_key_values=past_key_values,
655
+ inputs_embeds=inputs_embeds,
656
+ use_cache=use_cache,
657
+ output_attentions=output_attentions,
658
+ output_hidden_states=output_hidden_states,
659
+ return_dict=return_dict,
660
+ )
661
+
662
+ hidden_states = outputs[0]
663
+ logits = self.lm_head(hidden_states)
664
+
665
+ loss = None
666
+ if labels is not None:
667
+ # Shift so that tokens < n predict n
668
+ shift_logits = logits[..., :-1, :].contiguous()
669
+ shift_labels = labels[..., 1:].contiguous()
670
+ # Flatten the tokens
671
+ loss_fct = CrossEntropyLoss()
672
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
673
+ shift_labels = shift_labels.view(-1)
674
+ # Enable model parallelism
675
+ shift_labels = shift_labels.to(shift_logits.device)
676
+ loss = loss_fct(shift_logits, shift_labels)
677
+
678
+ if not return_dict:
679
+ output = (logits,) + outputs[1:]
680
+ return (loss,) + output if loss is not None else output
681
+
682
+ return CausalLMOutputWithPast(
683
+ loss=loss,
684
+ logits=logits,
685
+ past_key_values=outputs.past_key_values,
686
+ hidden_states=outputs.hidden_states,
687
+ attentions=outputs.attentions,
688
+ )
689
+
690
+ def prepare_inputs_for_generation(
691
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
692
+ ):
693
+ if past_key_values:
694
+ input_ids = input_ids[:, -1:]
695
+ position_ids = kwargs.get("position_ids", None)
696
+
697
+ if attention_mask is not None and position_ids is None:
698
+ # create position_ids on the fly for batch generation
699
+ position_ids = attention_mask.long().cumsum(-1) - 1
700
+ position_ids.masked_fill_(attention_mask == 0, 1)
701
+ if past_key_values:
702
+ position_ids = position_ids[:, -1].unsqueeze(-1)
703
+
704
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
705
+ if inputs_embeds is not None and past_key_values is None:
706
+ model_inputs = {"inputs_embeds": inputs_embeds}
707
+ else:
708
+ model_inputs = {"input_ids": input_ids}
709
+
710
+ model_inputs.update(
711
+ {
712
+ "position_ids": position_ids,
713
+ "past_key_values": past_key_values,
714
+ "use_cache": kwargs.get("use_cache"),
715
+ "attention_mask": attention_mask,
716
+ }
717
+ )
718
+ return model_inputs
719
+
720
+ @staticmethod
721
+ def _reorder_cache(past_key_values, beam_idx):
722
+ reordered_past = ()
723
+ for layer_past in past_key_values:
724
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
725
+ return reordered_past
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9031be7f80f4af5395e87400cb76a68c7664fddee01d4666b5258c73c7bbb4c3
3
+ size 5776732467
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenization_baichuan.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Baichuan Inc. All Rights Reserved.
2
+
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import os
23
+ from shutil import copyfile
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ import sentencepiece as spm
27
+
28
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
29
+ from transformers.utils import logging
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
35
+
36
+ PRETRAINED_VOCAB_FILES_MAP = {
37
+ "vocab_file": {},
38
+ "tokenizer_file": {},
39
+ }
40
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
41
+
42
+
43
+ class BaichuanTokenizer(PreTrainedTokenizer):
44
+ """
45
+ Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
46
+
47
+ Args:
48
+ vocab_file (`str`):
49
+ Path to the vocabulary file.
50
+ """
51
+
52
+ vocab_files_names = VOCAB_FILES_NAMES
53
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
54
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
55
+ model_input_names = ["input_ids", "attention_mask"]
56
+
57
+ def __init__(
58
+ self,
59
+ vocab_file,
60
+ unk_token="<unk>",
61
+ bos_token="<s>",
62
+ eos_token="</s>",
63
+ pad_token=None,
64
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
65
+ add_bos_token=True,
66
+ add_eos_token=False,
67
+ clean_up_tokenization_spaces=False,
68
+ **kwargs,
69
+ ):
70
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
71
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
72
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
73
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
74
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
75
+ self.vocab_file = vocab_file
76
+ self.add_bos_token = add_bos_token
77
+ self.add_eos_token = add_eos_token
78
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
79
+ self.sp_model.Load(vocab_file)
80
+ super().__init__(
81
+ bos_token=bos_token,
82
+ eos_token=eos_token,
83
+ unk_token=unk_token,
84
+ pad_token=pad_token,
85
+ add_bos_token=add_bos_token,
86
+ add_eos_token=add_eos_token,
87
+ sp_model_kwargs=self.sp_model_kwargs,
88
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
89
+ **kwargs,
90
+ )
91
+
92
+ def __getstate__(self):
93
+ state = self.__dict__.copy()
94
+ state["sp_model"] = None
95
+ return state
96
+
97
+ def __setstate__(self, d):
98
+ self.__dict__ = d
99
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
100
+ self.sp_model.Load(self.vocab_file)
101
+
102
+ @property
103
+ def vocab_size(self):
104
+ """Returns vocab size"""
105
+ return self.sp_model.get_piece_size()
106
+
107
+ def get_vocab(self):
108
+ """Returns vocab as a dict"""
109
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
110
+ vocab.update(self.added_tokens_encoder)
111
+ return vocab
112
+
113
+ def _tokenize(self, text):
114
+ """Returns a tokenized string."""
115
+ return self.sp_model.encode(text, out_type=str)
116
+
117
+ def _convert_token_to_id(self, token):
118
+ """Converts a token (str) in an id using the vocab."""
119
+ return self.sp_model.piece_to_id(token)
120
+
121
+ def _convert_id_to_token(self, index):
122
+ """Converts an index (integer) in a token (str) using the vocab."""
123
+ token = self.sp_model.IdToPiece(index)
124
+ return token
125
+
126
+ def convert_tokens_to_string(self, tokens):
127
+ """Converts a sequence of tokens (string) in a single string."""
128
+ current_sub_tokens = []
129
+ out_string = ""
130
+ prev_is_special = False
131
+ for i, token in enumerate(tokens):
132
+ # make sure that special tokens are not decoded using sentencepiece model
133
+ if token in self.all_special_tokens:
134
+ if not prev_is_special and i != 0:
135
+ out_string += " "
136
+ out_string += self.sp_model.decode(current_sub_tokens) + token
137
+ prev_is_special = True
138
+ current_sub_tokens = []
139
+ else:
140
+ current_sub_tokens.append(token)
141
+ prev_is_special = False
142
+ out_string += self.sp_model.decode(current_sub_tokens)
143
+ return out_string
144
+
145
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
146
+ """
147
+ Save the vocabulary and special tokens file to a directory.
148
+
149
+ Args:
150
+ save_directory (`str`):
151
+ The directory in which to save the vocabulary.
152
+
153
+ Returns:
154
+ `Tuple(str)`: Paths to the files saved.
155
+ """
156
+ if not os.path.isdir(save_directory):
157
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
158
+ return
159
+ out_vocab_file = os.path.join(
160
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
161
+ )
162
+
163
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
164
+ copyfile(self.vocab_file, out_vocab_file)
165
+ elif not os.path.isfile(self.vocab_file):
166
+ with open(out_vocab_file, "wb") as fi:
167
+ content_spiece_model = self.sp_model.serialized_model_proto()
168
+ fi.write(content_spiece_model)
169
+
170
+ return (out_vocab_file,)
171
+
172
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
173
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
174
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
175
+
176
+ output = bos_token_id + token_ids_0 + eos_token_id
177
+
178
+ if token_ids_1 is not None:
179
+ output = output + bos_token_id + token_ids_1 + eos_token_id
180
+
181
+ return output
182
+
183
+ def get_special_tokens_mask(
184
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
185
+ ) -> List[int]:
186
+ """
187
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
188
+ special tokens using the tokenizer `prepare_for_model` method.
189
+
190
+ Args:
191
+ token_ids_0 (`List[int]`):
192
+ List of IDs.
193
+ token_ids_1 (`List[int]`, *optional*):
194
+ Optional second list of IDs for sequence pairs.
195
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
196
+ Whether or not the token list is already formatted with special tokens for the model.
197
+
198
+ Returns:
199
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
200
+ """
201
+ if already_has_special_tokens:
202
+ return super().get_special_tokens_mask(
203
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
204
+ )
205
+
206
+ bos_token_id = [1] if self.add_bos_token else []
207
+ eos_token_id = [1] if self.add_eos_token else []
208
+
209
+ if token_ids_1 is None:
210
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
211
+ return (
212
+ bos_token_id
213
+ + ([0] * len(token_ids_0))
214
+ + eos_token_id
215
+ + bos_token_id
216
+ + ([0] * len(token_ids_1))
217
+ + eos_token_id
218
+ )
219
+
220
+ def create_token_type_ids_from_sequences(
221
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
222
+ ) -> List[int]:
223
+ """
224
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
225
+ sequence pair mask has the following format:
226
+
227
+ ```
228
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
229
+ | first sequence | second sequence |
230
+ ```
231
+
232
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
233
+
234
+ Args:
235
+ token_ids_0 (`List[int]`):
236
+ List of ids.
237
+ token_ids_1 (`List[int]`, *optional*):
238
+ Optional second list of IDs for sequence pairs.
239
+
240
+ Returns:
241
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
242
+ """
243
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
244
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
245
+
246
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
247
+
248
+ if token_ids_1 is not None:
249
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
250
+
251
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf77124b06b5e70920cd455a482f79271a39bec14b75d466cd0b27a6bf82b308
3
+ size 1118898
tokenizer_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": ["tokenization_baichuan.BaichuanTokenizer", null]
4
+ },
5
+ "add_bos_token": false,
6
+ "add_eos_token": false,
7
+ "use_fast": false,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": {
10
+ "__type": "AddedToken",
11
+ "content": "</s>",
12
+ "lstrip": false,
13
+ "normalized": true,
14
+ "rstrip": false,
15
+ "single_word": true
16
+ },
17
+ "model_max_length": 4000,
18
+ "sp_model_kwargs": {},
19
+ "tokenizer_class": "BaichuanTokenizer",
20
+ "pad_token": {
21
+ "__type": "AddedToken",
22
+ "content": "<unk>",
23
+ "lstrip": false,
24
+ "normalized": true,
25
+ "rstrip": false,
26
+ "single_word": true
27
+ },
28
+ "unk_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": true
35
+ }
36
+ }