tokenization_roberta.py 16 KB

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