Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2020 The Facebook AI Research Team Authors and The HuggingFace Inc. team.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15 16import json17import os18from functools import lru_cache19from typing import Optional20 21import regex as re22 23from ...tokenization_utils import AddedToken, PreTrainedTokenizer24from ...utils import logging25 26 27logger = logging.get_logger(__name__)28 29 30VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}31 32# See all BART models at https://huggingface.co/models?filter=bart33 34 35@lru_cache36def bytes_to_unicode():37 """38 Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control39 characters the bpe code barfs on.40 41 The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab42 if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for43 decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup44 tables between utf-8 bytes and unicode strings.45 """46 bs = (47 list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))48 )49 cs = bs[:]50 n = 051 for b in range(2**8):52 if b not in bs:53 bs.append(b)54 cs.append(2**8 + n)55 n += 156 cs = [chr(n) for n in cs]57 return dict(zip(bs, cs))58 59 60def get_pairs(word):61 """62 Return set of symbol pairs in a word.63 64 Word is represented as tuple of symbols (symbols being variable-length strings).65 """66 pairs = set()67 prev_char = word[0]68 for char in word[1:]:69 pairs.add((prev_char, char))70 prev_char = char71 return pairs72 73 74class BartTokenizer(PreTrainedTokenizer):75 """76 Constructs a BART tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.77 78 This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will79 be encoded differently whether it is at the beginning of the sentence (without space) or not:80 81 ```python82 >>> from transformers import BartTokenizer83 84 >>> tokenizer = BartTokenizer.from_pretrained("facebook/bart-base")85 >>> tokenizer("Hello world")["input_ids"]86 [0, 31414, 232, 2]87 88 >>> tokenizer(" Hello world")["input_ids"]89 [0, 20920, 232, 2]90 ```91 92 You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you93 call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.94 95 <Tip>96 97 When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).98 99 </Tip>100 101 This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to102 this superclass for more information regarding those methods.103 104 Args:105 vocab_file (`str`):106 Path to the vocabulary file.107 merges_file (`str`):108 Path to the merges file.109 errors (`str`, *optional*, defaults to `"replace"`):110 Paradigm to follow when decoding bytes to UTF-8. See111 [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.112 bos_token (`str`, *optional*, defaults to `"<s>"`):113 The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.114 115 <Tip>116 117 When building a sequence using special tokens, this is not the token that is used for the beginning of118 sequence. The token used is the `cls_token`.119 120 </Tip>121 122 eos_token (`str`, *optional*, defaults to `"</s>"`):123 The end of sequence token.124 125 <Tip>126 127 When building a sequence using special tokens, this is not the token that is used for the end of sequence.128 The token used is the `sep_token`.129 130 </Tip>131 132 sep_token (`str`, *optional*, defaults to `"</s>"`):133 The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for134 sequence classification or for a text and a question for question answering. It is also used as the last135 token of a sequence built with special tokens.136 cls_token (`str`, *optional*, defaults to `"<s>"`):137 The classifier token which is used when doing sequence classification (classification of the whole sequence138 instead of per-token classification). It is the first token of the sequence when built with special tokens.139 unk_token (`str`, *optional*, defaults to `"<unk>"`):140 The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this141 token instead.142 pad_token (`str`, *optional*, defaults to `"<pad>"`):143 The token used for padding, for example when batching sequences of different lengths.144 mask_token (`str`, *optional*, defaults to `"<mask>"`):145 The token used for masking values. This is the token used when training this model with masked language146 modeling. This is the token which the model will try to predict.147 add_prefix_space (`bool`, *optional*, defaults to `False`):148 Whether or not to add an initial space to the input. This allows to treat the leading word just as any149 other word. (BART tokenizer detect beginning of words by the preceding space).150 """151 152 vocab_files_names = VOCAB_FILES_NAMES153 model_input_names = ["input_ids", "attention_mask"]154 155 def __init__(156 self,157 vocab_file,158 merges_file,159 errors="replace",160 bos_token="<s>",161 eos_token="</s>",162 sep_token="</s>",163 cls_token="<s>",164 unk_token="<unk>",165 pad_token="<pad>",166 mask_token="<mask>",167 add_prefix_space=False,168 **kwargs,169 ):170 bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token171 eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token172 sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token173 cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token174 unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token175 pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token176 177 # Mask token behave like a normal word, i.e. include the space before it178 mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token179 180 with open(vocab_file, encoding="utf-8") as vocab_handle:181 self.encoder = json.load(vocab_handle)182 self.decoder = {v: k for k, v in self.encoder.items()}183 self.errors = errors # how to handle errors in decoding184 self.byte_encoder = bytes_to_unicode()185 self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}186 with open(merges_file, encoding="utf-8") as merges_handle:187 bpe_merges = merges_handle.read().split("\n")[1:-1]188 bpe_merges = [tuple(merge.split()) for merge in bpe_merges]189 self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))190 self.cache = {}191 self.add_prefix_space = add_prefix_space192 193 # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions194 self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")195 196 super().__init__(197 errors=errors,198 bos_token=bos_token,199 eos_token=eos_token,200 unk_token=unk_token,201 sep_token=sep_token,202 cls_token=cls_token,203 pad_token=pad_token,204 mask_token=mask_token,205 add_prefix_space=add_prefix_space,206 **kwargs,207 )208 209 @property210 def vocab_size(self):211 return len(self.encoder)212 213 def get_vocab(self):214 return dict(self.encoder, **self.added_tokens_encoder)215 216 def bpe(self, token):217 if token in self.cache:218 return self.cache[token]219 word = tuple(token)220 pairs = get_pairs(word)221 222 if not pairs:223 return token224 225 while True:226 bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))227 if bigram not in self.bpe_ranks:228 break229 first, second = bigram230 new_word = []231 i = 0232 while i < len(word):233 try:234 j = word.index(first, i)235 except ValueError:236 new_word.extend(word[i:])237 break238 else:239 new_word.extend(word[i:j])240 i = j241 242 if word[i] == first and i < len(word) - 1 and word[i + 1] == second:243 new_word.append(first + second)244 i += 2245 else:246 new_word.append(word[i])247 i += 1248 new_word = tuple(new_word)249 word = new_word250 if len(word) == 1:251 break252 else:253 pairs = get_pairs(word)254 word = " ".join(word)255 self.cache[token] = word256 return word257 258 def _tokenize(self, text):259 """Tokenize a string."""260 bpe_tokens = []261 for token in re.findall(self.pat, text):262 token = "".join(263 self.byte_encoder[b] for b in token.encode("utf-8")264 ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)265 bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))266 return bpe_tokens267 268 def _convert_token_to_id(self, token):269 """Converts a token (str) in an id using the vocab."""270 return self.encoder.get(token, self.encoder.get(self.unk_token))271 272 def _convert_id_to_token(self, index):273 """Converts an index (integer) in a token (str) using the vocab."""274 return self.decoder.get(index)275 276 def convert_tokens_to_string(self, tokens):277 """Converts a sequence of tokens (string) in a single string."""278 text = "".join(tokens)279 text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)280 return text281 282 def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:283 if not os.path.isdir(save_directory):284 logger.error(f"Vocabulary path ({save_directory}) should be a directory")285 return286 vocab_file = os.path.join(287 save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]288 )289 merge_file = os.path.join(290 save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]291 )292 293 with open(vocab_file, "w", encoding="utf-8") as f:294 f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")295 296 index = 0297 with open(merge_file, "w", encoding="utf-8") as writer:298 writer.write("#version: 0.2\n")299 for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):300 if index != token_index:301 logger.warning(302 f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."303 " Please check that the tokenizer is not corrupted!"304 )305 index = token_index306 writer.write(" ".join(bpe_tokens) + "\n")307 index += 1308 309 return vocab_file, merge_file310 311 def build_inputs_with_special_tokens(312 self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None313 ) -> list[int]:314 """315 Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and316 adding special tokens. A BART sequence has the following format:317 318 - single sequence: `<s> X </s>`319 - pair of sequences: `<s> A </s></s> B </s>`320 321 Args:322 token_ids_0 (`list[int]`):323 List of IDs to which the special tokens will be added.324 token_ids_1 (`list[int]`, *optional*):325 Optional second list of IDs for sequence pairs.326 327 Returns:328 `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.329 """330 if token_ids_1 is None:331 return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]332 cls = [self.cls_token_id]333 sep = [self.sep_token_id]334 return cls + token_ids_0 + sep + sep + token_ids_1 + sep335 336 def get_special_tokens_mask(337 self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False338 ) -> list[int]:339 """340 Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding341 special tokens using the tokenizer `prepare_for_model` method.342 343 Args:344 token_ids_0 (`list[int]`):345 List of IDs.346 token_ids_1 (`list[int]`, *optional*):347 Optional second list of IDs for sequence pairs.348 already_has_special_tokens (`bool`, *optional*, defaults to `False`):349 Whether or not the token list is already formatted with special tokens for the model.350 351 Returns:352 `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.353 """354 if already_has_special_tokens:355 return super().get_special_tokens_mask(356 token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True357 )358 359 if token_ids_1 is None:360 return [1] + ([0] * len(token_ids_0)) + [1]361 return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]362 363 def create_token_type_ids_from_sequences(364 self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None365 ) -> list[int]:366 """367 Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not368 make use of token type ids, therefore a list of zeros is returned.369 370 Args:371 token_ids_0 (`list[int]`):372 List of IDs.373 token_ids_1 (`list[int]`, *optional*):374 Optional second list of IDs for sequence pairs.375 376 Returns:377 `list[int]`: List of zeros.378 """379 sep = [self.sep_token_id]380 cls = [self.cls_token_id]381 382 if token_ids_1 is None:383 return len(cls + token_ids_0 + sep) * [0]384 return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]385 386 def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):387 add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)388 if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):389 text = " " + text390 return (text, kwargs)391 392 393__all__ = ["BartTokenizer"]394 