jstzwj commited on
Commit
521ba82
1 Parent(s): ab790b6
Files changed (2) hide show
  1. tokenization_shami.py +273 -0
  2. tokenization_shami_fast.py +95 -0
tokenization_shami.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for Shami."""
2
+
3
+ import json
4
+ import os
5
+ from functools import lru_cache
6
+ from typing import List, Optional, Tuple
7
+
8
+ import regex as re
9
+
10
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
11
+ from transformers.utils import logging
12
+
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+ VOCAB_FILES_NAMES = {
17
+ "vocab_file": "tokenizer.json",
18
+ }
19
+
20
+ PRETRAINED_VOCAB_FILES_MAP = {
21
+ "vocab_file": {
22
+ },
23
+ }
24
+
25
+
26
+ @lru_cache()
27
+ def bytes_to_unicode():
28
+ """
29
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
30
+ characters the bpe code barfs on.
31
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
32
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
33
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
34
+ tables between utf-8 bytes and unicode strings.
35
+ """
36
+ bs = (
37
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
38
+ )
39
+ cs = bs[:]
40
+ n = 0
41
+ for b in range(2**8):
42
+ if b not in bs:
43
+ bs.append(b)
44
+ cs.append(2**8 + n)
45
+ n += 1
46
+ cs = [chr(n) for n in cs]
47
+ return dict(zip(bs, cs))
48
+
49
+
50
+ def get_pairs(word):
51
+ """
52
+ Return set of symbol pairs in a word.
53
+ Word is represented as tuple of symbols (symbols being variable-length strings).
54
+ """
55
+ pairs = set()
56
+ prev_char = word[0]
57
+ for char in word[1:]:
58
+ pairs.add((prev_char, char))
59
+ prev_char = char
60
+ return pairs
61
+
62
+
63
+ class ShamiTokenizer(PreTrainedTokenizer):
64
+ vocab_files_names = VOCAB_FILES_NAMES
65
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
66
+ model_input_names = ["input_ids", "attention_mask"]
67
+
68
+ def __init__(
69
+ self,
70
+ vocab_file,
71
+ errors="replace",
72
+ unk_token="<|endoftext|>",
73
+ bos_token="<|endoftext|>",
74
+ eos_token="<|endoftext|>",
75
+ pad_token=None,
76
+ add_prefix_space=False,
77
+ add_bos_token=False,
78
+ **kwargs
79
+ ):
80
+ self.add_bos_token = add_bos_token
81
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
82
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
83
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
84
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
85
+
86
+ super().__init__(
87
+ errors=errors,
88
+ bos_token=bos_token,
89
+ eos_token=eos_token,
90
+ unk_token=unk_token,
91
+ pad_token=pad_token,
92
+ add_prefix_space=add_prefix_space,
93
+ **kwargs,
94
+ )
95
+
96
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
97
+ self.vocab = json.load(vocab_handle)
98
+ self.encoder = self.vocab["model"]["vocab"]
99
+ self.decoder = {v: k for k, v in self.encoder.items()}
100
+ self.errors = errors # how to handle errors in decoding
101
+ self.byte_encoder = bytes_to_unicode()
102
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
103
+
104
+ bpe_merges = self.vocab["model"]["merges"]
105
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
106
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
107
+ self.cache = {}
108
+ self.add_prefix_space = add_prefix_space
109
+
110
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
111
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
112
+
113
+ @property
114
+ def vocab_size(self):
115
+ return len(self.encoder)
116
+
117
+ def get_vocab(self):
118
+ return dict(self.encoder, **self.added_tokens_encoder)
119
+
120
+ def bpe(self, token):
121
+ if token in self.cache:
122
+ return self.cache[token]
123
+ word = tuple(token)
124
+ pairs = get_pairs(word)
125
+
126
+ if not pairs:
127
+ return token
128
+
129
+ while True:
130
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
131
+ if bigram not in self.bpe_ranks:
132
+ break
133
+ first, second = bigram
134
+ new_word = []
135
+ i = 0
136
+ while i < len(word):
137
+ try:
138
+ j = word.index(first, i)
139
+ except ValueError:
140
+ new_word.extend(word[i:])
141
+ break
142
+ else:
143
+ new_word.extend(word[i:j])
144
+ i = j
145
+
146
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
147
+ new_word.append(first + second)
148
+ i += 2
149
+ else:
150
+ new_word.append(word[i])
151
+ i += 1
152
+ new_word = tuple(new_word)
153
+ word = new_word
154
+ if len(word) == 1:
155
+ break
156
+ else:
157
+ pairs = get_pairs(word)
158
+ word = " ".join(word)
159
+ self.cache[token] = word
160
+ return word
161
+
162
+ def _tokenize(self, text):
163
+ """Tokenize a string."""
164
+ bpe_tokens = []
165
+ for token in re.findall(self.pat, text):
166
+ token = "".join(
167
+ self.byte_encoder[b] for b in token.encode("utf-8")
168
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
169
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
170
+ return bpe_tokens
171
+
172
+ def _convert_token_to_id(self, token):
173
+ """Converts a token (str) in an id using the vocab."""
174
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
175
+
176
+ def _convert_id_to_token(self, index):
177
+ """Converts an index (integer) in a token (str) using the vocab."""
178
+ return self.decoder.get(index)
179
+
180
+ def convert_tokens_to_string(self, tokens):
181
+ """Converts a sequence of tokens (string) in a single string."""
182
+ text = "".join(tokens)
183
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
184
+ return text
185
+
186
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
187
+ if not os.path.isdir(save_directory):
188
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
189
+ return
190
+ vocab_file = os.path.join(
191
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
192
+ )
193
+ merge_file = os.path.join(
194
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
195
+ )
196
+
197
+ with open(vocab_file, "w", encoding="utf-8") as f:
198
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
199
+
200
+ index = 0
201
+ with open(merge_file, "w", encoding="utf-8") as writer:
202
+ writer.write("#version: 0.2\n")
203
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
204
+ if index != token_index:
205
+ logger.warning(
206
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
207
+ " Please check that the tokenizer is not corrupted!"
208
+ )
209
+ index = token_index
210
+ writer.write(" ".join(bpe_tokens) + "\n")
211
+ index += 1
212
+
213
+ return vocab_file, merge_file
214
+
215
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
216
+ if self.add_bos_token:
217
+ bos_token_ids = [self.bos_token_id]
218
+ else:
219
+ bos_token_ids = []
220
+
221
+ output = bos_token_ids + token_ids_0
222
+
223
+ if token_ids_1 is None:
224
+ return output
225
+
226
+ return output + bos_token_ids + token_ids_1
227
+
228
+ def get_special_tokens_mask(
229
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
230
+ ) -> List[int]:
231
+ """
232
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
233
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
234
+ Args:
235
+ token_ids_0 (`List[int]`):
236
+ List of IDs.
237
+ token_ids_1 (`List[int]`, *optional*):
238
+ Optional second list of IDs for sequence pairs.
239
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
240
+ Whether or not the token list is already formatted with special tokens for the model.
241
+ Returns:
242
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
243
+ """
244
+ if already_has_special_tokens:
245
+ return super().get_special_tokens_mask(
246
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
247
+ )
248
+
249
+ if not self.add_bos_token:
250
+ return super().get_special_tokens_mask(
251
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
252
+ )
253
+
254
+ if token_ids_1 is None:
255
+ return [1] + ([0] * len(token_ids_0))
256
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
257
+
258
+
259
+ def create_token_type_ids_from_sequences(
260
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
261
+ ) -> List[int]:
262
+ sep = [self.sep_token_id]
263
+ cls = [self.cls_token_id]
264
+
265
+ if token_ids_1 is None:
266
+ return len(cls + token_ids_0 + sep) * [0]
267
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
268
+
269
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
270
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
271
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
272
+ text = " " + text
273
+ return (text, kwargs)
tokenization_shami_fast.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast tokenization classes for Shami."""
2
+ import json
3
+ from typing import TYPE_CHECKING, List, Optional, Tuple
4
+
5
+ from tokenizers import pre_tokenizers
6
+
7
+ from transformers.tokenization_utils_base import BatchEncoding
8
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
9
+ from transformers.utils import logging
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from transformers.pipelines.conversational import Conversation
14
+
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+ VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
19
+
20
+ PRETRAINED_VOCAB_FILES_MAP = {
21
+ "tokenizer_file": {
22
+ },
23
+ }
24
+
25
+ class ShamiTokenizerFast(PreTrainedTokenizerFast):
26
+ vocab_files_names = VOCAB_FILES_NAMES
27
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
28
+ model_input_names = ["input_ids", "attention_mask"]
29
+ slow_tokenizer_class = None
30
+
31
+ def __init__(
32
+ self,
33
+ vocab_file=None,
34
+ merges_file=None,
35
+ tokenizer_file=None,
36
+ unk_token="<|endoftext|>",
37
+ bos_token="<|endoftext|>",
38
+ eos_token="<|endoftext|>",
39
+ pad_token="<|endoftext|>",
40
+ add_prefix_space=False,
41
+ **kwargs
42
+ ):
43
+ super().__init__(
44
+ vocab_file,
45
+ merges_file,
46
+ tokenizer_file=tokenizer_file,
47
+ unk_token=unk_token,
48
+ bos_token=bos_token,
49
+ eos_token=eos_token,
50
+ pad_token=pad_token,
51
+ add_prefix_space=add_prefix_space,
52
+ **kwargs,
53
+ )
54
+ pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
55
+ if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
56
+ pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
57
+ pre_tok_state["add_prefix_space"] = add_prefix_space
58
+ self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
59
+
60
+ self.add_prefix_space = add_prefix_space
61
+
62
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
63
+ is_split_into_words = kwargs.get("is_split_into_words", False)
64
+ if not (self.add_prefix_space or not is_split_into_words):
65
+ raise Exception(
66
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
67
+ " pretokenized inputs."
68
+ )
69
+
70
+ return super()._batch_encode_plus(*args, **kwargs)
71
+
72
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
73
+ is_split_into_words = kwargs.get("is_split_into_words", False)
74
+
75
+ if not (self.add_prefix_space or not is_split_into_words):
76
+ raise Exception(
77
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
78
+ " pretokenized inputs."
79
+ )
80
+
81
+ return super()._encode_plus(*args, **kwargs)
82
+
83
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
84
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
85
+ return tuple(files)
86
+
87
+ def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
88
+ """This corresponds to DialoGPT variants of models."""
89
+ input_ids = []
90
+ for is_user, text in conversation.iter_texts():
91
+ input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])
92
+
93
+ if len(input_ids) > self.model_max_length:
94
+ input_ids = input_ids[-self.model_max_length :]
95
+ return input_ids