gmchuggingface commited on
Commit
541ddd4
1 Parent(s): 03dc0f2

第一个版本

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