tokenization_openai.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. import re
  19. import unicodedata
  20. from typing import Optional, Tuple
  21. from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
  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. # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
  29. def whitespace_tokenize(text):
  30. """Runs basic whitespace cleaning and splitting on a piece of text."""
  31. text = text.strip()
  32. if not text:
  33. return []
  34. tokens = text.split()
  35. return tokens
  36. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  37. class BasicTokenizer:
  38. """
  39. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  40. Args:
  41. do_lower_case (`bool`, *optional*, defaults to `True`):
  42. Whether or not to lowercase the input when tokenizing.
  43. never_split (`Iterable`, *optional*):
  44. Collection of tokens which will never be split during tokenization. Only has an effect when
  45. `do_basic_tokenize=True`
  46. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  47. Whether or not to tokenize Chinese characters.
  48. This should likely be deactivated for Japanese (see this
  49. [issue](https://github.com/huggingface/transformers/issues/328)).
  50. strip_accents (`bool`, *optional*):
  51. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  52. value for `lowercase` (as in the original BERT).
  53. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  54. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  55. the full context of the words, such as contractions.
  56. """
  57. def __init__(
  58. self,
  59. do_lower_case=True,
  60. never_split=None,
  61. tokenize_chinese_chars=True,
  62. strip_accents=None,
  63. do_split_on_punc=True,
  64. ):
  65. if never_split is None:
  66. never_split = []
  67. self.do_lower_case = do_lower_case
  68. self.never_split = set(never_split)
  69. self.tokenize_chinese_chars = tokenize_chinese_chars
  70. self.strip_accents = strip_accents
  71. self.do_split_on_punc = do_split_on_punc
  72. def tokenize(self, text, never_split=None):
  73. """
  74. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  75. Args:
  76. never_split (`List[str]`, *optional*)
  77. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  78. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  79. """
  80. # union() returns a new set by concatenating the two sets.
  81. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
  82. text = self._clean_text(text)
  83. # This was added on November 1st, 2018 for the multilingual and Chinese
  84. # models. This is also applied to the English models now, but it doesn't
  85. # matter since the English models were not trained on any Chinese data
  86. # and generally don't have any Chinese data in them (there are Chinese
  87. # characters in the vocabulary because Wikipedia does have some Chinese
  88. # words in the English Wikipedia.).
  89. if self.tokenize_chinese_chars:
  90. text = self._tokenize_chinese_chars(text)
  91. # prevents treating the same character with different unicode codepoints as different characters
  92. unicode_normalized_text = unicodedata.normalize("NFC", text)
  93. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  94. split_tokens = []
  95. for token in orig_tokens:
  96. if token not in never_split:
  97. if self.do_lower_case:
  98. token = token.lower()
  99. if self.strip_accents is not False:
  100. token = self._run_strip_accents(token)
  101. elif self.strip_accents:
  102. token = self._run_strip_accents(token)
  103. split_tokens.extend(self._run_split_on_punc(token, never_split))
  104. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  105. return output_tokens
  106. def _run_strip_accents(self, text):
  107. """Strips accents from a piece of text."""
  108. text = unicodedata.normalize("NFD", text)
  109. output = []
  110. for char in text:
  111. cat = unicodedata.category(char)
  112. if cat == "Mn":
  113. continue
  114. output.append(char)
  115. return "".join(output)
  116. def _run_split_on_punc(self, text, never_split=None):
  117. """Splits punctuation on a piece of text."""
  118. if not self.do_split_on_punc or (never_split is not None and text in never_split):
  119. return [text]
  120. chars = list(text)
  121. i = 0
  122. start_new_word = True
  123. output = []
  124. while i < len(chars):
  125. char = chars[i]
  126. if _is_punctuation(char):
  127. output.append([char])
  128. start_new_word = True
  129. else:
  130. if start_new_word:
  131. output.append([])
  132. start_new_word = False
  133. output[-1].append(char)
  134. i += 1
  135. return ["".join(x) for x in output]
  136. def _tokenize_chinese_chars(self, text):
  137. """Adds whitespace around any CJK character."""
  138. output = []
  139. for char in text:
  140. cp = ord(char)
  141. if self._is_chinese_char(cp):
  142. output.append(" ")
  143. output.append(char)
  144. output.append(" ")
  145. else:
  146. output.append(char)
  147. return "".join(output)
  148. def _is_chinese_char(self, cp):
  149. """Checks whether CP is the codepoint of a CJK character."""
  150. # This defines a "chinese character" as anything in the CJK Unicode block:
  151. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  152. #
  153. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  154. # despite its name. The modern Korean Hangul alphabet is a different block,
  155. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  156. # space-separated words, so they are not treated specially and handled
  157. # like the all of the other languages.
  158. if (
  159. (cp >= 0x4E00 and cp <= 0x9FFF)
  160. or (cp >= 0x3400 and cp <= 0x4DBF) #
  161. or (cp >= 0x20000 and cp <= 0x2A6DF) #
  162. or (cp >= 0x2A700 and cp <= 0x2B73F) #
  163. or (cp >= 0x2B740 and cp <= 0x2B81F) #
  164. or (cp >= 0x2B820 and cp <= 0x2CEAF) #
  165. or (cp >= 0xF900 and cp <= 0xFAFF)
  166. or (cp >= 0x2F800 and cp <= 0x2FA1F) #
  167. ): #
  168. return True
  169. return False
  170. def _clean_text(self, text):
  171. """Performs invalid character removal and whitespace cleanup on text."""
  172. output = []
  173. for char in text:
  174. cp = ord(char)
  175. if cp == 0 or cp == 0xFFFD or _is_control(char):
  176. continue
  177. if _is_whitespace(char):
  178. output.append(" ")
  179. else:
  180. output.append(char)
  181. return "".join(output)
  182. def get_pairs(word):
  183. """
  184. Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
  185. strings)
  186. """
  187. pairs = set()
  188. prev_char = word[0]
  189. for char in word[1:]:
  190. pairs.add((prev_char, char))
  191. prev_char = char
  192. return pairs
  193. def text_standardize(text):
  194. """
  195. fixes some issues the spacy tokenizer had on books corpus also does some whitespace standardization
  196. """
  197. text = text.replace("—", "-")
  198. text = text.replace("–", "-")
  199. text = text.replace("―", "-")
  200. text = text.replace("…", "...")
  201. text = text.replace("´", "'")
  202. text = re.sub(r"""(-+|~+|!+|"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)""", r" \1 ", text)
  203. text = re.sub(r"\s*\n\s*", " \n ", text)
  204. text = re.sub(r"[^\S\n]+", " ", text)
  205. return text.strip()
  206. class OpenAIGPTTokenizer(PreTrainedTokenizer):
  207. """
  208. Construct a GPT Tokenizer. Based on Byte-Pair-Encoding with the following peculiarities:
  209. - lowercases all inputs,
  210. - uses `SpaCy` tokenizer and `ftfy` for pre-BPE tokenization if they are installed, fallback to BERT's
  211. `BasicTokenizer` if not.
  212. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  213. this superclass for more information regarding those methods.
  214. Args:
  215. vocab_file (`str`):
  216. Path to the vocabulary file.
  217. merges_file (`str`):
  218. Path to the merges file.
  219. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  220. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  221. token instead.
  222. """
  223. vocab_files_names = VOCAB_FILES_NAMES
  224. model_input_names = ["input_ids", "attention_mask"]
  225. def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs):
  226. try:
  227. import ftfy
  228. from spacy.lang.en import English
  229. _nlp = English()
  230. self.nlp = _nlp.tokenizer
  231. self.fix_text = ftfy.fix_text
  232. except ImportError:
  233. logger.warning("ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy.")
  234. self.nlp = BasicTokenizer(do_lower_case=True)
  235. self.fix_text = None
  236. with open(vocab_file, encoding="utf-8") as vocab_handle:
  237. self.encoder = json.load(vocab_handle)
  238. self.decoder = {v: k for k, v in self.encoder.items()}
  239. with open(merges_file, encoding="utf-8") as merges_handle:
  240. merges = merges_handle.read().split("\n")[1:-1]
  241. merges = [tuple(merge.split()) for merge in merges]
  242. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  243. self.cache = {}
  244. super().__init__(unk_token=unk_token, **kwargs)
  245. @property
  246. def do_lower_case(self):
  247. return True
  248. @property
  249. def vocab_size(self):
  250. return len(self.encoder)
  251. def get_vocab(self):
  252. return dict(self.encoder, **self.added_tokens_encoder)
  253. def bpe(self, token):
  254. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  255. if token in self.cache:
  256. return self.cache[token]
  257. pairs = get_pairs(word)
  258. if not pairs:
  259. return token + "</w>"
  260. while True:
  261. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  262. if bigram not in self.bpe_ranks:
  263. break
  264. first, second = bigram
  265. new_word = []
  266. i = 0
  267. while i < len(word):
  268. try:
  269. j = word.index(first, i)
  270. except ValueError:
  271. new_word.extend(word[i:])
  272. break
  273. else:
  274. new_word.extend(word[i:j])
  275. i = j
  276. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  277. new_word.append(first + second)
  278. i += 2
  279. else:
  280. new_word.append(word[i])
  281. i += 1
  282. new_word = tuple(new_word)
  283. word = new_word
  284. if len(word) == 1:
  285. break
  286. else:
  287. pairs = get_pairs(word)
  288. word = " ".join(word)
  289. if word == "\n </w>":
  290. word = "\n</w>"
  291. self.cache[token] = word
  292. return word
  293. def _tokenize(self, text):
  294. """Tokenize a string."""
  295. split_tokens = []
  296. if self.fix_text is None:
  297. # Using BERT's BasicTokenizer
  298. text = self.nlp.tokenize(text)
  299. for token in text:
  300. split_tokens.extend(list(self.bpe(token).split(" ")))
  301. else:
  302. # Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
  303. text = self.nlp(text_standardize(self.fix_text(text)))
  304. for token in text:
  305. split_tokens.extend(list(self.bpe(token.text.lower()).split(" ")))
  306. return split_tokens
  307. def _convert_token_to_id(self, token):
  308. """Converts a token (str) in an id using the vocab."""
  309. return self.encoder.get(token, self.encoder.get(self.unk_token))
  310. def _convert_id_to_token(self, index):
  311. """Converts an id in a token (BPE) using the vocab."""
  312. return self.decoder.get(index, self.unk_token)
  313. def convert_tokens_to_string(self, tokens):
  314. """Converts a sequence of tokens (string) in a single string."""
  315. out_string = "".join(tokens).replace("</w>", " ").strip()
  316. return out_string
  317. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  318. if not os.path.isdir(save_directory):
  319. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  320. return
  321. vocab_file = os.path.join(
  322. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  323. )
  324. merge_file = os.path.join(
  325. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  326. )
  327. with open(vocab_file, "w", encoding="utf-8") as f:
  328. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  329. index = 0
  330. with open(merge_file, "w", encoding="utf-8") as writer:
  331. writer.write("#version: 0.2\n")
  332. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  333. if index != token_index:
  334. logger.warning(
  335. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  336. " Please check that the tokenizer is not corrupted!"
  337. )
  338. index = token_index
  339. writer.write(" ".join(bpe_tokens) + "\n")
  340. index += 1
  341. return vocab_file, merge_file