myduy commited on
Commit
9b4ff88
·
verified ·
1 Parent(s): 8bc847d

Upload tokenization_dream.py

Browse files
Files changed (1) hide show
  1. tokenization_dream.py +367 -0
tokenization_dream.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Dream team, HKUNLP Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on Qwen's implementations in this library.
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Tokenization classes for Dream."""
17
+
18
+ import json
19
+ import os
20
+ import unicodedata
21
+ from functools import lru_cache
22
+ from typing import Optional, Tuple
23
+
24
+ import regex as re
25
+
26
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
27
+ from transformers.utils import logging
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ VOCAB_FILES_NAMES = {
33
+ "vocab_file": "vocab.json",
34
+ "merges_file": "merges.txt",
35
+ }
36
+
37
+
38
+ MAX_MODEL_INPUT_SIZES = {"dream/dream-tokenizer": 32768}
39
+
40
+ PRETOKENIZE_REGEX = 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+"""
41
+
42
+
43
+ @lru_cache()
44
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
45
+ def bytes_to_unicode():
46
+ """
47
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
48
+ characters the bpe code barfs on.
49
+
50
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
51
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
52
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
53
+ tables between utf-8 bytes and unicode strings.
54
+ """
55
+ bs = (
56
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
57
+ )
58
+ cs = bs[:]
59
+ n = 0
60
+ for b in range(2**8):
61
+ if b not in bs:
62
+ bs.append(b)
63
+ cs.append(2**8 + n)
64
+ n += 1
65
+ cs = [chr(n) for n in cs]
66
+ return dict(zip(bs, cs))
67
+
68
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
69
+ def get_pairs(word):
70
+ """
71
+ Return set of symbol pairs in a word.
72
+
73
+ Word is represented as tuple of symbols (symbols being variable-length strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class DreamTokenizer(PreTrainedTokenizer):
84
+ """
85
+ Construct a Dream tokenizer. Based on byte-level Byte-Pair-Encoding.
86
+
87
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
88
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
89
+
90
+ ```python
91
+ >>> from transformers import AutoTokenizer
92
+
93
+ >>> tokenizer = AutoTokenizer.from_pretrained("Dream-org/Dream-v0-Base-7B", trust_remote_code=True)
94
+ >>> tokenizer("Hello world")["input_ids"]
95
+ [9707, 1879]
96
+
97
+ >>> tokenizer(" Hello world")["input_ids"]
98
+ [21927, 1879]
99
+ ```
100
+ This is expected.
101
+
102
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
103
+
104
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
105
+ this superclass for more information regarding those methods.
106
+
107
+ Args:
108
+ vocab_file (`str`):
109
+ Path to the vocabulary file.
110
+ merges_file (`str`):
111
+ Path to the merges file.
112
+ errors (`str`, *optional*, defaults to `"replace"`):
113
+ Paradigm to follow when decoding bytes to UTF-8. See
114
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
115
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
116
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
117
+ token instead.
118
+ bos_token (`str`, *optional*):
119
+ The beginning of sequence token. Not applicable for this tokenizer.
120
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
121
+ The end of sequence token.
122
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The token used for padding, for example when batching sequences of different lengths.
124
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
125
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
126
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
127
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
129
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
130
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
131
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
132
+ """
133
+
134
+ vocab_files_names = VOCAB_FILES_NAMES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ merges_file,
141
+ errors="replace",
142
+ unk_token="<|endoftext|>",
143
+ bos_token=None,
144
+ eos_token="<|endoftext|>",
145
+ pad_token="<|endoftext|>",
146
+ b_ner_token="<ner>",
147
+ e_ner_token="</ner>",
148
+ b_entity_token="<entity>",
149
+ e_entity_token="</entity>",
150
+ clean_up_tokenization_spaces=False,
151
+ split_special_tokens=False,
152
+ **kwargs,
153
+ ):
154
+ # Dream vocab does not contain control tokens; added tokens need to be special
155
+ bos_token = (
156
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
157
+ if isinstance(bos_token, str)
158
+ else bos_token
159
+ )
160
+ eos_token = (
161
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
162
+ if isinstance(eos_token, str)
163
+ else eos_token
164
+ )
165
+ unk_token = (
166
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
167
+ if isinstance(unk_token, str)
168
+ else unk_token
169
+ )
170
+ pad_token = (
171
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
172
+ if isinstance(pad_token, str)
173
+ else pad_token
174
+ )
175
+ b_ner_token = (
176
+ AddedToken(b_ner_token, lstrip=False, rstrip=False, special=True, normalized=False)
177
+ if isinstance(b_ner_token, str)
178
+ else b_ner_token
179
+ )
180
+ e_ner_token = (
181
+ AddedToken(e_ner_token, lstrip=False, rstrip=False, special=True, normalized=False)
182
+ if isinstance(e_ner_token, str)
183
+ else e_ner_token
184
+ )
185
+ b_entity_token = (
186
+ AddedToken(b_entity_token, lstrip=False, rstrip=False, special=True, normalized=False)
187
+ if isinstance(b_entity_token, str)
188
+ else b_entity_token
189
+ )
190
+ e_entity_token = (
191
+ AddedToken(e_entity_token, lstrip=False, rstrip=False, special=True, normalized=False)
192
+ if isinstance(e_entity_token, str)
193
+ else e_entity_token
194
+ )
195
+
196
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
197
+ self.encoder = json.load(vocab_handle)
198
+ self.decoder = {v: k for k, v in self.encoder.items()}
199
+ self.errors = errors # how to handle errors in decoding
200
+ self.byte_encoder = bytes_to_unicode()
201
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
202
+ bpe_merges = []
203
+ with open(merges_file, encoding="utf-8") as merges_handle:
204
+ for i, line in enumerate(merges_handle):
205
+ line = line.strip()
206
+ if (i == 0 and line.startswith("#version:")) or not line:
207
+ continue
208
+ bpe_merges.append(tuple(line.split()))
209
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
210
+ # NOTE: the cache can grow without bound and will get really large for long running processes
211
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
212
+ # not a memory leak but appears as one.
213
+ # GPT2Tokenizer has the same problem, so let's be consistent.
214
+ self.cache = {}
215
+
216
+ self.pat = re.compile(PRETOKENIZE_REGEX)
217
+
218
+ if kwargs.get("add_prefix_space", False):
219
+ logger.warning_once(
220
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
221
+ )
222
+
223
+ super().__init__(
224
+ errors=errors,
225
+ bos_token=bos_token,
226
+ eos_token=eos_token,
227
+ pad_token=pad_token,
228
+ unk_token=unk_token,
229
+ b_ner_token=b_ner_token,
230
+ e_ner_token=e_ner_token,
231
+ b_entity_token=b_entity_token,
232
+ e_entity_token=e_entity_token,
233
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
234
+ split_special_tokens=split_special_tokens,
235
+ **kwargs,
236
+ )
237
+
238
+ @property
239
+ def vocab_size(self) -> int:
240
+ return len(self.encoder)
241
+
242
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
243
+ def get_vocab(self):
244
+ return dict(self.encoder, **self.added_tokens_encoder)
245
+
246
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
247
+ def bpe(self, token):
248
+ if token in self.cache:
249
+ return self.cache[token]
250
+ word = tuple(token)
251
+ pairs = get_pairs(word)
252
+
253
+ if not pairs:
254
+ return token
255
+
256
+ while True:
257
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
258
+ if bigram not in self.bpe_ranks:
259
+ break
260
+ first, second = bigram
261
+ new_word = []
262
+ i = 0
263
+ while i < len(word):
264
+ try:
265
+ j = word.index(first, i)
266
+ except ValueError:
267
+ new_word.extend(word[i:])
268
+ break
269
+ else:
270
+ new_word.extend(word[i:j])
271
+ i = j
272
+
273
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
274
+ new_word.append(first + second)
275
+ i += 2
276
+ else:
277
+ new_word.append(word[i])
278
+ i += 1
279
+ new_word = tuple(new_word)
280
+ word = new_word
281
+ if len(word) == 1:
282
+ break
283
+ else:
284
+ pairs = get_pairs(word)
285
+ word = " ".join(word)
286
+ self.cache[token] = word
287
+ return word
288
+
289
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
290
+ def _tokenize(self, text):
291
+ """Tokenize a string."""
292
+ bpe_tokens = []
293
+ for token in re.findall(self.pat, text):
294
+ token = "".join(
295
+ self.byte_encoder[b] for b in token.encode("utf-8")
296
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
297
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
298
+ return bpe_tokens
299
+
300
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
301
+ def _convert_token_to_id(self, token):
302
+ """Converts a token (str) in an id using the vocab."""
303
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
304
+
305
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
306
+ def _convert_id_to_token(self, index):
307
+ """Converts an index (integer) in a token (str) using the vocab."""
308
+ return self.decoder.get(index)
309
+
310
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
311
+ def convert_tokens_to_string(self, tokens):
312
+ """Converts a sequence of tokens (string) in a single string."""
313
+ text = "".join(tokens)
314
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
315
+ return text
316
+
317
+ def decode(
318
+ self,
319
+ token_ids,
320
+ skip_special_tokens: bool = False,
321
+ clean_up_tokenization_spaces: Optional[bool] = False,
322
+ spaces_between_special_tokens: bool = False,
323
+ **kwargs,
324
+ ) -> str:
325
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
326
+ # and cannot be configured elsewhere, but it should default to False for DreamTokenizer
327
+ return super().decode(
328
+ token_ids,
329
+ skip_special_tokens=skip_special_tokens,
330
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
331
+ spaces_between_special_tokens=spaces_between_special_tokens,
332
+ **kwargs,
333
+ )
334
+
335
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
336
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
337
+ if not os.path.isdir(save_directory):
338
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
339
+ return
340
+ vocab_file = os.path.join(
341
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
342
+ )
343
+ merge_file = os.path.join(
344
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
345
+ )
346
+
347
+ with open(vocab_file, "w", encoding="utf-8") as f:
348
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
349
+
350
+ index = 0
351
+ with open(merge_file, "w", encoding="utf-8") as writer:
352
+ writer.write("#version: 0.2\n")
353
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
354
+ if index != token_index:
355
+ logger.warning(
356
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
357
+ " Please check that the tokenizer is not corrupted!"
358
+ )
359
+ index = token_index
360
+ writer.write(" ".join(bpe_tokens) + "\n")
361
+ index += 1
362
+
363
+ return vocab_file, merge_file
364
+
365
+ def prepare_for_tokenization(self, text, **kwargs):
366
+ text = unicodedata.normalize("NFC", text)
367
+ return (text, kwargs)