dododododo commited on
Commit
d62447a
1 Parent(s): aef7bfb

Create tokenization_baichuan.py

Browse files
Files changed (1) hide show
  1. tokenization_baichuan.py +244 -0
tokenization_baichuan.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Baichuan Inc. All Rights Reserved.
2
+
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import os
23
+ from shutil import copyfile
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ import sentencepiece as spm
27
+
28
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
29
+ from transformers.utils import logging
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
35
+
36
+ PRETRAINED_VOCAB_FILES_MAP = {
37
+ "vocab_file": {},
38
+ "tokenizer_file": {},
39
+ }
40
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
41
+
42
+
43
+ class BaichuanTokenizer(PreTrainedTokenizer):
44
+ """
45
+ Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
46
+ 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
+
75
+ self.vocab_file = vocab_file
76
+ self.add_bos_token = add_bos_token
77
+ self.add_eos_token = add_eos_token
78
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
79
+ self.sp_model.Load(vocab_file)
80
+
81
+ super().__init__(
82
+ bos_token=bos_token,
83
+ eos_token=eos_token,
84
+ unk_token=unk_token,
85
+ pad_token=pad_token,
86
+ add_bos_token=add_bos_token,
87
+ add_eos_token=add_eos_token,
88
+ sp_model_kwargs=self.sp_model_kwargs,
89
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
90
+ **kwargs,
91
+ )
92
+
93
+ def __getstate__(self):
94
+ state = self.__dict__.copy()
95
+ state["sp_model"] = None
96
+ return state
97
+
98
+ def __setstate__(self, d):
99
+ self.__dict__ = d
100
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
101
+ self.sp_model.Load(self.vocab_file)
102
+
103
+ @property
104
+ def vocab_size(self):
105
+ """Returns vocab size"""
106
+ return self.sp_model.get_piece_size()
107
+
108
+ def get_vocab(self):
109
+ """Returns vocab as a dict"""
110
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
111
+ vocab.update(self.added_tokens_encoder)
112
+ return vocab
113
+
114
+ def _tokenize(self, text):
115
+ """Returns a tokenized string."""
116
+ return self.sp_model.encode(text, out_type=str)
117
+
118
+ def _convert_token_to_id(self, token):
119
+ """Converts a token (str) in an id using the vocab."""
120
+ return self.sp_model.piece_to_id(token)
121
+
122
+ def _convert_id_to_token(self, index):
123
+ """Converts an index (integer) in a token (str) using the vocab."""
124
+ token = self.sp_model.IdToPiece(index)
125
+ return token
126
+
127
+ def convert_tokens_to_string(self, tokens):
128
+ """Converts a sequence of tokens (string) in a single string."""
129
+ current_sub_tokens = []
130
+ out_string = ""
131
+ prev_is_special = False
132
+ for i, token in enumerate(tokens):
133
+ # make sure that special tokens are not decoded using sentencepiece model
134
+ if token in self.all_special_tokens:
135
+ if not prev_is_special and i != 0:
136
+ out_string += " "
137
+ out_string += self.sp_model.decode(current_sub_tokens) + token
138
+ prev_is_special = True
139
+ current_sub_tokens = []
140
+ else:
141
+ current_sub_tokens.append(token)
142
+ prev_is_special = False
143
+ out_string += self.sp_model.decode(current_sub_tokens)
144
+ return out_string
145
+
146
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+ Args:
150
+ save_directory (`str`):
151
+ The directory in which to save the vocabulary.
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
+ Args:
189
+ token_ids_0 (`List[int]`):
190
+ List of IDs.
191
+ token_ids_1 (`List[int]`, *optional*):
192
+ Optional second list of IDs for sequence pairs.
193
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
194
+ Whether or not the token list is already formatted with special tokens for the model.
195
+ Returns:
196
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
197
+ """
198
+ if already_has_special_tokens:
199
+ return super().get_special_tokens_mask(
200
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
201
+ )
202
+
203
+ bos_token_id = [1] if self.add_bos_token else []
204
+ eos_token_id = [1] if self.add_eos_token else []
205
+
206
+ if token_ids_1 is None:
207
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
208
+ return (
209
+ bos_token_id
210
+ + ([0] * len(token_ids_0))
211
+ + eos_token_id
212
+ + bos_token_id
213
+ + ([0] * len(token_ids_1))
214
+ + eos_token_id
215
+ )
216
+
217
+ def create_token_type_ids_from_sequences(
218
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
219
+ ) -> List[int]:
220
+ """
221
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
222
+ sequence pair mask has the following format:
223
+ ```
224
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
225
+ | first sequence | second sequence |
226
+ ```
227
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
228
+ Args:
229
+ token_ids_0 (`List[int]`):
230
+ List of ids.
231
+ token_ids_1 (`List[int]`, *optional*):
232
+ Optional second list of IDs for sequence pairs.
233
+ Returns:
234
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
235
+ """
236
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
237
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
238
+
239
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
240
+
241
+ if token_ids_1 is not None:
242
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
243
+
244
+ return output