gonglinyuan commited on
Commit
31b5dbe
1 Parent(s): df37bca

Upload tokenizer

Browse files
dict.txt ADDED
The diff for this file is too large to render. See raw diff
 
fairseq_dictionary.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is ported from fairseq:
4
+ # https://github.com/facebookresearch/fairseq
5
+ #
6
+ # This source code is licensed under the MIT license found in the
7
+ # LICENSE file in the root directory of the fairseq repo
8
+
9
+
10
+ import os
11
+ import re
12
+ from collections import Counter
13
+ from multiprocessing import Pool
14
+ from typing import Iterable, List
15
+
16
+ import torch
17
+
18
+
19
+ def item(tensor):
20
+ # tpu-comment: making this a no-op for xla devices.
21
+ if torch.is_tensor(tensor) and tensor.device.type == "xla":
22
+ return tensor.detach()
23
+ if hasattr(tensor, "item"):
24
+ return tensor.item()
25
+ if hasattr(tensor, "__getitem__"):
26
+ return tensor[0]
27
+ return tensor
28
+
29
+
30
+ def post_process(sentence: str, symbol: str):
31
+ if symbol == "sentencepiece":
32
+ sentence = sentence.replace(" ", "").replace("\u2581", " ").strip()
33
+ elif symbol == "wordpiece":
34
+ sentence = sentence.replace(" ", "").replace("_", " ").strip()
35
+ elif symbol == "letter":
36
+ sentence = sentence.replace(" ", "").replace("|", " ").strip()
37
+ elif symbol == "silence":
38
+ import re
39
+
40
+ sentence = sentence.replace("<SIL>", "")
41
+ sentence = re.sub(" +", " ", sentence).strip()
42
+ elif symbol == "_EOW":
43
+ sentence = sentence.replace(" ", "").replace("_EOW", " ").strip()
44
+ elif symbol in {"subword_nmt", "@@ ", "@@"}:
45
+ if symbol == "subword_nmt":
46
+ symbol = "@@ "
47
+ sentence = (sentence + " ").replace(symbol, "").rstrip()
48
+ elif symbol == "none":
49
+ pass
50
+ elif symbol is not None:
51
+ raise NotImplementedError(f"Unknown post_process option: {symbol}")
52
+ return sentence
53
+
54
+
55
+ SPACE_NORMALIZER = re.compile(r"\s+")
56
+
57
+
58
+ def tokenize_line(line):
59
+ line = SPACE_NORMALIZER.sub(" ", line)
60
+ line = line.strip()
61
+ return line.split()
62
+
63
+
64
+ def _safe_readline(fd) -> str:
65
+ pos = fd.tell()
66
+ while True:
67
+ try:
68
+ return fd.readline()
69
+ except UnicodeDecodeError:
70
+ pos -= 1
71
+ fd.seek(pos) # search where this character begins
72
+
73
+
74
+ def find_offsets(filename: str, num_chunks: int) -> List[int]:
75
+ """
76
+ given a file and a number of chuncks, find the offsets in the file
77
+ to be able to chunk around full lines.
78
+ """
79
+ with open(filename, "r", encoding="utf-8") as f:
80
+ size = os.fstat(f.fileno()).st_size
81
+ chunk_size = size // num_chunks
82
+ offsets = [0 for _ in range(num_chunks + 1)]
83
+ for i in range(1, num_chunks):
84
+ f.seek(chunk_size * i)
85
+ _safe_readline(f)
86
+ offsets[i] = f.tell()
87
+ offsets[-1] = size
88
+ return offsets
89
+
90
+
91
+ class ChunkLineIterator:
92
+ """
93
+ Iterator to properly iterate over lines of a file chunck.
94
+ """
95
+
96
+ def __init__(self, fd, start_offset: int, end_offset: int):
97
+ self._fd = fd
98
+ self._start_offset = start_offset
99
+ self._end_offset = end_offset
100
+
101
+ def __iter__(self) -> Iterable[str]:
102
+ self._fd.seek(self._start_offset)
103
+ # next(f) breaks f.tell(), hence readline() must be used
104
+ line = _safe_readline(self._fd)
105
+ while line:
106
+ pos = self._fd.tell()
107
+ # f.tell() does not always give the byte position in the file
108
+ # sometimes it skips to a very large number
109
+ # it is unlikely that through a normal read we go from
110
+ # end bytes to end + 2**32 bytes (4 GB) and this makes it unlikely
111
+ # that the procedure breaks by the undeterministic behavior of
112
+ # f.tell()
113
+ if (
114
+ self._end_offset > 0
115
+ and pos > self._end_offset
116
+ and pos < self._end_offset + 2 ** 32
117
+ ):
118
+ break
119
+ yield line
120
+ line = self._fd.readline()
121
+
122
+
123
+ class Chunker:
124
+ """
125
+ contextmanager to read a chunck of a file line by line.
126
+ """
127
+
128
+ def __init__(self, path: str, start_offset: int, end_offset: int):
129
+ self.path = path
130
+ self.start_offset = start_offset
131
+ self.end_offset = end_offset
132
+
133
+ def __enter__(self) -> ChunkLineIterator:
134
+ self.fd = open(self.path, "r", encoding="utf-8")
135
+ return ChunkLineIterator(self.fd, self.start_offset, self.end_offset)
136
+
137
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
138
+ self.fd.close()
139
+
140
+
141
+ class Dictionary:
142
+ """A mapping from symbols to consecutive integers"""
143
+
144
+ def __init__(
145
+ self,
146
+ *, # begin keyword-only arguments
147
+ bos="<s>",
148
+ pad="<pad>",
149
+ eos="</s>",
150
+ unk="<unk>",
151
+ extra_special_symbols=None,
152
+ ):
153
+ self.bos_word, self.unk_word, self.pad_word, self.eos_word = bos, unk, pad, eos
154
+ self.symbols = []
155
+ self.count = []
156
+ self.indices = {}
157
+ self.bos_index = self.add_symbol(bos)
158
+ self.pad_index = self.add_symbol(pad)
159
+ self.eos_index = self.add_symbol(eos)
160
+ self.unk_index = self.add_symbol(unk)
161
+ if extra_special_symbols:
162
+ for s in extra_special_symbols:
163
+ self.add_symbol(s)
164
+ self.nspecial = len(self.symbols)
165
+
166
+ def __eq__(self, other):
167
+ return self.indices == other.indices
168
+
169
+ def __getitem__(self, idx):
170
+ if idx < len(self.symbols):
171
+ return self.symbols[idx]
172
+ return self.unk_word
173
+
174
+ def get_count(self, idx):
175
+ return self.count[idx]
176
+
177
+ def __len__(self):
178
+ """Returns the number of symbols in the dictionary"""
179
+ return len(self.symbols)
180
+
181
+ def __contains__(self, sym):
182
+ return sym in self.indices
183
+
184
+ def index(self, sym):
185
+ """Returns the index of the specified symbol"""
186
+ assert isinstance(sym, str)
187
+ if sym in self.indices:
188
+ return self.indices[sym]
189
+ return self.unk_index
190
+
191
+ def string(
192
+ self,
193
+ tensor,
194
+ bpe_symbol=None,
195
+ escape_unk=False,
196
+ extra_symbols_to_ignore=None,
197
+ unk_string=None,
198
+ include_eos=False,
199
+ separator=" ",
200
+ ):
201
+ """Helper for converting a tensor of token indices to a string.
202
+
203
+ Can optionally remove BPE symbols or escape <unk> words.
204
+ """
205
+ if torch.is_tensor(tensor) and tensor.dim() == 2:
206
+ return "\n".join(
207
+ self.string(
208
+ t,
209
+ bpe_symbol,
210
+ escape_unk,
211
+ extra_symbols_to_ignore,
212
+ include_eos=include_eos,
213
+ )
214
+ for t in tensor
215
+ )
216
+
217
+ extra_symbols_to_ignore = set(extra_symbols_to_ignore or [])
218
+ if not include_eos:
219
+ extra_symbols_to_ignore.add(self.eos())
220
+
221
+ def token_string(i):
222
+ if i == self.unk():
223
+ if unk_string is not None:
224
+ return unk_string
225
+ else:
226
+ return self.unk_string(escape_unk)
227
+ else:
228
+ return self[i]
229
+
230
+ if hasattr(self, "bos_index"):
231
+ extra_symbols_to_ignore.add(self.bos())
232
+
233
+ sent = separator.join(
234
+ token_string(i)
235
+ for i in tensor
236
+ if item(i) not in extra_symbols_to_ignore
237
+ )
238
+
239
+ return post_process(sent, bpe_symbol)
240
+
241
+ def unk_string(self, escape=False):
242
+ """Return unknown string, optionally escaped as: <<unk>>"""
243
+ if escape:
244
+ return "<{}>".format(self.unk_word)
245
+ else:
246
+ return self.unk_word
247
+
248
+ def add_symbol(self, word, n=1, overwrite=False):
249
+ """Adds a word to the dictionary"""
250
+ if word in self.indices and not overwrite:
251
+ idx = self.indices[word]
252
+ self.count[idx] = self.count[idx] + n
253
+ return idx
254
+ else:
255
+ idx = len(self.symbols)
256
+ self.indices[word] = idx
257
+ self.symbols.append(word)
258
+ self.count.append(n)
259
+ return idx
260
+
261
+ def update(self, new_dict):
262
+ """Updates counts from new dictionary."""
263
+ for word in new_dict.symbols:
264
+ idx2 = new_dict.indices[word]
265
+ if word in self.indices:
266
+ idx = self.indices[word]
267
+ self.count[idx] = self.count[idx] + new_dict.count[idx2]
268
+ else:
269
+ idx = len(self.symbols)
270
+ self.indices[word] = idx
271
+ self.symbols.append(word)
272
+ self.count.append(new_dict.count[idx2])
273
+
274
+ def finalize(self, threshold=-1, nwords=-1, padding_factor=8):
275
+ """Sort symbols by frequency in descending order, ignoring special ones.
276
+
277
+ Args:
278
+ - threshold defines the minimum word count
279
+ - nwords defines the total number of words in the final dictionary,
280
+ including special symbols
281
+ - padding_factor can be used to pad the dictionary size to be a
282
+ multiple of 8, which is important on some hardware (e.g., Nvidia
283
+ Tensor Cores).
284
+ """
285
+ if nwords <= 0:
286
+ nwords = len(self)
287
+
288
+ new_indices = dict(zip(self.symbols[: self.nspecial], range(self.nspecial)))
289
+ new_symbols = self.symbols[: self.nspecial]
290
+ new_count = self.count[: self.nspecial]
291
+
292
+ c = Counter(
293
+ dict(
294
+ sorted(zip(self.symbols[self.nspecial:], self.count[self.nspecial:]))
295
+ )
296
+ )
297
+ for symbol, count in c.most_common(nwords - self.nspecial):
298
+ if count >= threshold:
299
+ new_indices[symbol] = len(new_symbols)
300
+ new_symbols.append(symbol)
301
+ new_count.append(count)
302
+ else:
303
+ break
304
+
305
+ assert len(new_symbols) == len(new_indices)
306
+
307
+ self.count = list(new_count)
308
+ self.symbols = list(new_symbols)
309
+ self.indices = new_indices
310
+
311
+ self.pad_to_multiple_(padding_factor)
312
+
313
+ def pad_to_multiple_(self, padding_factor):
314
+ """Pad Dictionary size to be a multiple of *padding_factor*."""
315
+ if padding_factor > 1:
316
+ i = 0
317
+ while len(self) % padding_factor != 0:
318
+ symbol = "madeupword{:04d}".format(i)
319
+ self.add_symbol(symbol, n=0)
320
+ i += 1
321
+
322
+ def bos(self):
323
+ """Helper to get index of beginning-of-sentence symbol"""
324
+ return self.bos_index
325
+
326
+ def pad(self):
327
+ """Helper to get index of pad symbol"""
328
+ return self.pad_index
329
+
330
+ def eos(self):
331
+ """Helper to get index of end-of-sentence symbol"""
332
+ return self.eos_index
333
+
334
+ def unk(self):
335
+ """Helper to get index of unk symbol"""
336
+ return self.unk_index
337
+
338
+ @classmethod
339
+ def load(cls, f):
340
+ """Loads the dictionary from a text file with the format:
341
+
342
+ ```
343
+ <symbol0> <count0>
344
+ <symbol1> <count1>
345
+ ...
346
+ ```
347
+ """
348
+ d = cls()
349
+ d.add_from_file(f)
350
+ return d
351
+
352
+ def add_from_file(self, f):
353
+ """
354
+ Loads a pre-existing dictionary from a text file and adds its symbols
355
+ to this instance.
356
+ """
357
+ if isinstance(f, str):
358
+ try:
359
+ with open(f, "r", encoding="utf-8") as fd:
360
+ self.add_from_file(fd)
361
+ except FileNotFoundError as fnfe:
362
+ raise fnfe
363
+ except UnicodeError:
364
+ raise Exception(
365
+ "Incorrect encoding detected in {}, please "
366
+ "rebuild the dataset".format(f)
367
+ )
368
+ return
369
+
370
+ lines = f.readlines()
371
+ indices_start_line = self._load_meta(lines)
372
+
373
+ for line in lines[indices_start_line:]:
374
+ try:
375
+ line, field = line.rstrip().rsplit(" ", 1)
376
+ if field == "#fairseq:overwrite":
377
+ overwrite = True
378
+ line, field = line.rsplit(" ", 1)
379
+ else:
380
+ overwrite = False
381
+ count = int(field)
382
+ word = line
383
+ if word in self and not overwrite:
384
+ raise RuntimeError(
385
+ "Duplicate word found when loading Dictionary: '{}'. "
386
+ "Duplicate words can overwrite earlier ones by adding the "
387
+ "#fairseq:overwrite flag at the end of the corresponding row "
388
+ "in the dictionary file. If using the Camembert model, please "
389
+ "download an updated copy of the model file.".format(word)
390
+ )
391
+ self.add_symbol(word, n=count, overwrite=overwrite)
392
+ except ValueError:
393
+ raise ValueError(
394
+ f"Incorrect dictionary format, expected '<token> <cnt> [flags]': \"{line}\""
395
+ )
396
+
397
+ def _save(self, f, kv_iterator):
398
+ if isinstance(f, str):
399
+ os.makedirs(os.path.dirname(f), exist_ok=True)
400
+ with open(f, "w", encoding="utf-8") as fd:
401
+ return self.save(fd)
402
+ for k, v in kv_iterator:
403
+ print("{} {}".format(k, v), file=f)
404
+
405
+ def _get_meta(self):
406
+ return [], []
407
+
408
+ def _load_meta(self, lines):
409
+ return 0
410
+
411
+ def save(self, f):
412
+ """Stores dictionary into a text file"""
413
+ ex_keys, ex_vals = self._get_meta()
414
+ self._save(
415
+ f,
416
+ zip(
417
+ ex_keys + self.symbols[self.nspecial:],
418
+ ex_vals + self.count[self.nspecial:],
419
+ ),
420
+ )
421
+
422
+ def dummy_sentence(self, length):
423
+ t = torch.Tensor(length).uniform_(self.nspecial + 1, len(self)).long()
424
+ t[-1] = self.eos()
425
+ return t
426
+
427
+ def encode_line(
428
+ self,
429
+ line,
430
+ line_tokenizer=tokenize_line,
431
+ add_if_not_exist=True,
432
+ consumer=None,
433
+ append_eos=True,
434
+ reverse_order=False,
435
+ ) -> torch.IntTensor:
436
+ words = line_tokenizer(line)
437
+ if reverse_order:
438
+ words = list(reversed(words))
439
+ nwords = len(words)
440
+ ids = torch.IntTensor(nwords + 1 if append_eos else nwords)
441
+
442
+ for i, word in enumerate(words):
443
+ if add_if_not_exist:
444
+ idx = self.add_symbol(word)
445
+ else:
446
+ idx = self.index(word)
447
+ if consumer is not None:
448
+ consumer(word, idx)
449
+ ids[i] = idx
450
+ if append_eos:
451
+ ids[nwords] = self.eos_index
452
+ return ids
453
+
454
+ @staticmethod
455
+ def _add_file_to_dictionary_single_worker(
456
+ filename,
457
+ tokenize,
458
+ eos_word,
459
+ start_offset,
460
+ end_offset,
461
+ ):
462
+ counter = Counter()
463
+ with Chunker(filename, start_offset, end_offset) as line_iterator:
464
+ for line in line_iterator:
465
+ for word in tokenize(line):
466
+ counter.update([word])
467
+ counter.update([eos_word])
468
+ return counter
469
+
470
+ @staticmethod
471
+ def add_file_to_dictionary(filename, dict, tokenize, num_workers):
472
+ def merge_result(counter):
473
+ for w, c in sorted(counter.items()):
474
+ dict.add_symbol(w, c)
475
+
476
+ local_file = filename
477
+ offsets = find_offsets(local_file, num_workers)
478
+ if num_workers > 1:
479
+ chunks = zip(offsets, offsets[1:])
480
+ pool = Pool(processes=num_workers)
481
+ results = []
482
+ for (start_offset, end_offset) in chunks:
483
+ results.append(
484
+ pool.apply_async(
485
+ Dictionary._add_file_to_dictionary_single_worker,
486
+ (
487
+ local_file,
488
+ tokenize,
489
+ dict.eos_word,
490
+ start_offset,
491
+ end_offset,
492
+ ),
493
+ )
494
+ )
495
+ pool.close()
496
+ pool.join()
497
+ for r in results:
498
+ merge_result(r.get())
499
+ else:
500
+ merge_result(
501
+ Dictionary._add_file_to_dictionary_single_worker(
502
+ local_file, tokenize, dict.eos_word, offsets[0], offsets[1]
503
+ )
504
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "cls_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "pad_token": "<pad>",
6
+ "sep_token": "</s>",
7
+ "unk_token": "<unk>"
8
+ }
tokenization_ast_t5.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from shutil import copyfile
4
+ from typing import List, Optional
5
+
6
+ import tiktoken
7
+ from transformers.tokenization_utils import PreTrainedTokenizer
8
+ from transformers.utils import logging
9
+
10
+ from .fairseq_dictionary import Dictionary
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ VOCAB_FILES_NAMES = {
15
+ "dict_path": "dict.txt"
16
+ }
17
+
18
+ GPT4ENC = tiktoken.encoding_for_model("gpt-4")
19
+
20
+
21
+ class GPT4Dictionary:
22
+ def __init__(self):
23
+ self.vocab = {}
24
+ self.words = {}
25
+ self.vocab_cnt = 4
26
+ for i in range(GPT4ENC.n_vocab):
27
+ try:
28
+ w = GPT4ENC.decode_single_token_bytes(i)
29
+ self.vocab[w] = self.vocab_cnt
30
+ self.words[self.vocab_cnt] = w
31
+ self.vocab_cnt += 1
32
+ except KeyError:
33
+ pass
34
+ self.eos_index = 2
35
+ self.words[2] = b"</s>"
36
+ self.sentinel_start = self.vocab_cnt
37
+ for i in range(1000):
38
+ self.words[self.sentinel_start + i] = f"<sen{i:03d}>".encode("utf-8")
39
+
40
+ def index(self, w):
41
+ assert w in self.vocab
42
+ return self.vocab[w]
43
+
44
+ def __getitem__(self, i):
45
+ if i in self.words:
46
+ return self.words[i]
47
+ else:
48
+ return b""
49
+
50
+
51
+ class ASTT5Tokenizer(PreTrainedTokenizer):
52
+ vocab_files_names = VOCAB_FILES_NAMES
53
+ model_input_names = ["input_ids", "attention_mask"]
54
+
55
+ def __init__(
56
+ self,
57
+ dict_path,
58
+ n_sentinel_tokens=0,
59
+ bos_token="<s>",
60
+ eos_token="</s>",
61
+ unk_token="<unk>",
62
+ pad_token="<pad>",
63
+ **kwargs
64
+ ) -> None:
65
+
66
+ self.dict_path = dict_path
67
+ self.tik_dict = GPT4Dictionary()
68
+ self.fs_dict = Dictionary.load(dict_path)
69
+ self.fs_dict_sentinel_start = len(self.fs_dict)
70
+ for i in range(n_sentinel_tokens):
71
+ self.fs_dict.add_symbol(f'<sen{i:03d}>')
72
+
73
+ if "sep_token" in kwargs:
74
+ assert kwargs["sep_token"] == eos_token
75
+ kwargs.pop("sep_token")
76
+ if "cls_token" in kwargs:
77
+ assert kwargs["cls_token"] == bos_token
78
+ kwargs.pop("cls_token")
79
+
80
+ super().__init__(
81
+ bos_token=bos_token,
82
+ eos_token=eos_token,
83
+ unk_token=unk_token,
84
+ pad_token=pad_token,
85
+ sep_token=eos_token,
86
+ cls_token=bos_token,
87
+ n_sentinel_tokens=n_sentinel_tokens,
88
+ **kwargs, )
89
+
90
+ @property
91
+ def vocab_size(self):
92
+ return len(self.fs_dict)
93
+
94
+ def get_vocab(self):
95
+ return self.fs_dict.indices
96
+
97
+ def get_special_tokens_mask(
98
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
99
+ ) -> List[int]:
100
+ """
101
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
102
+ special tokens using the tokenizer `prepare_for_model` method.
103
+ Args:
104
+ token_ids_0 (`List[int]`):
105
+ List of IDs.
106
+ token_ids_1 (`List[int]`, *optional*):
107
+ Optional second list of IDs for sequence pairs.
108
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
109
+ Whether or not the token list is already formatted with special tokens for the model.
110
+ Returns:
111
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
112
+ """
113
+ if already_has_special_tokens:
114
+ return super().get_special_tokens_mask(
115
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
116
+ )
117
+
118
+ mask_0 = [(0 if w < self.fs_dict_sentinel_start else 1) for w in token_ids_0]
119
+ mask_1 = [(0 if w < self.fs_dict_sentinel_start else 1) for w in token_ids_1]
120
+ if token_ids_1 is None:
121
+ return mask_0 + [1]
122
+ return mask_0 + [1] + mask_1 + [1]
123
+
124
+ def create_token_type_ids_from_sequences(
125
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
126
+ ) -> List[int]:
127
+ sep = [self.sep_token_id]
128
+
129
+ if token_ids_1 is None:
130
+ return len(token_ids_0 + sep) * [0]
131
+ return len(token_ids_0 + sep + token_ids_1 + sep) * [0]
132
+
133
+ def build_inputs_with_special_tokens(
134
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
135
+ ) -> List[int]:
136
+ if token_ids_1 is None:
137
+ return token_ids_0 + [self.sep_token_id]
138
+ sep = [self.sep_token_id]
139
+ return token_ids_0 + sep + token_ids_1 + sep
140
+
141
+ def _tokenize(self, text: str) -> List[str]:
142
+ parts = re.split(r"(<sen\d+>)", text)
143
+ tokenized = []
144
+ for part in parts:
145
+ if re.match(r"<sen\d+>", part):
146
+ tokenized.append(part)
147
+ else:
148
+ tokenized.extend(
149
+ [
150
+ self.fs_dict[self.tik_dict.index(w)]
151
+ for w in GPT4ENC.decode_tokens_bytes(GPT4ENC.encode_ordinary(part))
152
+ ]
153
+ )
154
+ return tokenized
155
+
156
+ def _convert_token_to_id(self, token):
157
+ return self.fs_dict.index(token)
158
+
159
+ def _convert_id_to_token(self, index):
160
+ return self.fs_dict[index]
161
+
162
+ def convert_tokens_to_string(self, tokens):
163
+ token_bytes = b"".join([self.tik_dict[self.fs_dict.index(token)] for token in tokens])
164
+ return token_bytes.decode("utf-8", errors="ignore")
165
+
166
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None):
167
+ if not os.path.isdir(save_directory):
168
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
169
+ return
170
+ out_dict_path = os.path.join(
171
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["dict_path"]
172
+ )
173
+
174
+ if os.path.abspath(self.dict_path) != os.path.abspath(out_dict_path):
175
+ copyfile(self.dict_path, out_dict_path)
176
+ logger.info(f"Copy from {self.dict_path} to {out_dict_path}")
177
+
178
+ return (out_dict_path,)
tokenizer_config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "auto_map": {
37
+ "AutoTokenizer": [
38
+ "tokenization_ast_t5.ASTT5Tokenizer",
39
+ null
40
+ ]
41
+ },
42
+ "bos_token": "<s>",
43
+ "clean_up_tokenization_spaces": true,
44
+ "cls_token": "<s>",
45
+ "eos_token": "</s>",
46
+ "model_max_length": 1000000000000000019884624838656,
47
+ "n_sentinel_tokens": 1000,
48
+ "pad_token": "<pad>",
49
+ "sep_token": "</s>",
50
+ "tokenizer_class": "ASTT5Tokenizer",
51
+ "unk_token": "<unk>"
52
+ }