manaestras commited on
Commit
d2838d9
·
verified ·
1 Parent(s): e6b755c

Upload tokenization_hy.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tokenization_hy.py +297 -0
tokenization_hy.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import logging
3
+ import os
4
+ import unicodedata
5
+ from typing import Collection, Dict, List, Set, Tuple, Union
6
+
7
+ import tiktoken
8
+ from transformers import PreTrainedTokenizer, AddedToken
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ VOCAB_FILES_NAMES = {"vocab_file": "hy.tiktoken"}
14
+
15
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
16
+ # PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
17
+ ENDOFTEXT = "<|endoftext|>"
18
+ STARTOFTEXT = "<|startoftext|>"
19
+ BOSTOKEN = "<|bos|>"
20
+ EOSTOKEN = "<|eos|>"
21
+ PADTOKEN = "<|pad|>"
22
+
23
+ # as the default behavior is changed to allow special tokens in
24
+ # regular texts, the surface forms of special tokens need to be
25
+ # as different as possible to minimize the impact
26
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
27
+ # changed to use actual index to avoid misconfiguration with vocabulary expansion
28
+
29
+
30
+ SPECIAL_START_ID = 127957
31
+
32
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
33
+ # with open(tiktoken_bpe_file, "rb", encoding="utf-8") as f:
34
+ # contents = f.read()
35
+ dic = {}
36
+ rank = 0
37
+ for line in open(tiktoken_bpe_file, "rb"):
38
+ if line:
39
+ token, _ = line.split()
40
+ if base64.b64decode(token) in dic:
41
+ continue
42
+ dic[base64.b64decode(token)] = int(rank)
43
+ rank += 1
44
+ global SPECIAL_START_ID
45
+ SPECIAL_START_ID=rank
46
+ return dic
47
+
48
+ # NOTE: Please use the code line to check `SPECIAL_START_ID` right, this will affect the SPECIAL_START_ID
49
+ # print(SPECIAL_START_ID)
50
+
51
+ SPECIAL_TOKENS = tuple(
52
+ enumerate(
53
+ (
54
+ (
55
+ ENDOFTEXT,
56
+ STARTOFTEXT,
57
+ BOSTOKEN,
58
+ EOSTOKEN,
59
+ PADTOKEN,
60
+ )
61
+ + EXTRAS
62
+ ),
63
+ start=SPECIAL_START_ID,
64
+ )
65
+ )
66
+ # NOTE: Unused Token ID starts from 127962
67
+ SPECIAL_TOKENS_SET = set(t for i, t in SPECIAL_TOKENS)
68
+
69
+ class HYTokenizer(PreTrainedTokenizer):
70
+ """hunyuan tokenizer."""
71
+
72
+ vocab_files_names = VOCAB_FILES_NAMES
73
+
74
+ def __init__(
75
+ self,
76
+ vocab_file,
77
+ errors="replace",
78
+ extra_vocab_file=None,
79
+ **kwargs,
80
+ ):
81
+ super().__init__(**kwargs)
82
+
83
+ # how to handle errors in decoding UTF-8 byte sequences
84
+ # use ignore if you are in streaming inference
85
+ self.errors = errors
86
+
87
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
88
+ self.special_tokens = {
89
+ token: index
90
+ for index, token in SPECIAL_TOKENS
91
+ }
92
+
93
+ # try load extra vocab from file
94
+ if extra_vocab_file is not None:
95
+ used_ids = set(self.mergeable_ranks.values()) | set(self.special_tokens.values())
96
+ extra_mergeable_ranks = _load_tiktoken_bpe(extra_vocab_file)
97
+ for token, index in extra_mergeable_ranks.items():
98
+ if token in self.mergeable_ranks:
99
+ logger.info(f"extra token {token} exists, skipping")
100
+ continue
101
+ if index in used_ids:
102
+ logger.info(f'the index {index} for extra token {token} exists, skipping')
103
+ continue
104
+ self.mergeable_ranks[token] = index
105
+ # the index may be sparse after this, but don't worry tiktoken.Encoding will handle this
106
+
107
+ enc = tiktoken.Encoding(
108
+ "HunYuan",
109
+ pat_str=PAT_STR,
110
+ mergeable_ranks=self.mergeable_ranks,
111
+ special_tokens=self.special_tokens,
112
+ )
113
+ assert (
114
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
115
+ ), f"{len(self.mergeable_ranks)} + {len(self.special_tokens)} != {enc.n_vocab} in encoding"
116
+
117
+ self.decoder = {
118
+ v: k for k, v in self.mergeable_ranks.items()
119
+ } # type: dict[int, bytes|str]
120
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
121
+
122
+ self.tokenizer = enc # type: tiktoken.Encoding
123
+
124
+ self.eod_id = self.tokenizer.eot_token
125
+ self.bod_id = self.special_tokens[STARTOFTEXT]
126
+ self.bos_id = self.special_tokens[BOSTOKEN]
127
+ self.eos_id = self.special_tokens[EOSTOKEN]
128
+ self.pad_id = self.special_tokens[PADTOKEN]
129
+
130
+ def __getstate__(self):
131
+ # for pickle lovers
132
+ state = self.__dict__.copy()
133
+ del state["tokenizer"]
134
+ return state
135
+
136
+ def __setstate__(self, state):
137
+ # tokenizer is not python native; don't pass it; rebuild it
138
+ self.__dict__.update(state)
139
+ enc = tiktoken.Encoding(
140
+ "HunYuan",
141
+ pat_str=PAT_STR,
142
+ mergeable_ranks=self.mergeable_ranks,
143
+ special_tokens=self.special_tokens,
144
+ )
145
+ self.tokenizer = enc
146
+
147
+ def __len__(self) -> int:
148
+ return self.tokenizer.n_vocab
149
+
150
+ def get_vocab(self) -> Dict[bytes, int]:
151
+ return self.mergeable_ranks
152
+
153
+ def convert_tokens_to_ids(
154
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
155
+ ) -> List[int]:
156
+ ids = []
157
+ if isinstance(tokens, (str, bytes)):
158
+ if tokens in self.special_tokens:
159
+ return self.special_tokens[tokens]
160
+ else:
161
+ return self.mergeable_ranks.get(tokens)
162
+ for token in tokens:
163
+ if token in self.special_tokens:
164
+ ids.append(self.special_tokens[token])
165
+ else:
166
+ ids.append(self.mergeable_ranks.get(token))
167
+ return ids
168
+
169
+ def _add_tokens(
170
+ self,
171
+ new_tokens: Union[List[str], List[AddedToken]],
172
+ special_tokens: bool = False,
173
+ ) -> int:
174
+ if not special_tokens and new_tokens:
175
+ raise ValueError("Adding regular tokens is not supported")
176
+ for token in new_tokens:
177
+ surface_form = token.content if isinstance(token, AddedToken) else token
178
+ if surface_form not in SPECIAL_TOKENS_SET:
179
+ raise ValueError("Adding unknown special tokens is not supported")
180
+ return 0
181
+
182
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
183
+ """
184
+ Save only the vocabulary of the tokenizer (vocabulary).
185
+ Returns:
186
+ `Tuple(str)`: Paths to the files saved.
187
+ """
188
+ file_path = os.path.join(save_directory, "hy.tiktoken")
189
+ with open(file_path, "w", encoding="utf-8") as w:
190
+ for k, v in self.mergeable_ranks.items():
191
+ line = base64.b64encode(k).decode("utf-8") + " " + str(v) + "\n"
192
+ w.write(line)
193
+ return (file_path,)
194
+
195
+ def tokenize(
196
+ self,
197
+ text: str,
198
+ allowed_special: Union[Set, str] = "all",
199
+ disallowed_special: Union[Collection, str] = (),
200
+ **kwargs,
201
+ ) -> List[Union[bytes, str]]:
202
+ """
203
+ Converts a string in a sequence of tokens.
204
+ Args:
205
+ text (`str`):
206
+ The sequence to be encoded.
207
+ allowed_special (`Literal["all"]` or `set`):
208
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
209
+ Default to "all".
210
+ disallowed_special (`Literal["all"]` or `Collection`):
211
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
212
+ Default to an empty tuple.
213
+ kwargs (additional keyword arguments, *optional*):
214
+ Will be passed to the underlying model specific encode method.
215
+ Returns:
216
+ `List[bytes|str]`: The list of tokens.
217
+ """
218
+ tokens = []
219
+ text = unicodedata.normalize("NFC", text)
220
+
221
+ # this implementation takes a detour: text -> token id -> token surface forms
222
+ for t in self.tokenizer.encode(
223
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
224
+ ):
225
+ tokens.append(self.decoder[t])
226
+ return tokens
227
+
228
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
229
+ """
230
+ Converts a sequence of tokens in a single string.
231
+ """
232
+ text = ""
233
+ temp = b""
234
+ for t in tokens:
235
+ if isinstance(t, str):
236
+ if temp:
237
+ text += temp.decode("utf-8", errors=self.errors)
238
+ temp = b""
239
+ text += t
240
+ elif isinstance(t, bytes):
241
+ temp += t
242
+ else:
243
+ raise TypeError("token should only be of type types or str")
244
+ if temp:
245
+ text += temp.decode("utf-8", errors=self.errors)
246
+ return text
247
+
248
+ @property
249
+ def vocab_size(self):
250
+ return self.tokenizer.n_vocab
251
+
252
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
253
+ """Converts an id to a token, special tokens included"""
254
+ if index in self.decoder:
255
+ return self.decoder[index]
256
+ raise ValueError("unknown ids")
257
+
258
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
259
+ """Converts a token to an id using the vocab, special tokens included"""
260
+ if token in self.special_tokens:
261
+ return self.special_tokens[token]
262
+ if token in self.mergeable_ranks:
263
+ return self.mergeable_ranks[token]
264
+ raise ValueError("unknown token")
265
+
266
+ def _tokenize(self, text: str, **kwargs):
267
+ """
268
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
269
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
270
+ Do NOT take care of added tokens.
271
+ """
272
+ raise NotImplementedError
273
+
274
+ def _decode(
275
+ self,
276
+ token_ids: Union[int, List[int]],
277
+ skip_special_tokens: bool = False,
278
+ errors: str = None,
279
+ **kwargs,
280
+ ) -> str:
281
+ if isinstance(token_ids, int):
282
+ token_ids = [token_ids]
283
+ if skip_special_tokens:
284
+ token_ids = [i for i in token_ids if i < self.eod_id]
285
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
286
+
287
+ # tests
288
+ if __name__ == "__main__":
289
+ tokenizer = HYTokenizer.from_pretrained('./other_tokenizer_vocab/hy')
290
+ text = '你好,世界'
291
+ tokens = tokenizer.tokenize(text)
292
+ print(tokens)
293
+ ids = tokenizer.convert_tokens_to_ids(tokens)
294
+ print(ids)
295
+ text2 = tokenizer.convert_tokens_to_string(tokens)
296
+ print(text2)
297
+ ids2 = tokenizer.convert_tokens_to_ids(tokens)