tokenization_gpt2.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 OpenAI GPT."""
  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 GPT2Tokenizer(PreTrainedTokenizer):
  62. """
  63. Construct a GPT-2 tokenizer. Based on 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 GPT2Tokenizer
  68. >>> tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
  69. >>> tokenizer("Hello world")["input_ids"]
  70. [15496, 995]
  71. >>> tokenizer(" Hello world")["input_ids"]
  72. [18435, 995]
  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. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  90. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  91. token instead.
  92. bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  93. The beginning of sequence token.
  94. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  95. The end of sequence token.
  96. pad_token (`str`, *optional*):
  97. The token used for padding, for example when batching sequences of different lengths.
  98. add_prefix_space (`bool`, *optional*, defaults to `False`):
  99. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  100. other word. (GPT2 tokenizer detect beginning of words by the preceding space).
  101. add_bos_token (`bool`, *optional*, defaults to `False`):
  102. Whether or not to add an initial beginning of sentence token to the input. This allows to treat the leading
  103. word just as any other word.
  104. """
  105. vocab_files_names = VOCAB_FILES_NAMES
  106. model_input_names = ["input_ids", "attention_mask"]
  107. def __init__(
  108. self,
  109. vocab_file,
  110. merges_file,
  111. errors="replace",
  112. unk_token="<|endoftext|>",
  113. bos_token="<|endoftext|>",
  114. eos_token="<|endoftext|>",
  115. pad_token=None,
  116. add_prefix_space=False,
  117. add_bos_token=False,
  118. **kwargs,
  119. ):
  120. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  121. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  122. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  123. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  124. self.add_bos_token = add_bos_token
  125. with open(vocab_file, encoding="utf-8") as vocab_handle:
  126. self.encoder = json.load(vocab_handle)
  127. self.decoder = {v: k for k, v in self.encoder.items()}
  128. self.errors = errors # how to handle errors in decoding
  129. self.byte_encoder = bytes_to_unicode()
  130. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  131. with open(merges_file, encoding="utf-8") as merges_handle:
  132. bpe_merges = merges_handle.read().split("\n")[1:-1]
  133. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  134. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  135. self.cache = {}
  136. self.add_prefix_space = add_prefix_space
  137. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  138. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  139. super().__init__(
  140. errors=errors,
  141. unk_token=unk_token,
  142. bos_token=bos_token,
  143. eos_token=eos_token,
  144. pad_token=pad_token,
  145. add_prefix_space=add_prefix_space,
  146. add_bos_token=add_bos_token,
  147. **kwargs,
  148. )
  149. @property
  150. def vocab_size(self):
  151. return len(self.encoder)
  152. def get_vocab(self):
  153. return dict(self.encoder, **self.added_tokens_encoder)
  154. def bpe(self, token):
  155. if token in self.cache:
  156. return self.cache[token]
  157. word = tuple(token)
  158. pairs = get_pairs(word)
  159. if not pairs:
  160. return token
  161. while True:
  162. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  163. if bigram not in self.bpe_ranks:
  164. break
  165. first, second = bigram
  166. new_word = []
  167. i = 0
  168. while i < len(word):
  169. try:
  170. j = word.index(first, i)
  171. except ValueError:
  172. new_word.extend(word[i:])
  173. break
  174. else:
  175. new_word.extend(word[i:j])
  176. i = j
  177. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  178. new_word.append(first + second)
  179. i += 2
  180. else:
  181. new_word.append(word[i])
  182. i += 1
  183. new_word = tuple(new_word)
  184. word = new_word
  185. if len(word) == 1:
  186. break
  187. else:
  188. pairs = get_pairs(word)
  189. word = " ".join(word)
  190. self.cache[token] = word
  191. return word
  192. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  193. if self.add_bos_token:
  194. bos_token_ids = [self.bos_token_id]
  195. else:
  196. bos_token_ids = []
  197. output = bos_token_ids + token_ids_0
  198. if token_ids_1 is None:
  199. return output
  200. return output + bos_token_ids + token_ids_1
  201. def get_special_tokens_mask(
  202. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  203. ) -> List[int]:
  204. """
  205. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  206. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  207. Args:
  208. token_ids_0 (`List[int]`):
  209. List of IDs.
  210. token_ids_1 (`List[int]`, *optional*):
  211. Optional second list of IDs for sequence pairs.
  212. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  213. Whether or not the token list is already formatted with special tokens for the model.
  214. Returns:
  215. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  216. """
  217. if already_has_special_tokens:
  218. return super().get_special_tokens_mask(
  219. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  220. )
  221. if not self.add_bos_token:
  222. return super().get_special_tokens_mask(
  223. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
  224. )
  225. if token_ids_1 is None:
  226. return [1] + ([0] * len(token_ids_0))
  227. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
  228. def _tokenize(self, text):
  229. """Tokenize a string."""
  230. bpe_tokens = []
  231. for token in re.findall(self.pat, text):
  232. token = "".join(
  233. self.byte_encoder[b] for b in token.encode("utf-8")
  234. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  235. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  236. return bpe_tokens
  237. def _convert_token_to_id(self, token):
  238. """Converts a token (str) in an id using the vocab."""
  239. return self.encoder.get(token, self.encoder.get(self.unk_token))
  240. def _convert_id_to_token(self, index):
  241. """Converts an index (integer) in a token (str) using the vocab."""
  242. return self.decoder.get(index)
  243. def convert_tokens_to_string(self, tokens):
  244. """Converts a sequence of tokens (string) in a single string."""
  245. text = "".join(tokens)
  246. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  247. return text
  248. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  249. if not os.path.isdir(save_directory):
  250. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  251. return
  252. vocab_file = os.path.join(
  253. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  254. )
  255. merge_file = os.path.join(
  256. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  257. )
  258. with open(vocab_file, "w", encoding="utf-8") as f:
  259. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  260. index = 0
  261. with open(merge_file, "w", encoding="utf-8") as writer:
  262. writer.write("#version: 0.2\n")
  263. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  264. if index != token_index:
  265. logger.warning(
  266. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  267. " Please check that the tokenizer is not corrupted!"
  268. )
  269. index = token_index
  270. writer.write(" ".join(bpe_tokens) + "\n")
  271. index += 1
  272. return vocab_file, merge_file
  273. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  274. add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
  275. if is_split_into_words or add_prefix_space:
  276. text = " " + text
  277. return (text, kwargs)