txsun commited on
Commit
fcc7e69
1 Parent(s): 057de87

Upload tokenization_moss.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tokenization_moss.py +368 -0
tokenization_moss.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for Moss"""
2
+
3
+ import json
4
+ import os
5
+ import numpy as np
6
+ import regex as re
7
+
8
+ from functools import lru_cache
9
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
10
+
11
+ from transformers.utils import is_tf_available, is_torch_available, logging
12
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ if is_torch_available():
17
+ import torch
18
+ if is_tf_available():
19
+ import tensorflow as tf
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ VOCAB_FILES_NAMES = {
25
+ "vocab_file": "vocab.json",
26
+ "merges_file": "merges.txt",
27
+ }
28
+
29
+ PRETRAINED_VOCAB_FILES_MAP = {
30
+ "vocab_file": {
31
+ "fnlp/moss-moon-003-base": "https://huggingface.co/fnlp/moss-moon-003-base/resolve/main/vocab.json",
32
+ "fnlp/moss-moon-003-sft": "https://huggingface.co/fnlp/moss-moon-003-sft/resolve/main/vocab.json",
33
+ "fnlp/moss-moon-003-sft-plugin": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin/resolve/main/vocab.json",
34
+ },
35
+ "merges_file": {
36
+ "fnlp/moss-moon-003-base": "https://huggingface.co/fnlp/moss-moon-003-base/resolve/main/merge.txt",
37
+ "fnlp/moss-moon-003-sft": "https://huggingface.co/fnlp/moss-moon-003-sft/resolve/main/merge.txt",
38
+ "fnlp/moss-moon-003-sft-plugin": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin/resolve/main/merge.txt",
39
+ },
40
+ }
41
+
42
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
43
+ "fnlp/moss-moon-003-base": 2048,
44
+ "fnlp/moss-moon-003-sft": 2048,
45
+ "fnlp/moss-moon-003-sft-plugin": 2048,
46
+ }
47
+
48
+
49
+ @lru_cache()
50
+ def bytes_to_unicode():
51
+ """
52
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
53
+ characters the bpe code barfs on.
54
+
55
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
56
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
57
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
58
+ tables between utf-8 bytes and unicode strings.
59
+ """
60
+ bs = (
61
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
62
+ )
63
+ cs = bs[:]
64
+ n = 0
65
+ for b in range(2**8):
66
+ if b not in bs:
67
+ bs.append(b)
68
+ cs.append(2**8 + n)
69
+ n += 1
70
+ cs = [chr(n) for n in cs]
71
+ return dict(zip(bs, cs))
72
+
73
+
74
+ def get_pairs(word):
75
+ """
76
+ Return set of symbol pairs in a word.
77
+
78
+ Word is represented as tuple of symbols (symbols being variable-length strings).
79
+ """
80
+ pairs = set()
81
+ prev_char = word[0]
82
+ for char in word[1:]:
83
+ pairs.add((prev_char, char))
84
+ prev_char = char
85
+ return pairs
86
+
87
+
88
+ class MossTokenizer(PreTrainedTokenizer):
89
+ """
90
+ Construct a Moss tokenizer. Based on byte-level Byte-Pair-Encoding.
91
+
92
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
93
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
94
+
95
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
96
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
97
+
98
+ <Tip>
99
+
100
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
101
+
102
+ </Tip>
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*, defaults to `<|endoftext|>`):
119
+ The beginning of sequence token.
120
+ eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
121
+ The end of sequence token.
122
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
123
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
124
+ other word. (Moss tokenizer detect beginning of words by the preceding space).
125
+ """
126
+
127
+ vocab_files_names = VOCAB_FILES_NAMES
128
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
129
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
130
+ model_input_names = ["input_ids", "attention_mask"]
131
+
132
+ def __init__(
133
+ self,
134
+ vocab_file,
135
+ merges_file,
136
+ errors="replace",
137
+ unk_token="<|endoftext|>",
138
+ bos_token="<|endoftext|>",
139
+ eos_token="<eom>",
140
+ pad_token=None,
141
+ add_prefix_space=False,
142
+ add_bos_token=False,
143
+ **kwargs,
144
+ ):
145
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
146
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
147
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
148
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
149
+ super().__init__(
150
+ errors=errors,
151
+ unk_token=unk_token,
152
+ bos_token=bos_token,
153
+ eos_token=eos_token,
154
+ pad_token=pad_token,
155
+ add_prefix_space=add_prefix_space,
156
+ add_bos_token=add_bos_token,
157
+ **kwargs,
158
+ )
159
+ self.add_bos_token = add_bos_token
160
+
161
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
162
+ self.encoder = json.load(vocab_handle)
163
+ self.decoder = {v: k for k, v in self.encoder.items()}
164
+ self.errors = errors # how to handle errors in decoding
165
+ self.byte_encoder = bytes_to_unicode()
166
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
167
+ with open(merges_file, encoding="utf-8") as merges_handle:
168
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
169
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
170
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
171
+ self.cache = {}
172
+ self.add_prefix_space = add_prefix_space
173
+
174
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
175
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
176
+
177
+ @property
178
+ def vocab_size(self):
179
+ return len(self.encoder)
180
+
181
+ def get_vocab(self):
182
+ return dict(self.encoder, **self.added_tokens_encoder)
183
+
184
+ def bpe(self, token):
185
+ if token in self.cache:
186
+ return self.cache[token]
187
+ word = tuple(token)
188
+ pairs = get_pairs(word)
189
+
190
+ if not pairs:
191
+ return token
192
+
193
+ while True:
194
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
195
+ if bigram not in self.bpe_ranks:
196
+ break
197
+ first, second = bigram
198
+ new_word = []
199
+ i = 0
200
+ while i < len(word):
201
+ try:
202
+ j = word.index(first, i)
203
+ except ValueError:
204
+ new_word.extend(word[i:])
205
+ break
206
+ else:
207
+ new_word.extend(word[i:j])
208
+ i = j
209
+
210
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
211
+ new_word.append(first + second)
212
+ i += 2
213
+ else:
214
+ new_word.append(word[i])
215
+ i += 1
216
+ new_word = tuple(new_word)
217
+ word = new_word
218
+ if len(word) == 1:
219
+ break
220
+ else:
221
+ pairs = get_pairs(word)
222
+ word = " ".join(word)
223
+ self.cache[token] = word
224
+ return word
225
+
226
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
227
+ if self.add_bos_token:
228
+ bos_token_ids = [self.bos_token_id]
229
+ else:
230
+ bos_token_ids = []
231
+
232
+ output = bos_token_ids + token_ids_0
233
+
234
+ if token_ids_1 is None:
235
+ return output
236
+
237
+ return output + bos_token_ids + token_ids_1
238
+
239
+ def _tokenize(self, text):
240
+ """Tokenize a string."""
241
+ bpe_tokens = []
242
+ for token in re.findall(self.pat, text):
243
+ token = "".join(
244
+ self.byte_encoder[b] for b in token.encode("utf-8")
245
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
246
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
247
+ return bpe_tokens
248
+
249
+ def _convert_token_to_id(self, token):
250
+ """Converts a token (str) in an id using the vocab."""
251
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
252
+
253
+ def _convert_id_to_token(self, index):
254
+ """Converts an index (integer) in a token (str) using the vocab."""
255
+ return self.decoder.get(index)
256
+
257
+ def convert_tokens_to_string(self, tokens):
258
+ """Converts a sequence of tokens (string) in a single string."""
259
+ text = "".join(tokens)
260
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
261
+ return text
262
+
263
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
264
+ if not os.path.isdir(save_directory):
265
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
266
+ return
267
+ vocab_file = os.path.join(
268
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
269
+ )
270
+ merge_file = os.path.join(
271
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
272
+ )
273
+
274
+ with open(vocab_file, "w", encoding="utf-8") as f:
275
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
276
+
277
+ index = 0
278
+ with open(merge_file, "w", encoding="utf-8") as writer:
279
+ writer.write("#version: 0.2\n")
280
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
281
+ if index != token_index:
282
+ logger.warning(
283
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
284
+ " Please check that the tokenizer is not corrupted!"
285
+ )
286
+ index = token_index
287
+ writer.write(" ".join(bpe_tokens) + "\n")
288
+ index += 1
289
+
290
+ return vocab_file, merge_file
291
+
292
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
293
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
294
+ if is_split_into_words or add_prefix_space:
295
+ text = " " + text
296
+ return (text, kwargs)
297
+
298
+ def decode(
299
+ self,
300
+ token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
301
+ skip_special_tokens: bool = False,
302
+ clean_up_tokenization_spaces: bool = None,
303
+ truncate_before_pattern: Optional[List[str]] = None,
304
+ **kwargs,
305
+ ) -> str:
306
+ """
307
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
308
+ tokens and clean up tokenization spaces.
309
+
310
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
311
+
312
+ Args:
313
+ token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
314
+ List of tokenized input ids. Can be obtained using the `__call__` method.
315
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
316
+ Whether or not to remove special tokens in the decoding.
317
+ clean_up_tokenization_spaces (`bool`, *optional*):
318
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
319
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
320
+ truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
321
+ A list of regular expression strings that will be used to truncate the returned string. This can be
322
+ used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
323
+ of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
324
+ kwargs (additional keyword arguments, *optional*):
325
+ Will be passed to the underlying model specific decode method.
326
+
327
+ Returns:
328
+ `str`: The decoded sentence.
329
+ """
330
+ decoded_text = super()._decode(
331
+ token_ids=token_ids,
332
+ skip_special_tokens=skip_special_tokens,
333
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
334
+ **kwargs,
335
+ )
336
+
337
+ if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
338
+ decoded_text = self.truncate(decoded_text, truncate_before_pattern)
339
+
340
+ return decoded_text
341
+
342
+ def truncate(self, completion, truncate_before_pattern):
343
+ def find_re(string, pattern, start_pos):
344
+ m = pattern.search(string, start_pos)
345
+ return m.start() if m else -1
346
+
347
+ terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
348
+
349
+ prints = list(re.finditer("^print", completion, re.MULTILINE))
350
+
351
+ if len(prints) > 1:
352
+ completion = completion[: prints[1].start()]
353
+
354
+ defs = list(re.finditer("^def", completion, re.MULTILINE))
355
+
356
+ if len(defs) > 1:
357
+ completion = completion[: defs[1].start()]
358
+
359
+ start_pos = 0
360
+
361
+ terminals_pos = [
362
+ pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
363
+ ]
364
+
365
+ if len(terminals_pos) > 0:
366
+ return completion[: min(terminals_pos)]
367
+ else:
368
+ return completion