tokenization_blenderbot.py 18 KB

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