dqnguyen commited on
Commit
558969f
1 Parent(s): 07a52cc

Upload 3 files

Browse files
__init__.py ADDED
File without changes
tokenization_phobert.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
3
+ # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
4
+ #
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 PhoBERT"""
17
+
18
+
19
+ import os
20
+ import re
21
+ from shutil import copyfile
22
+ from typing import List, Optional, Tuple
23
+
24
+ from transformers.tokenization_utils import PreTrainedTokenizer
25
+ from transformers.utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {
31
+ "vocab_file": "vocab.txt",
32
+ "merges_file": "bpe.codes",
33
+ }
34
+
35
+ PRETRAINED_VOCAB_FILES_MAP = {
36
+ "vocab_file": {
37
+ "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt",
38
+ "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt",
39
+ },
40
+ "merges_file": {
41
+ "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes",
42
+ "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes",
43
+ },
44
+ }
45
+
46
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
47
+ "vinai/phobert-base": 256,
48
+ "vinai/phobert-large": 256,
49
+ }
50
+
51
+
52
+ def get_pairs(word):
53
+ """
54
+ Return set of symbol pairs in a word.
55
+
56
+ Word is represented as tuple of symbols (symbols being variable-length strings).
57
+ """
58
+ pairs = set()
59
+ prev_char = word[0]
60
+ for char in word[1:]:
61
+ pairs.add((prev_char, char))
62
+ prev_char = char
63
+
64
+ pairs = set(pairs)
65
+ return pairs
66
+
67
+
68
+ class PhobertTokenizer(PreTrainedTokenizer):
69
+ """
70
+ Construct a PhoBERT tokenizer. Based on Byte-Pair-Encoding.
71
+
72
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
73
+ this superclass for more information regarding those methods.
74
+
75
+ Args:
76
+ vocab_file (`str`):
77
+ Path to the vocabulary file.
78
+ merges_file (`str`):
79
+ Path to the merges file.
80
+ bos_token (`st`, *optional*, defaults to `"<s>"`):
81
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
82
+
83
+ <Tip>
84
+
85
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
86
+ sequence. The token used is the `cls_token`.
87
+
88
+ </Tip>
89
+
90
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
91
+ The end of sequence token.
92
+
93
+ <Tip>
94
+
95
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
96
+ The token used is the `sep_token`.
97
+
98
+ </Tip>
99
+
100
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
101
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
102
+ sequence classification or for a text and a question for question answering. It is also used as the last
103
+ token of a sequence built with special tokens.
104
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
105
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
106
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
107
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
108
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
109
+ token instead.
110
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
111
+ The token used for padding, for example when batching sequences of different lengths.
112
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
113
+ The token used for masking values. This is the token used when training this model with masked language
114
+ modeling. This is the token which the model will try to predict.
115
+ """
116
+
117
+ vocab_files_names = VOCAB_FILES_NAMES
118
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
119
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
120
+ model_input_names = ["input_ids", "attention_mask"]
121
+
122
+ def __init__(
123
+ self,
124
+ vocab_file,
125
+ merges_file,
126
+ bos_token="<s>",
127
+ eos_token="</s>",
128
+ sep_token="</s>",
129
+ cls_token="<s>",
130
+ unk_token="<unk>",
131
+ pad_token="<pad>",
132
+ mask_token="<mask>",
133
+ **kwargs
134
+ ):
135
+ super().__init__(
136
+ bos_token=bos_token,
137
+ eos_token=eos_token,
138
+ unk_token=unk_token,
139
+ sep_token=sep_token,
140
+ cls_token=cls_token,
141
+ pad_token=pad_token,
142
+ mask_token=mask_token,
143
+ **kwargs,
144
+ )
145
+
146
+ self.vocab_file = vocab_file
147
+ self.merges_file = merges_file
148
+
149
+ self.encoder = {}
150
+ self.encoder[self.bos_token] = 0
151
+ self.encoder[self.pad_token] = 1
152
+ self.encoder[self.eos_token] = 2
153
+ self.encoder[self.unk_token] = 3
154
+
155
+ self.add_from_file(vocab_file)
156
+ self.encoder[self.mask_token] = len(self.encoder)
157
+
158
+ self.decoder = {v: k for k, v in self.encoder.items()}
159
+
160
+ with open(merges_file, encoding="utf-8") as merges_handle:
161
+ merges = merges_handle.read().split("\n")[:-1]
162
+ merges = [tuple(merge.split()[:-1]) for merge in merges]
163
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
164
+ self.cache = {}
165
+
166
+ def build_inputs_with_special_tokens(
167
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
168
+ ) -> List[int]:
169
+ """
170
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
171
+ adding special tokens. A PhoBERT sequence has the following format:
172
+
173
+ - single sequence: `<s> X </s>`
174
+ - pair of sequences: `<s> A </s></s> B </s>`
175
+
176
+ Args:
177
+ token_ids_0 (`List[int]`):
178
+ List of IDs to which the special tokens will be added.
179
+ token_ids_1 (`List[int]`, *optional*):
180
+ Optional second list of IDs for sequence pairs.
181
+
182
+ Returns:
183
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
184
+ """
185
+
186
+ if token_ids_1 is None:
187
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
188
+ cls = [self.cls_token_id]
189
+ sep = [self.sep_token_id]
190
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
191
+
192
+ def get_special_tokens_mask(
193
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
194
+ ) -> List[int]:
195
+ """
196
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
197
+ special tokens using the tokenizer `prepare_for_model` method.
198
+
199
+ Args:
200
+ token_ids_0 (`List[int]`):
201
+ List of IDs.
202
+ token_ids_1 (`List[int]`, *optional*):
203
+ Optional second list of IDs for sequence pairs.
204
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
205
+ Whether or not the token list is already formatted with special tokens for the model.
206
+
207
+ Returns:
208
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
209
+ """
210
+
211
+ if already_has_special_tokens:
212
+ return super().get_special_tokens_mask(
213
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
214
+ )
215
+
216
+ if token_ids_1 is None:
217
+ return [1] + ([0] * len(token_ids_0)) + [1]
218
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
219
+
220
+ def create_token_type_ids_from_sequences(
221
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
222
+ ) -> List[int]:
223
+ """
224
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. PhoBERT does not
225
+ make use of token type ids, therefore a list of zeros is returned.
226
+
227
+ Args:
228
+ token_ids_0 (`List[int]`):
229
+ List of IDs.
230
+ token_ids_1 (`List[int]`, *optional*):
231
+ Optional second list of IDs for sequence pairs.
232
+
233
+ Returns:
234
+ `List[int]`: List of zeros.
235
+ """
236
+
237
+ sep = [self.sep_token_id]
238
+ cls = [self.cls_token_id]
239
+
240
+ if token_ids_1 is None:
241
+ return len(cls + token_ids_0 + sep) * [0]
242
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
243
+
244
+ @property
245
+ def vocab_size(self):
246
+ return len(self.encoder)
247
+
248
+ def get_vocab(self):
249
+ return dict(self.encoder, **self.added_tokens_encoder)
250
+
251
+ def bpe(self, token):
252
+ if token in self.cache:
253
+ return self.cache[token]
254
+ word = tuple(token)
255
+ word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
256
+ pairs = get_pairs(word)
257
+
258
+ if not pairs:
259
+ return token
260
+
261
+ while True:
262
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
263
+ if bigram not in self.bpe_ranks:
264
+ break
265
+ first, second = bigram
266
+ new_word = []
267
+ i = 0
268
+ while i < len(word):
269
+ try:
270
+ j = word.index(first, i)
271
+ except ValueError:
272
+ new_word.extend(word[i:])
273
+ break
274
+ else:
275
+ new_word.extend(word[i:j])
276
+ i = j
277
+
278
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
279
+ new_word.append(first + second)
280
+ i += 2
281
+ else:
282
+ new_word.append(word[i])
283
+ i += 1
284
+ new_word = tuple(new_word)
285
+ word = new_word
286
+ if len(word) == 1:
287
+ break
288
+ else:
289
+ pairs = get_pairs(word)
290
+ word = "@@ ".join(word)
291
+ word = word[:-4]
292
+ self.cache[token] = word
293
+ return word
294
+
295
+ def _tokenize(self, text):
296
+ """Tokenize a string."""
297
+ split_tokens = []
298
+
299
+ words = re.findall(r"\S+\n?", text)
300
+
301
+ for token in words:
302
+ split_tokens.extend([t for t in self.bpe(token).split(" ")])
303
+ return split_tokens
304
+
305
+ def _convert_token_to_id(self, token):
306
+ """Converts a token (str) in an id using the vocab."""
307
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
308
+
309
+ def _convert_id_to_token(self, index):
310
+ """Converts an index (integer) in a token (str) using the vocab."""
311
+ return self.decoder.get(index, self.unk_token)
312
+
313
+ def convert_tokens_to_string(self, tokens):
314
+ """Converts a sequence of tokens (string) in a single string."""
315
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
316
+ return out_string
317
+
318
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
319
+ if not os.path.isdir(save_directory):
320
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory.")
321
+ return
322
+
323
+ out_vocab_file = os.path.join(
324
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
325
+ )
326
+
327
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
328
+ copyfile(self.vocab_file, out_vocab_file)
329
+ elif not os.path.isfile(self.vocab_file):
330
+ with open(out_vocab_file, "w", encoding="utf-8") as fp:
331
+ for token, value in self.encoder.items():
332
+ if token not in self.all_special_tokens:
333
+ fp.write(f"{str(token)} 1\n")
334
+
335
+ out_merges_file = os.path.join(
336
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
337
+ )
338
+
339
+ if os.path.abspath(self.merges_file) != os.path.abspath(out_merges_file) and os.path.isfile(self.merges_file):
340
+ copyfile(self.merges_file, out_merges_file)
341
+ elif not os.path.isfile(self.merges_file):
342
+ index = 0
343
+ with open(out_merges_file, "w", encoding="utf-8") as writer:
344
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
345
+ if index != token_index:
346
+ logger.warning(
347
+ f"Saving vocabulary to {out_merges_file}: BPE merge indices are not consecutive."
348
+ " Please check that the tokenizer is not corrupted!"
349
+ )
350
+ index = token_index
351
+ writer.write(" ".join(bpe_tokens) + " 1\n")
352
+ index += 1
353
+
354
+ return (out_vocab_file, out_merges_file)
355
+
356
+ # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
357
+ # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
358
+ # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
359
+ # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
360
+ # return ''.join(tokens_generated_so_far)
361
+
362
+ def add_from_file(self, f):
363
+ """
364
+ Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
365
+ """
366
+ if isinstance(f, str):
367
+ try:
368
+ with open(f, "r", encoding="utf-8") as fd:
369
+ self.add_from_file(fd)
370
+ except FileNotFoundError as fnfe:
371
+ raise fnfe
372
+ except UnicodeError:
373
+ raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
374
+ return
375
+
376
+ lines = f.readlines()
377
+ for lineTmp in lines:
378
+ line = lineTmp.strip()
379
+ idx = line.rfind(" ")
380
+ if idx == -1:
381
+ raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
382
+ word = line[:idx]
383
+ self.encoder[word] = len(self.encoder)
tokenization_phobert_fast.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
3
+ # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
4
+ #
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 PhoBERT"""
17
+
18
+ import os
19
+ from collections import defaultdict
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple, Union
22
+
23
+ from transformers.tokenization_utils_base import EncodingFast
24
+
25
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
26
+ from transformers.utils import logging
27
+ from .tokenization_phobert import PhobertTokenizer
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ VOCAB_FILES_NAMES = {
33
+ "vocab_file": "vocab.txt",
34
+ "merges_file": "bpe.codes",
35
+ "tokenizer_file": "tokenizer.json",
36
+ }
37
+
38
+ PRETRAINED_VOCAB_FILES_MAP = {
39
+ "vocab_file": {
40
+ "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt",
41
+ "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt",
42
+ },
43
+ "merges_file": {
44
+ "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes",
45
+ "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes",
46
+ },
47
+ "tokenizer_file": {
48
+ "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/tokenizer.json",
49
+ "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/tokenizer.json",
50
+ },
51
+ }
52
+
53
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
54
+ "vinai/phobert-base": 256,
55
+ "vinai/phobert-large": 256,
56
+ }
57
+
58
+
59
+ class PhobertTokenizerFast(PreTrainedTokenizerFast):
60
+ """
61
+ Construct a "Fast" BPE tokenizer for PhoBERT (backed by HuggingFace's *tokenizers* library).
62
+
63
+ Peculiarities:
64
+
65
+ - uses BERT's pre-tokenizer: BertPreTokenizer splits tokens on spaces, and also on punctuation. Each occurrence of
66
+ a punctuation character will be treated separately.
67
+
68
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the methods. Users should refer to the
69
+ superclass for more information regarding methods.
70
+
71
+ Args:
72
+ vocab_file (`str`):
73
+ Path to the vocabulary file.
74
+ merges_file (`str`):
75
+ Path to the merges file.
76
+ """
77
+
78
+ vocab_files_names = VOCAB_FILES_NAMES
79
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
80
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
81
+ model_input_names = ["input_ids", "attention_mask"]
82
+ slow_tokenizer_class = PhobertTokenizer
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_file=None,
87
+ merges_file=None,
88
+ tokenizer_file=None,
89
+ bos_token="<s>",
90
+ eos_token="</s>",
91
+ sep_token="</s>",
92
+ cls_token="<s>",
93
+ unk_token="<unk>",
94
+ pad_token="<pad>",
95
+ mask_token="<mask>",
96
+ **kwargs
97
+ ):
98
+ super().__init__(
99
+ vocab_file,
100
+ merges_file,
101
+ tokenizer_file=tokenizer_file,
102
+ bos_token=bos_token,
103
+ eos_token=eos_token,
104
+ sep_token=sep_token,
105
+ cls_token=cls_token,
106
+ unk_token=unk_token,
107
+ pad_token=pad_token,
108
+ mask_token=mask_token,
109
+ **kwargs,
110
+ )
111
+
112
+ self.vocab_file = vocab_file
113
+ self.merges_file = merges_file
114
+ self.can_save_slow_tokenizer = False if not self.vocab_file else True
115
+
116
+ def get_added_vocab_hacking(self):
117
+ """
118
+ Returns the added tokens in the vocabulary as a dictionary of token to index.
119
+
120
+ Returns:
121
+ `Dict[str, int], Dict[int, int]`: The added tokens, and their original and new ids
122
+ """
123
+ base_vocab_size = self._tokenizer.get_vocab_size(with_added_tokens=False)
124
+ full_vocab_size = self._tokenizer.get_vocab_size(with_added_tokens=True)
125
+ if full_vocab_size == base_vocab_size:
126
+ return {}, {}
127
+
128
+ # Tokens in added_vocab should have ids that are equal to or larger than the size of base_vocab
129
+ added_vocab = dict(
130
+ (self._tokenizer.id_to_token(index), index + 1 - base_vocab_size + self.mask_token_id)
131
+ for index in range(base_vocab_size, full_vocab_size)
132
+ )
133
+
134
+ id_mapping = dict((index, self._tokenizer.token_to_id(tok)) for tok, index in added_vocab.items())
135
+
136
+ return added_vocab, id_mapping
137
+
138
+ def _decode(
139
+ self,
140
+ token_ids: Union[int, List[int]],
141
+ skip_special_tokens: bool = False,
142
+ clean_up_tokenization_spaces: bool = True,
143
+ **kwargs
144
+ ) -> str:
145
+ self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
146
+
147
+ if isinstance(token_ids, int):
148
+ token_ids = [token_ids]
149
+
150
+ # Mapping ids into their original values
151
+ _, id_mapping = self.get_added_vocab_hacking()
152
+ if len(id_mapping) > 0:
153
+ token_ids = [id_mapping[id] if id in id_mapping else id for id in token_ids]
154
+
155
+ text = self._tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
156
+
157
+ if clean_up_tokenization_spaces:
158
+ clean_text = self.clean_up_tokenization(text)
159
+ return clean_text
160
+ else:
161
+ return text
162
+
163
+ def _convert_encoding(
164
+ self,
165
+ encoding: EncodingFast,
166
+ return_token_type_ids: Optional[bool] = None,
167
+ return_attention_mask: Optional[bool] = None,
168
+ return_overflowing_tokens: bool = False,
169
+ return_special_tokens_mask: bool = False,
170
+ return_offsets_mapping: bool = False,
171
+ return_length: bool = False,
172
+ verbose: bool = True,
173
+ ) -> Tuple[Dict[str, Any], List[EncodingFast]]:
174
+ """
175
+ Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list
176
+ of encodings, take care of building a batch from overflowing tokens.
177
+
178
+ Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are
179
+ lists (overflows) of lists (tokens).
180
+
181
+ Output shape: (overflows, sequence length)
182
+ """
183
+ if return_token_type_ids is None:
184
+ return_token_type_ids = "token_type_ids" in self.model_input_names
185
+ if return_attention_mask is None:
186
+ return_attention_mask = "attention_mask" in self.model_input_names
187
+
188
+ if return_overflowing_tokens and encoding.overflowing is not None:
189
+ encodings = [encoding] + encoding.overflowing
190
+ else:
191
+ encodings = [encoding]
192
+
193
+ encoding_dict = defaultdict(list)
194
+ added_vocab, _ = self.get_added_vocab_hacking()
195
+ for e in encodings:
196
+ # encoding_dict["input_ids"].append(e.ids)
197
+ # Reassign ids of tokens due to the hacking strategy
198
+ ids = []
199
+ for id, token in zip(e.ids, e.tokens):
200
+ if id <= self.mask_token_id:
201
+ ids.append(id)
202
+ else:
203
+ if token.strip() in added_vocab:
204
+ ids.append(added_vocab[token.strip()])
205
+ else:
206
+ ids.append(self.unk_token_id)
207
+
208
+ encoding_dict["input_ids"].append(ids)
209
+
210
+ if return_token_type_ids:
211
+ encoding_dict["token_type_ids"].append(e.type_ids)
212
+ if return_attention_mask:
213
+ encoding_dict["attention_mask"].append(e.attention_mask)
214
+ if return_special_tokens_mask:
215
+ encoding_dict["special_tokens_mask"].append(e.special_tokens_mask)
216
+ if return_offsets_mapping:
217
+ encoding_dict["offset_mapping"].append(e.offsets)
218
+ if return_length:
219
+ # encoding_dict["length"].append(len(e.ids))
220
+ encoding_dict["length"].append(len(ids))
221
+
222
+ return encoding_dict, encodings
223
+
224
+ def build_inputs_with_special_tokens(
225
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
226
+ ) -> List[int]:
227
+ """
228
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
229
+ adding special tokens. A PhoBERT sequence has the following format:
230
+
231
+ - single sequence: `<s> X </s>`
232
+ - pair of sequences: `<s> A </s></s> B </s>`
233
+
234
+ Args:
235
+ token_ids_0 (`List[int]`):
236
+ List of IDs to which the special tokens will be added.
237
+ token_ids_1 (`List[int]`, *optional*):
238
+ Optional second list of IDs for sequence pairs.
239
+
240
+ Returns:
241
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
242
+ """
243
+
244
+ if token_ids_1 is None:
245
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
246
+ cls = [self.cls_token_id]
247
+ sep = [self.sep_token_id]
248
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
249
+
250
+ def get_special_tokens_mask(
251
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
252
+ ) -> List[int]:
253
+ """
254
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
255
+ special tokens using the tokenizer `prepare_for_model` method.
256
+
257
+ Args:
258
+ token_ids_0 (`List[int]`):
259
+ List of IDs.
260
+ token_ids_1 (`List[int]`, *optional*):
261
+ Optional second list of IDs for sequence pairs.
262
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
263
+ Whether or not the token list is already formatted with special tokens for the model.
264
+
265
+ Returns:
266
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
267
+ """
268
+
269
+ if already_has_special_tokens:
270
+ return super().get_special_tokens_mask(
271
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
272
+ )
273
+
274
+ if token_ids_1 is None:
275
+ return [1] + ([0] * len(token_ids_0)) + [1]
276
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
277
+
278
+ def create_token_type_ids_from_sequences(
279
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
280
+ ) -> List[int]:
281
+ """
282
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. PhoBERT does not
283
+ make use of token type ids, therefore a list of zeros is returned.
284
+
285
+ Args:
286
+ token_ids_0 (`List[int]`):
287
+ List of IDs.
288
+ token_ids_1 (`List[int]`, *optional*):
289
+ Optional second list of IDs for sequence pairs.
290
+
291
+ Returns:
292
+ `List[int]`: List of zeros.
293
+
294
+ """
295
+
296
+ sep = [self.sep_token_id]
297
+ cls = [self.cls_token_id]
298
+
299
+ if token_ids_1 is None:
300
+ return len(cls + token_ids_0 + sep) * [0]
301
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
302
+
303
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
304
+ if not self.can_save_slow_tokenizer:
305
+ raise ValueError(
306
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
307
+ "tokenizer."
308
+ )
309
+
310
+ if not os.path.isdir(save_directory):
311
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory.")
312
+ return
313
+
314
+ out_vocab_file = os.path.join(
315
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
316
+ )
317
+
318
+ out_merges_file = os.path.join(
319
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
320
+ )
321
+
322
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
323
+ copyfile(self.vocab_file, out_vocab_file)
324
+
325
+ if os.path.abspath(self.merges_file) != os.path.abspath(out_merges_file):
326
+ copyfile(self.merges_file, out_merges_file)
327
+
328
+ return (out_vocab_file, out_merges_file)