rrustlee commited on
Commit
e1b9f1e
1 Parent(s): c8bb579

commit from morecry

Browse files
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "_name_or_path": "baichuan-inc/Baichuan2-13B-Base",
4
+ "architectures": [
5
+ "BaichuanRM"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "baichuan-inc/Baichuan2-13B-Base--configuration_baichuan.BaichuanConfig",
9
+ "AutoModelForCausalLM": "baichuan-inc/Baichuan2-13B-Base--modeling_baichuan.BaichuanForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 5120,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 13696,
17
+ "model_max_length": 4096,
18
+ "model_type": "baichuan",
19
+ "num_attention_heads": 40,
20
+ "num_hidden_layers": 40,
21
+ "pad_token_id": 0,
22
+ "rms_norm_eps": 1e-06,
23
+ "tie_word_embeddings": false,
24
+ "tokenizer_class": "BaichuanTokenizer",
25
+ "torch_dtype": "bfloat16",
26
+ "transformers_version": "4.30.2",
27
+ "use_cache": false,
28
+ "vocab_size": 125696
29
+ }
configuration_baichuan.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+ class BaichuanConfig(PretrainedConfig):
6
+ model_type = "baichuan"
7
+ keys_to_ignore_at_inference = ["past_key_values"]
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=64000,
12
+ hidden_size=5120,
13
+ intermediate_size=13696,
14
+ num_hidden_layers=40,
15
+ num_attention_heads=40,
16
+ hidden_act="silu",
17
+ model_max_length=4096,
18
+ initializer_range=0.02,
19
+ rms_norm_eps=1e-6,
20
+ use_cache=True,
21
+ pad_token_id=0,
22
+ bos_token_id=1,
23
+ eos_token_id=2,
24
+ tie_word_embeddings=False,
25
+ gradient_checkpointing=False,
26
+ **kwargs,
27
+ ):
28
+ self.vocab_size = vocab_size
29
+ self.model_max_length = model_max_length
30
+ self.hidden_size = hidden_size
31
+ self.intermediate_size = intermediate_size
32
+ self.num_hidden_layers = num_hidden_layers
33
+ self.num_attention_heads = num_attention_heads
34
+ self.hidden_act = hidden_act
35
+ self.initializer_range = initializer_range
36
+ self.rms_norm_eps = rms_norm_eps
37
+ self.use_cache = use_cache
38
+ self.gradient_checkpointing = gradient_checkpointing,
39
+ super().__init__(
40
+ pad_token_id=pad_token_id,
41
+ bos_token_id=bos_token_id,
42
+ eos_token_id=eos_token_id,
43
+ tie_word_embeddings=tie_word_embeddings,
44
+ **kwargs,
45
+ )
46
+
modeling_baichuan.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
+
3
+ from .configuration_baichuan import BaichuanConfig
4
+ # from .generation_utils import build_chat_input, TextIterStreamer
5
+
6
+ import math
7
+ from threading import Thread
8
+ from typing import List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import CrossEntropyLoss
13
+ from torch.nn import functional as F
14
+ from transformers import PreTrainedModel, PretrainedConfig
15
+ from transformers.activations import ACT2FN
16
+ from transformers.generation.utils import GenerationConfig
17
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
18
+ from transformers.utils import logging, ContextManagers
19
+
20
+ import os
21
+ from contextlib import contextmanager
22
+ from accelerate import init_empty_weights
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ try:
27
+ from xformers import ops as xops
28
+ except ImportError:
29
+ xops = None
30
+ logger.warning(
31
+ "Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers."
32
+ )
33
+
34
+
35
+ def _get_interleave(n):
36
+ def _get_interleave_power_of_2(n):
37
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
38
+ ratio = start
39
+ return [start * ratio**i for i in range(n)]
40
+
41
+ if math.log2(n).is_integer():
42
+ return _get_interleave_power_of_2(n)
43
+ else:
44
+ closest_power_of_2 = 2 ** math.floor(math.log2(n))
45
+ return (
46
+ _get_interleave_power_of_2(closest_power_of_2)
47
+ + _get_interleave(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
48
+ )
49
+
50
+
51
+ def _fill_with_neg_inf(t):
52
+ """FP16-compatible function that fills a tensor with -inf."""
53
+ return t.float().fill_(float("-inf")).type_as(t)
54
+
55
+
56
+ def _buffered_future_mask(tensor, maxpos, alibi, attn_heads):
57
+ _future_mask = torch.triu(_fill_with_neg_inf(torch.zeros([maxpos, maxpos])), 1)
58
+ _future_mask = _future_mask.unsqueeze(0) + alibi
59
+ new_future_mask = _future_mask.to(tensor)
60
+ return new_future_mask[: tensor.shape[0] * attn_heads, :maxpos, :maxpos]
61
+
62
+
63
+ def _gen_alibi_mask(tensor, n_head, max_pos):
64
+ slopes = torch.Tensor(_get_interleave(n_head))
65
+ position_point = torch.arange(max_pos) - max_pos + 1
66
+ position_point = position_point.unsqueeze(0).unsqueeze(0).expand(n_head, -1, -1)
67
+ diag = torch.diag(position_point[0])
68
+ position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(-1, -2)
69
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
70
+ alibi = alibi.view(n_head, 1, max_pos)
71
+ alibi_mask = torch.triu(_fill_with_neg_inf(torch.zeros([max_pos, max_pos])), 1)
72
+ alibi_mask = alibi_mask.unsqueeze(0) + alibi
73
+ return alibi_mask
74
+
75
+
76
+ class RMSNorm(torch.nn.Module):
77
+ def __init__(self, hidden_size, epsilon=1e-6):
78
+ super().__init__()
79
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size))
80
+ self.epsilon = epsilon
81
+
82
+ def forward(self, hidden_states):
83
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
84
+ hidden_states = hidden_states * torch.rsqrt(variance + self.epsilon)
85
+
86
+ # convert into half-precision
87
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
88
+ hidden_states = hidden_states.to(self.weight.dtype)
89
+
90
+ return self.weight * hidden_states
91
+
92
+
93
+ class MLP(torch.nn.Module):
94
+ def __init__(
95
+ self,
96
+ hidden_size: int,
97
+ intermediate_size: int,
98
+ hidden_act: str,
99
+ ):
100
+ super().__init__()
101
+ self.gate_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
102
+ self.down_proj = torch.nn.Linear(intermediate_size, hidden_size, bias=False)
103
+ self.up_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
104
+ self.act_fn = ACT2FN[hidden_act]
105
+
106
+ def forward(self, x):
107
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
108
+
109
+
110
+ class BaichuanAttention(torch.nn.Module):
111
+ def __init__(self, config: BaichuanConfig):
112
+ super().__init__()
113
+ self.config = config
114
+ self.hidden_size = config.hidden_size
115
+ self.num_heads = config.num_attention_heads
116
+ self.head_dim = self.hidden_size // self.num_heads
117
+ self.max_position_embeddings = config.model_max_length
118
+
119
+ if (self.head_dim * self.num_heads) != self.hidden_size:
120
+ raise ValueError(
121
+ f"hidden_size {self.hidden_size} is not divisible by num_heads {self.num_heads}"
122
+ )
123
+ self.W_pack = torch.nn.Linear(
124
+ self.hidden_size, 3 * self.hidden_size, bias=False
125
+ )
126
+ self.o_proj = torch.nn.Linear(
127
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
128
+ )
129
+
130
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
131
+ return (
132
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
133
+ .transpose(1, 2)
134
+ .contiguous()
135
+ )
136
+
137
+ def forward(
138
+ self,
139
+ hidden_states: torch.Tensor,
140
+ attention_mask: Optional[torch.Tensor] = None,
141
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
142
+ output_attentions: bool = False,
143
+ use_cache: bool = False,
144
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
145
+ bsz, q_len, _ = hidden_states.size()
146
+
147
+ proj = self.W_pack(hidden_states)
148
+ proj = (
149
+ proj.unflatten(-1, (3, self.hidden_size))
150
+ .unsqueeze(0)
151
+ .transpose(0, -2)
152
+ .squeeze(-2)
153
+ )
154
+ query_states = (
155
+ proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
156
+ )
157
+ key_states = (
158
+ proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
159
+ )
160
+ value_states = (
161
+ proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
162
+ )
163
+
164
+ kv_seq_len = key_states.shape[-2]
165
+ if past_key_value is not None:
166
+ kv_seq_len += past_key_value[0].shape[-2]
167
+
168
+ if past_key_value is not None:
169
+ # reuse k, v, self_attention
170
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
171
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
172
+
173
+ past_key_value = (key_states, value_states) if use_cache else None
174
+ if xops is not None and self.training:
175
+ attn_weights = None
176
+ # query_states = query_states.transpose(1, 2)
177
+ # key_states = key_states.transpose(1, 2)
178
+ # value_states = value_states.transpose(1, 2)
179
+ # attn_output = xops.memory_efficient_attention(
180
+ # query_states, key_states, value_states, attn_bias=attention_mask
181
+ # )
182
+ with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
183
+ attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
184
+ attn_output = attn_output.transpose(1, 2)
185
+ else:
186
+ attn_weights = torch.matmul(
187
+ query_states, key_states.transpose(2, 3)
188
+ ) / math.sqrt(self.head_dim)
189
+
190
+ if attention_mask is not None:
191
+ if q_len == 1: # inference with cache
192
+ if len(attention_mask.size()) == 4:
193
+ attention_mask = attention_mask[:, :, -1:, :]
194
+ else:
195
+ attention_mask = attention_mask[:, -1:, :]
196
+ attn_weights = attn_weights + attention_mask
197
+ attn_weights = torch.max(
198
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
199
+ )
200
+
201
+ attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
202
+ attn_output = torch.matmul(attn_weights, value_states)
203
+
204
+ attn_output = attn_output.transpose(1, 2)
205
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
206
+ attn_output = self.o_proj(attn_output)
207
+
208
+ if not output_attentions:
209
+ attn_weights = None
210
+
211
+ return attn_output, attn_weights, past_key_value
212
+
213
+
214
+ class BaichuanLayer(torch.nn.Module):
215
+ def __init__(self, config: BaichuanConfig):
216
+ super().__init__()
217
+ self.hidden_size = config.hidden_size
218
+ self.self_attn = BaichuanAttention(config=config)
219
+ self.mlp = MLP(
220
+ hidden_size=self.hidden_size,
221
+ intermediate_size=config.intermediate_size,
222
+ hidden_act=config.hidden_act,
223
+ )
224
+ self.input_layernorm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
225
+ self.post_attention_layernorm = RMSNorm(
226
+ config.hidden_size, epsilon=config.rms_norm_eps
227
+ )
228
+
229
+ def forward(
230
+ self,
231
+ hidden_states: torch.Tensor,
232
+ attention_mask: Optional[torch.Tensor] = None,
233
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
234
+ output_attentions: Optional[bool] = False,
235
+ use_cache: Optional[bool] = False,
236
+ ) -> Tuple[
237
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
238
+ ]:
239
+ residual = hidden_states
240
+
241
+ hidden_states = self.input_layernorm(hidden_states)
242
+
243
+ # Self Attention
244
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
245
+ hidden_states=hidden_states,
246
+ attention_mask=attention_mask,
247
+ past_key_value=past_key_value,
248
+ output_attentions=output_attentions,
249
+ use_cache=use_cache,
250
+ )
251
+ hidden_states = residual + hidden_states
252
+
253
+ # Fully Connected
254
+ residual = hidden_states
255
+ hidden_states = self.post_attention_layernorm(hidden_states)
256
+ hidden_states = self.mlp(hidden_states)
257
+ hidden_states = residual + hidden_states
258
+
259
+ outputs = (hidden_states,)
260
+
261
+ if use_cache:
262
+ outputs += (present_key_value,)
263
+
264
+ return outputs
265
+
266
+
267
+ class BaichuanPreTrainedModel(PreTrainedModel):
268
+ config_class = BaichuanConfig
269
+ base_model_prefix = "model"
270
+ supports_gradient_checkpointing = True
271
+ _no_split_modules = ["BaichuanLayer"]
272
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
273
+
274
+ def _init_weights(self, module):
275
+ std = self.config.initializer_range
276
+ if isinstance(module, torch.nn.Linear):
277
+ module.weight.data.normal_(mean=0.0, std=std)
278
+ if module.bias is not None:
279
+ module.bias.data.zero_()
280
+ elif isinstance(module, torch.nn.Embedding):
281
+ module.weight.data.normal_(mean=0.0, std=std)
282
+ if module.padding_idx is not None:
283
+ module.weight.data[module.padding_idx].zero_()
284
+
285
+ def _set_gradient_checkpointing(self, module, value=False):
286
+ if isinstance(module, BaichuanModel):
287
+ module.gradient_checkpointing = value
288
+
289
+
290
+ class BaichuanModel(BaichuanPreTrainedModel):
291
+ def __init__(self, config: BaichuanConfig):
292
+ super().__init__(config)
293
+ self.padding_idx = config.pad_token_id
294
+ self.vocab_size = config.vocab_size
295
+ self.n_head = config.num_attention_heads
296
+ self.embed_tokens = torch.nn.Embedding(
297
+ config.vocab_size, config.hidden_size, self.padding_idx
298
+ )
299
+ self.layers = torch.nn.ModuleList(
300
+ [BaichuanLayer(config) for _ in range(config.num_hidden_layers)]
301
+ )
302
+ self.norm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
303
+
304
+ self.gradient_checkpointing = config.gradient_checkpointing
305
+ self.post_init()
306
+ self.max_cache_pos = config.model_max_length
307
+ self.first_run = True
308
+ self.alibi_mask = None
309
+
310
+ def get_input_embeddings(self):
311
+ return self.embed_tokens
312
+
313
+ def set_input_embeddings(self, value):
314
+ self.embed_tokens = value
315
+
316
+ def get_alibi_mask(self, tensor, seq_length_with_past):
317
+ if self.training:
318
+ slopes = torch.Tensor(_get_interleave(self.n_head))
319
+ position_point = (
320
+ torch.arange(seq_length_with_past) - seq_length_with_past + 1
321
+ )
322
+ position_point = (
323
+ position_point.unsqueeze(0)
324
+ .unsqueeze(0)
325
+ .expand(self.n_head, seq_length_with_past, -1)
326
+ )
327
+ diag = torch.diag(position_point[0])
328
+ position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(
329
+ -1, -2
330
+ )
331
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
332
+ mask = _buffered_future_mask(
333
+ tensor, seq_length_with_past, alibi, self.n_head
334
+ )
335
+ else:
336
+ if self.first_run:
337
+ self.first_run = False
338
+ self.register_buffer(
339
+ "future_mask",
340
+ _gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
341
+ tensor
342
+ ),
343
+ persistent=False,
344
+ )
345
+ if seq_length_with_past > self.max_cache_pos:
346
+ self.max_cache_pos = seq_length_with_past
347
+ self.register_buffer(
348
+ "future_mask",
349
+ _gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
350
+ tensor
351
+ ),
352
+ persistent=False,
353
+ )
354
+ mask = self.future_mask[
355
+ : self.n_head, :seq_length_with_past, :seq_length_with_past
356
+ ]
357
+ return mask
358
+
359
+ def forward(
360
+ self,
361
+ input_ids: torch.LongTensor = None,
362
+ attention_mask: Optional[torch.Tensor] = None,
363
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
364
+ inputs_embeds: Optional[torch.FloatTensor] = None,
365
+ use_cache: Optional[bool] = False,
366
+ output_attentions: Optional[bool] = False,
367
+ output_hidden_states: Optional[bool] = False,
368
+ return_dict: Optional[bool] = None,
369
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
370
+ if input_ids is not None and inputs_embeds is not None:
371
+ raise ValueError(
372
+ "You cannot provide both input_ids and inputs_embeds simultaneously"
373
+ )
374
+ elif input_ids is not None:
375
+ batch_size, seq_length = input_ids.shape
376
+ elif inputs_embeds is not None:
377
+ batch_size, seq_length, _ = inputs_embeds.shape
378
+ else:
379
+ raise ValueError("You need to provide input_ids or inputs_embeds")
380
+
381
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
382
+
383
+ return_dict = (
384
+ return_dict if return_dict is not None else self.config.use_return_dict
385
+ )
386
+
387
+ seq_length_with_past = seq_length
388
+
389
+ if past_key_values is not None:
390
+ past_key_values_length = past_key_values[0][0].shape[2]
391
+ seq_length_with_past = seq_length_with_past + past_key_values_length
392
+
393
+ if inputs_embeds is None:
394
+ inputs_embeds = self.embed_tokens(input_ids)
395
+
396
+ if self.training:
397
+ if (
398
+ self.alibi_mask is None
399
+ or self.alibi_mask.shape[-1] != seq_length_with_past
400
+ ):
401
+ self.alibi_mask = self.get_alibi_mask(
402
+ inputs_embeds, seq_length_with_past
403
+ )
404
+ alibi_mask = self.alibi_mask
405
+ else:
406
+ alibi_mask = self.get_alibi_mask(inputs_embeds, seq_length_with_past)
407
+
408
+ if attention_mask is not None:
409
+ if len(attention_mask.shape) == 2:
410
+ expanded_mask = attention_mask.to(alibi_mask.dtype)
411
+ expanded_mask = torch.tril(
412
+ torch.gt(expanded_mask[:, :, None] * expanded_mask[:, None, :], 0)
413
+ ) * torch.eq(expanded_mask[:, :, None] - expanded_mask[:, None, :], 0)
414
+ else:
415
+ expanded_mask = attention_mask
416
+ bsz = inputs_embeds.size(0)
417
+ src_len, tgt_len = alibi_mask.size()[-2:]
418
+ expanded_mask = (
419
+ expanded_mask.unsqueeze(1)
420
+ .expand(bsz, 1, src_len, tgt_len)
421
+ .to(alibi_mask.dtype)
422
+ )
423
+ inverted_mask = 1.0 - expanded_mask
424
+ inverted_mask = inverted_mask.masked_fill(
425
+ inverted_mask.to(torch.bool), torch.finfo(alibi_mask.dtype).min
426
+ )
427
+ attention_mask = inverted_mask + alibi_mask.unsqueeze(0)
428
+ else:
429
+ attention_mask = alibi_mask
430
+
431
+ hidden_states = inputs_embeds
432
+
433
+ if self.gradient_checkpointing and self.training:
434
+ if use_cache:
435
+ logger.warning_once(
436
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
437
+ )
438
+ use_cache = False
439
+
440
+ # decoder layers
441
+ all_hidden_states = () if output_hidden_states else None
442
+ all_self_attns = () if output_attentions else None
443
+ next_decoder_cache = () if use_cache else None
444
+
445
+ for idx, decoder_layer in enumerate(self.layers):
446
+ if output_hidden_states:
447
+ all_hidden_states += (hidden_states,)
448
+
449
+ past_key_value = (
450
+ past_key_values[idx] if past_key_values is not None else None
451
+ )
452
+
453
+ if self.gradient_checkpointing and self.training:
454
+
455
+ def create_custom_forward(module):
456
+ def custom_forward(*inputs):
457
+ # None for past_key_value
458
+ return module(*inputs, output_attentions, None)
459
+
460
+ return custom_forward
461
+
462
+ layer_outputs = torch.utils.checkpoint.checkpoint(
463
+ create_custom_forward(decoder_layer),
464
+ hidden_states,
465
+ attention_mask,
466
+ None,
467
+ )
468
+ else:
469
+ layer_outputs = decoder_layer(
470
+ hidden_states,
471
+ attention_mask=attention_mask,
472
+ past_key_value=past_key_value,
473
+ output_attentions=output_attentions,
474
+ use_cache=use_cache,
475
+ )
476
+
477
+ hidden_states = layer_outputs[0]
478
+
479
+ if use_cache:
480
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
481
+
482
+ if output_attentions:
483
+ all_self_attns += (layer_outputs[1],)
484
+
485
+ hidden_states = self.norm(hidden_states)
486
+
487
+ # add hidden states from the last decoder layer
488
+ if output_hidden_states:
489
+ all_hidden_states += (hidden_states,)
490
+
491
+ next_cache = next_decoder_cache if use_cache else None
492
+ if not return_dict:
493
+ return tuple(
494
+ v
495
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
496
+ if v is not None
497
+ )
498
+ return BaseModelOutputWithPast(
499
+ last_hidden_state=hidden_states,
500
+ past_key_values=next_cache,
501
+ hidden_states=all_hidden_states,
502
+ attentions=all_self_attns,
503
+ )
504
+
505
+
506
+ class NormHead(nn.Module):
507
+ def __init__(self, hidden_size, vocab_size, bias=False):
508
+ super().__init__()
509
+ self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
510
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
511
+ self.first_flag = True
512
+
513
+ def forward(self, hidden_states):
514
+ if self.training:
515
+ norm_weight = nn.functional.normalize(self.weight)
516
+ self.first_flag = True
517
+ elif self.first_flag:
518
+ self.first_flag = False
519
+ self.weight = nn.Parameter(nn.functional.normalize(self.weight))
520
+ norm_weight = self.weight
521
+ else:
522
+ norm_weight = self.weight
523
+ return nn.functional.linear(hidden_states, norm_weight)
524
+
525
+ _init_weights = True
526
+ @contextmanager
527
+ def no_init_weights(_enable=True):
528
+ global _init_weights
529
+ old_init_weights = _init_weights
530
+ if _enable:
531
+ _init_weights = False
532
+ try:
533
+ yield
534
+ finally:
535
+ _init_weights = old_init_weights
536
+
537
+
538
+ class BaichuanCharRM(BaichuanPreTrainedModel):
539
+ def __init__(self, config):
540
+ super().__init__(config)
541
+ self.model = BaichuanModel(config)
542
+ self.score = nn.Linear(config.hidden_size, 1, bias=True)
543
+ # Initialize weights and apply final processing
544
+ self.post_init()
545
+
546
+ def get_input_embeddings(self):
547
+ return self.model.embed_tokens
548
+
549
+ def set_input_embeddings(self, value):
550
+ self.model.embed_tokens = value
551
+
552
+
553
+ def forward(
554
+ self,
555
+ input_ids: torch.LongTensor = None,
556
+ attention_mask: Optional[torch.Tensor] = None,
557
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
558
+ inputs_embeds: Optional[torch.FloatTensor] = None,
559
+ labels: Optional[torch.LongTensor] = None,
560
+ use_cache: Optional[bool] = None,
561
+ output_attentions: Optional[bool] = None,
562
+ output_hidden_states: Optional[bool] = None,
563
+ return_dict: Optional[bool] = None,
564
+ ):
565
+ r"""
566
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
567
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
568
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
569
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
570
+ """
571
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
572
+
573
+ transformer_outputs = self.model(
574
+ input_ids,
575
+ attention_mask=attention_mask,
576
+ past_key_values=past_key_values,
577
+ inputs_embeds=inputs_embeds,
578
+ use_cache=use_cache,
579
+ output_attentions=output_attentions,
580
+ output_hidden_states=output_hidden_states,
581
+ return_dict=return_dict,
582
+ )
583
+ hidden_states = transformer_outputs[0]
584
+
585
+ hidden_states = hidden_states[:, -1, :]
586
+ # logits = F.sigmoid(self.score(hidden_states)).squeeze()
587
+ logits = F.sigmoid(self.score(hidden_states).squeeze())
588
+
589
+ loss = None
590
+ if labels is not None:
591
+ labels = labels.type_as(logits)
592
+ loss_fct = nn.MSELoss()
593
+ loss = loss_fct(logits.view(-1), labels.view(-1)/4)
594
+
595
+ # logits = logits.view(-1, 2)
596
+ # loss_fct_1 = nn.MSELoss()
597
+ # loss_fct_2 = nn.LogSoftmax(dim=-1)
598
+ # loss_1 = loss_fct_1(logits[:,0], labels)
599
+ # loss_2 = -torch.mean(loss_fct_2(logits)[:,1])
600
+ # loss = loss_1 + loss_2
601
+ return loss, logits
pytorch_model-00001-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c868e1bdccfe16392538d8020ef3f27ccf74b47cfca3c867617e8a8e0f2aa700
3
+ size 9973568983
pytorch_model-00002-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e0681ed449fb183d836920340c791e3bb3351c5f031011d05f11322d0d77b912
3
+ size 9947421360
pytorch_model-00003-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:942a5e7322a87a7fb3c609db97c177f5e8835109a38c8dea01953c5c88e68dab
3
+ size 6585330193
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 26506219522
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00003.bin",
7
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
8
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
9
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
10
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
11
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
12
+ "model.layers.0.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
13
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
14
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
15
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
16
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
17
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
18
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
19
+ "model.layers.1.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
20
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
21
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
22
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
23
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
24
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
25
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
26
+ "model.layers.10.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
27
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
28
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
29
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
30
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
31
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
32
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
33
+ "model.layers.11.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
34
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
35
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
36
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
37
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
38
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
39
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
40
+ "model.layers.12.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
41
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
42
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
43
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
44
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
45
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
46
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
47
+ "model.layers.13.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
48
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
49
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
50
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
51
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
52
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
53
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
54
+ "model.layers.14.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
55
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
56
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
57
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
58
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
59
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
60
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
61
+ "model.layers.15.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
62
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
63
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
64
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
65
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
66
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
67
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
68
+ "model.layers.16.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
69
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
70
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
71
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
72
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
73
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
74
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
75
+ "model.layers.17.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
76
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
77
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
78
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
79
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
80
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
81
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
82
+ "model.layers.18.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
83
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
84
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
85
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
86
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
87
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
88
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
89
+ "model.layers.19.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
90
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
91
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
92
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
93
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
94
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
95
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
96
+ "model.layers.2.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
97
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
98
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
99
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
100
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
101
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
102
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
103
+ "model.layers.20.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
104
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
105
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
106
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
107
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
108
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
109
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
110
+ "model.layers.21.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
111
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
112
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
113
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
114
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
115
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
116
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
117
+ "model.layers.22.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
118
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
119
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
120
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
121
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
122
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
123
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
124
+ "model.layers.23.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
125
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
126
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
127
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
128
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
129
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
130
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
131
+ "model.layers.24.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
132
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
133
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
134
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
135
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
136
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
137
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
138
+ "model.layers.25.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
139
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
140
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
141
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
142
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
143
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
144
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
145
+ "model.layers.26.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
146
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
147
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
148
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
149
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
150
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
151
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
152
+ "model.layers.27.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
153
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
154
+ "model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
155
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
156
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
157
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
158
+ "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
159
+ "model.layers.28.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
160
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
161
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
162
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
163
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
164
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
165
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
166
+ "model.layers.29.self_attn.W_pack.weight": "pytorch_model-00002-of-00003.bin",
167
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
168
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
169
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
170
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
171
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
172
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
173
+ "model.layers.3.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
174
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
175
+ "model.layers.30.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
176
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
177
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
178
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
179
+ "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
180
+ "model.layers.30.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
181
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
182
+ "model.layers.31.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
183
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
184
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
185
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
186
+ "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
187
+ "model.layers.31.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
188
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
189
+ "model.layers.32.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
190
+ "model.layers.32.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
191
+ "model.layers.32.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
192
+ "model.layers.32.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
193
+ "model.layers.32.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
194
+ "model.layers.32.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
195
+ "model.layers.32.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
196
+ "model.layers.33.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
197
+ "model.layers.33.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
198
+ "model.layers.33.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
199
+ "model.layers.33.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
200
+ "model.layers.33.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
201
+ "model.layers.33.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
202
+ "model.layers.33.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
203
+ "model.layers.34.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
204
+ "model.layers.34.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
205
+ "model.layers.34.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
206
+ "model.layers.34.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
207
+ "model.layers.34.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
208
+ "model.layers.34.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
209
+ "model.layers.34.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
210
+ "model.layers.35.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
211
+ "model.layers.35.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
212
+ "model.layers.35.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
213
+ "model.layers.35.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
214
+ "model.layers.35.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
215
+ "model.layers.35.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
216
+ "model.layers.35.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
217
+ "model.layers.36.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
218
+ "model.layers.36.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
219
+ "model.layers.36.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
220
+ "model.layers.36.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
221
+ "model.layers.36.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
222
+ "model.layers.36.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
223
+ "model.layers.36.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
224
+ "model.layers.37.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
225
+ "model.layers.37.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
226
+ "model.layers.37.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
227
+ "model.layers.37.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
228
+ "model.layers.37.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
229
+ "model.layers.37.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
230
+ "model.layers.37.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
231
+ "model.layers.38.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
232
+ "model.layers.38.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
233
+ "model.layers.38.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
234
+ "model.layers.38.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
235
+ "model.layers.38.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
236
+ "model.layers.38.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
237
+ "model.layers.38.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
238
+ "model.layers.39.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
239
+ "model.layers.39.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
240
+ "model.layers.39.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
241
+ "model.layers.39.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
242
+ "model.layers.39.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
243
+ "model.layers.39.self_attn.W_pack.weight": "pytorch_model-00003-of-00003.bin",
244
+ "model.layers.39.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
245
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
246
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
247
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
248
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
249
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
250
+ "model.layers.4.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
251
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
252
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
253
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
254
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
255
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
256
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
257
+ "model.layers.5.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
258
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
259
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
260
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
261
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
262
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
263
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
264
+ "model.layers.6.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
265
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
266
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
267
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
268
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
269
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
270
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
271
+ "model.layers.7.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
272
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
273
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
274
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
275
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
276
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
277
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
278
+ "model.layers.8.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
279
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
280
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
281
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
282
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
283
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
284
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
285
+ "model.layers.9.self_attn.W_pack.weight": "pytorch_model-00001-of-00003.bin",
286
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
287
+ "model.norm.weight": "pytorch_model-00003-of-00003.bin",
288
+ "score.bias": "pytorch_model-00003-of-00003.bin",
289
+ "score.weight": "pytorch_model-00003-of-00003.bin"
290
+ }
291
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": true
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": true
15
+ },
16
+ "pad_token": "</s>",
17
+ "unk_token": {
18
+ "content": "<unk>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": true
23
+ }
24
+ }
tokenization_baichuan.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
+
3
+ import os
4
+ from shutil import copyfile
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ import sentencepiece as spm
8
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
9
+ from transformers.utils import logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
15
+
16
+ PRETRAINED_VOCAB_FILES_MAP = {
17
+ "vocab_file": {},
18
+ "tokenizer_file": {},
19
+ }
20
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
21
+
22
+
23
+ class BaichuanTokenizer(PreTrainedTokenizer):
24
+ """
25
+ Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
26
+
27
+ Args:
28
+ vocab_file (`str`):
29
+ Path to the vocabulary file.
30
+ """
31
+
32
+ vocab_files_names = VOCAB_FILES_NAMES
33
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
34
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
35
+ model_input_names = ["input_ids", "attention_mask"]
36
+
37
+ def __init__(
38
+ self,
39
+ vocab_file,
40
+ unk_token="<unk>",
41
+ bos_token="<s>",
42
+ eos_token="</s>",
43
+ pad_token=None,
44
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
45
+ add_bos_token=True,
46
+ add_eos_token=False,
47
+ clean_up_tokenization_spaces=False,
48
+ **kwargs,
49
+ ):
50
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
51
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
52
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
53
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
54
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
55
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
56
+ self.sp_model.Load(vocab_file)
57
+ super().__init__(
58
+ bos_token=bos_token,
59
+ eos_token=eos_token,
60
+ unk_token=unk_token,
61
+ pad_token=pad_token,
62
+ add_bos_token=add_bos_token,
63
+ add_eos_token=add_eos_token,
64
+ sp_model_kwargs=self.sp_model_kwargs,
65
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
66
+ **kwargs,
67
+ )
68
+ self.vocab_file = vocab_file
69
+ self.add_bos_token = add_bos_token
70
+ self.add_eos_token = add_eos_token
71
+
72
+ def __getstate__(self):
73
+ state = self.__dict__.copy()
74
+ state["sp_model"] = None
75
+ return state
76
+
77
+ def __setstate__(self, d):
78
+ self.__dict__ = d
79
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
80
+ self.sp_model.Load(self.vocab_file)
81
+
82
+ @property
83
+ def vocab_size(self):
84
+ """Returns vocab size"""
85
+ return self.sp_model.get_piece_size()
86
+
87
+ def get_vocab(self):
88
+ """Returns vocab as a dict"""
89
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
90
+ vocab.update(self.added_tokens_encoder)
91
+ return vocab
92
+
93
+ def _tokenize(self, text):
94
+ """Returns a tokenized string."""
95
+ return self.sp_model.encode(text, out_type=str)
96
+
97
+ def _convert_token_to_id(self, token):
98
+ """Converts a token (str) in an id using the vocab."""
99
+ return self.sp_model.piece_to_id(token)
100
+
101
+ def _convert_id_to_token(self, index):
102
+ """Converts an index (integer) in a token (str) using the vocab."""
103
+ token = self.sp_model.IdToPiece(index)
104
+ return token
105
+
106
+ def convert_tokens_to_string(self, tokens):
107
+ """Converts a sequence of tokens (string) in a single string."""
108
+ current_sub_tokens = []
109
+ out_string = ""
110
+ prev_is_special = False
111
+ for i, token in enumerate(tokens):
112
+ # make sure that special tokens are not decoded using sentencepiece model
113
+ if token in self.all_special_tokens:
114
+ if not prev_is_special and i != 0:
115
+ out_string += " "
116
+ out_string += self.sp_model.decode(current_sub_tokens) + token
117
+ prev_is_special = True
118
+ current_sub_tokens = []
119
+ else:
120
+ current_sub_tokens.append(token)
121
+ prev_is_special = False
122
+ out_string += self.sp_model.decode(current_sub_tokens)
123
+ return out_string
124
+
125
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
126
+ """
127
+ Save the vocabulary and special tokens file to a directory.
128
+
129
+ Args:
130
+ save_directory (`str`):
131
+ The directory in which to save the vocabulary.
132
+
133
+ Returns:
134
+ `Tuple(str)`: Paths to the files saved.
135
+ """
136
+ if not os.path.isdir(save_directory):
137
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
138
+ return
139
+ out_vocab_file = os.path.join(
140
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
141
+ )
142
+
143
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
144
+ copyfile(self.vocab_file, out_vocab_file)
145
+ elif not os.path.isfile(self.vocab_file):
146
+ with open(out_vocab_file, "wb") as fi:
147
+ content_spiece_model = self.sp_model.serialized_model_proto()
148
+ fi.write(content_spiece_model)
149
+
150
+ return (out_vocab_file,)
151
+
152
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
153
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
154
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
155
+
156
+ output = bos_token_id + token_ids_0 + eos_token_id
157
+
158
+ if token_ids_1 is not None:
159
+ output = output + bos_token_id + token_ids_1 + eos_token_id
160
+
161
+ return output
162
+
163
+ def get_special_tokens_mask(
164
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
165
+ ) -> List[int]:
166
+ """
167
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
168
+ special tokens using the tokenizer `prepare_for_model` method.
169
+
170
+ Args:
171
+ token_ids_0 (`List[int]`):
172
+ List of IDs.
173
+ token_ids_1 (`List[int]`, *optional*):
174
+ Optional second list of IDs for sequence pairs.
175
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
176
+ Whether or not the token list is already formatted with special tokens for the model.
177
+
178
+ Returns:
179
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
180
+ """
181
+ if already_has_special_tokens:
182
+ return super().get_special_tokens_mask(
183
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
184
+ )
185
+
186
+ bos_token_id = [1] if self.add_bos_token else []
187
+ eos_token_id = [1] if self.add_eos_token else []
188
+
189
+ if token_ids_1 is None:
190
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
191
+ return (
192
+ bos_token_id
193
+ + ([0] * len(token_ids_0))
194
+ + eos_token_id
195
+ + bos_token_id
196
+ + ([0] * len(token_ids_1))
197
+ + eos_token_id
198
+ )
199
+
200
+ def create_token_type_ids_from_sequences(
201
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
202
+ ) -> List[int]:
203
+ """
204
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
205
+ sequence pair mask has the following format:
206
+
207
+ ```
208
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
209
+ | first sequence | second sequence |
210
+ ```
211
+
212
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
213
+
214
+ Args:
215
+ token_ids_0 (`List[int]`):
216
+ List of ids.
217
+ token_ids_1 (`List[int]`, *optional*):
218
+ Optional second list of IDs for sequence pairs.
219
+
220
+ Returns:
221
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
222
+ """
223
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
224
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
225
+
226
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
227
+
228
+ if token_ids_1 is not None:
229
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
230
+
231
+ return output
232
+
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79452955be6b419a65984273a9f08af86042e1c2a75ee3ba989cbf620a133cc2
3
+ size 2001107
tokenizer_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "baichuan-inc/Baichuan2-13B-Base--tokenization_baichuan.BaichuanTokenizer",
7
+ null
8
+ ]
9
+ },
10
+ "bos_token": {
11
+ "__type": "AddedToken",
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": true,
15
+ "rstrip": false,
16
+ "single_word": true
17
+ },
18
+ "clean_up_tokenization_spaces": false,
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": true
26
+ },
27
+ "model_max_length": 4096,
28
+ "pad_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": true
35
+ },
36
+ "sp_model_kwargs": {},
37
+ "tokenizer_class": "BaichuanTokenizer",
38
+ "unk_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<unk>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": true
45
+ }
46
+ }