tokenization_bart.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # coding=utf-8
  2. # 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 at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # 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 and
  14. # limitations under the License.
  15. import json
  16. import os
  17. from functools import lru_cache
  18. from typing import List, Optional, Tuple
  19. import regex as re
  20. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
  24. # See all BART models at https://huggingface.co/models?filter=bart
  25. @lru_cache()
  26. def bytes_to_unicode():
  27. """
  28. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  29. characters the bpe code barfs on.
  30. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  31. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  32. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  33. tables between utf-8 bytes and unicode strings.
  34. """
  35. bs = (
  36. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  37. )
  38. cs = bs[:]
  39. n = 0
  40. for b in range(2**8):
  41. if b not in bs:
  42. bs.append(b)
  43. cs.append(2**8 + n)
  44. n += 1
  45. cs = [chr(n) for n in cs]
  46. return dict(zip(bs, cs))
  47. def get_pairs(word):
  48. """
  49. Return set of symbol pairs in a word.
  50. Word is represented as tuple of symbols (symbols being variable-length strings).
  51. """
  52. pairs = set()
  53. prev_char = word[0]
  54. for char in word[1:]:
  55. pairs.add((prev_char, char))
  56. prev_char = char
  57. return pairs
  58. class BartTokenizer(PreTrainedTokenizer):
  59. """
  60. Constructs a BART tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.
  61. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  62. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  63. ```python
  64. >>> from transformers import BartTokenizer
  65. >>> tokenizer = BartTokenizer.from_pretrained("facebook/bart-base")
  66. >>> tokenizer("Hello world")["input_ids"]
  67. [0, 31414, 232, 2]
  68. >>> tokenizer(" Hello world")["input_ids"]
  69. [0, 20920, 232, 2]
  70. ```
  71. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  72. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  73. <Tip>
  74. When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
  75. </Tip>
  76. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  77. this superclass for more information regarding those methods.
  78. Args:
  79. vocab_file (`str`):
  80. Path to the vocabulary file.
  81. merges_file (`str`):
  82. Path to the merges file.
  83. errors (`str`, *optional*, defaults to `"replace"`):
  84. Paradigm to follow when decoding bytes to UTF-8. See
  85. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  86. bos_token (`str`, *optional*, defaults to `"<s>"`):
  87. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  88. <Tip>
  89. When building a sequence using special tokens, this is not the token that is used for the beginning of
  90. sequence. The token used is the `cls_token`.
  91. </Tip>
  92. eos_token (`str`, *optional*, defaults to `"</s>"`):
  93. The end of sequence token.
  94. <Tip>
  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. </Tip>
  98. sep_token (`str`, *optional*, defaults to `"</s>"`):
  99. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  100. sequence classification or for a text and a question for question answering. It is also used as the last
  101. token of a sequence built with special tokens.
  102. cls_token (`str`, *optional*, defaults to `"<s>"`):
  103. The classifier token which is used when doing sequence classification (classification of the whole sequence
  104. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  105. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  106. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  107. token instead.
  108. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  109. The token used for padding, for example when batching sequences of different lengths.
  110. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  111. The token used for masking values. This is the token used when training this model with masked language
  112. modeling. This is the token which the model will try to predict.
  113. add_prefix_space (`bool`, *optional*, defaults to `False`):
  114. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  115. other word. (BART tokenizer detect beginning of words by the preceding space).
  116. """
  117. vocab_files_names = VOCAB_FILES_NAMES
  118. model_input_names = ["input_ids", "attention_mask"]
  119. def __init__(
  120. self,
  121. vocab_file,
  122. merges_file,
  123. errors="replace",
  124. bos_token="<s>",
  125. eos_token="</s>",
  126. sep_token="</s>",
  127. cls_token="<s>",
  128. unk_token="<unk>",
  129. pad_token="<pad>",
  130. mask_token="<mask>",
  131. add_prefix_space=False,
  132. **kwargs,
  133. ):
  134. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  135. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  136. sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
  137. cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
  138. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  139. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  140. # Mask token behave like a normal word, i.e. include the space before it
  141. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  142. with open(vocab_file, encoding="utf-8") as vocab_handle:
  143. self.encoder = json.load(vocab_handle)
  144. self.decoder = {v: k for k, v in self.encoder.items()}
  145. self.errors = errors # how to handle errors in decoding
  146. self.byte_encoder = bytes_to_unicode()
  147. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  148. with open(merges_file, encoding="utf-8") as merges_handle:
  149. bpe_merges = merges_handle.read().split("\n")[1:-1]
  150. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  151. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  152. self.cache = {}
  153. self.add_prefix_space = add_prefix_space
  154. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  155. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  156. super().__init__(
  157. errors=errors,
  158. bos_token=bos_token,
  159. eos_token=eos_token,
  160. unk_token=unk_token,
  161. sep_token=sep_token,
  162. cls_token=cls_token,
  163. pad_token=pad_token,
  164. mask_token=mask_token,
  165. add_prefix_space=add_prefix_space,
  166. **kwargs,
  167. )
  168. @property
  169. def vocab_size(self):
  170. return len(self.encoder)
  171. def get_vocab(self):
  172. return dict(self.encoder, **self.added_tokens_encoder)
  173. def bpe(self, token):
  174. if token in self.cache:
  175. return self.cache[token]
  176. word = tuple(token)
  177. pairs = get_pairs(word)
  178. if not pairs:
  179. return token
  180. while True:
  181. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  182. if bigram not in self.bpe_ranks:
  183. break
  184. first, second = bigram
  185. new_word = []
  186. i = 0
  187. while i < len(word):
  188. try:
  189. j = word.index(first, i)
  190. except ValueError:
  191. new_word.extend(word[i:])
  192. break
  193. else:
  194. new_word.extend(word[i:j])
  195. i = j
  196. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  197. new_word.append(first + second)
  198. i += 2
  199. else:
  200. new_word.append(word[i])
  201. i += 1
  202. new_word = tuple(new_word)
  203. word = new_word
  204. if len(word) == 1:
  205. break
  206. else:
  207. pairs = get_pairs(word)
  208. word = " ".join(word)
  209. self.cache[token] = word
  210. return word
  211. def _tokenize(self, text):
  212. """Tokenize a string."""
  213. bpe_tokens = []
  214. for token in re.findall(self.pat, text):
  215. token = "".join(
  216. self.byte_encoder[b] for b in token.encode("utf-8")
  217. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  218. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  219. return bpe_tokens
  220. def _convert_token_to_id(self, token):
  221. """Converts a token (str) in an id using the vocab."""
  222. return self.encoder.get(token, self.encoder.get(self.unk_token))
  223. def _convert_id_to_token(self, index):
  224. """Converts an index (integer) in a token (str) using the vocab."""
  225. return self.decoder.get(index)
  226. def convert_tokens_to_string(self, tokens):
  227. """Converts a sequence of tokens (string) in a single string."""
  228. text = "".join(tokens)
  229. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  230. return text
  231. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  232. if not os.path.isdir(save_directory):
  233. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  234. return
  235. vocab_file = os.path.join(
  236. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  237. )
  238. merge_file = os.path.join(
  239. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  240. )
  241. with open(vocab_file, "w", encoding="utf-8") as f:
  242. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  243. index = 0
  244. with open(merge_file, "w", encoding="utf-8") as writer:
  245. writer.write("#version: 0.2\n")
  246. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  247. if index != token_index:
  248. logger.warning(
  249. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  250. " Please check that the tokenizer is not corrupted!"
  251. )
  252. index = token_index
  253. writer.write(" ".join(bpe_tokens) + "\n")
  254. index += 1
  255. return vocab_file, merge_file
  256. def build_inputs_with_special_tokens(
  257. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  258. ) -> List[int]:
  259. """
  260. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  261. adding special tokens. A BART sequence has the following format:
  262. - single sequence: `<s> X </s>`
  263. - pair of sequences: `<s> A </s></s> B </s>`
  264. Args:
  265. token_ids_0 (`List[int]`):
  266. List of IDs to which the special tokens will be added.
  267. token_ids_1 (`List[int]`, *optional*):
  268. Optional second list of IDs for sequence pairs.
  269. Returns:
  270. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  271. """
  272. if token_ids_1 is None:
  273. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  274. cls = [self.cls_token_id]
  275. sep = [self.sep_token_id]
  276. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  277. def get_special_tokens_mask(
  278. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  279. ) -> List[int]:
  280. """
  281. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  282. special tokens using the tokenizer `prepare_for_model` method.
  283. Args:
  284. token_ids_0 (`List[int]`):
  285. List of IDs.
  286. token_ids_1 (`List[int]`, *optional*):
  287. Optional second list of IDs for sequence pairs.
  288. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  289. Whether or not the token list is already formatted with special tokens for the model.
  290. Returns:
  291. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  292. """
  293. if already_has_special_tokens:
  294. return super().get_special_tokens_mask(
  295. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  296. )
  297. if token_ids_1 is None:
  298. return [1] + ([0] * len(token_ids_0)) + [1]
  299. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  300. def create_token_type_ids_from_sequences(
  301. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  302. ) -> List[int]:
  303. """
  304. Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
  305. make use of token type ids, therefore a list of zeros is returned.
  306. Args:
  307. token_ids_0 (`List[int]`):
  308. List of IDs.
  309. token_ids_1 (`List[int]`, *optional*):
  310. Optional second list of IDs for sequence pairs.
  311. Returns:
  312. `List[int]`: List of zeros.
  313. """
  314. sep = [self.sep_token_id]
  315. cls = [self.cls_token_id]
  316. if token_ids_1 is None:
  317. return len(cls + token_ids_0 + sep) * [0]
  318. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  319. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  320. add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
  321. if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
  322. text = " " + text
  323. return (text, kwargs)