tokenization.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # coding=utf-8
  2. # Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
  3. # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
  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."""
  16. from __future__ import absolute_import, division, print_function, unicode_literals
  17. import collections
  18. import logging
  19. import os
  20. import unicodedata
  21. import six
  22. from io import open
  23. from file_utils import cached_path
  24. logger = logging.getLogger(__name__)
  25. PRETRAINED_VOCAB_ARCHIVE_MAP = {
  26. 'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
  27. 'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
  28. 'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt",
  29. 'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt",
  30. 'bert-base-multilingual-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt",
  31. 'bert-base-multilingual-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt",
  32. 'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt",
  33. }
  34. PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP = {
  35. 'bert-base-uncased': 512,
  36. 'bert-large-uncased': 512,
  37. 'bert-base-cased': 512,
  38. 'bert-large-cased': 512,
  39. 'bert-base-multilingual-uncased': 512,
  40. 'bert-base-multilingual-cased': 512,
  41. 'bert-base-chinese': 512,
  42. }
  43. VOCAB_NAME = 'vocab.txt'
  44. def convert_to_unicode(text):
  45. """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
  46. if six.PY3:
  47. if isinstance(text, str):
  48. return text
  49. elif isinstance(text, bytes):
  50. return text.decode("utf-8", "ignore")
  51. else:
  52. raise ValueError("Unsupported string type: %s" % (type(text)))
  53. elif six.PY2:
  54. if isinstance(text, str):
  55. return text.decode("utf-8", "ignore")
  56. elif isinstance(text, unicode):
  57. return text
  58. else:
  59. raise ValueError("Unsupported string type: %s" % (type(text)))
  60. else:
  61. raise ValueError("Not running on Python2 or Python 3?")
  62. def load_vocab(vocab_file):
  63. """Loads a vocabulary file into a dictionary."""
  64. vocab = collections.OrderedDict()
  65. index = 0
  66. with open(vocab_file, "r", encoding="utf-8") as reader:
  67. while True:
  68. token = reader.readline()
  69. if not token:
  70. break
  71. token = token.strip()
  72. vocab[token] = index
  73. index += 1
  74. return vocab
  75. def whitespace_tokenize(text):
  76. """Runs basic whitespace cleaning and splitting on a piece of text."""
  77. text = text.strip()
  78. if not text:
  79. return []
  80. tokens = text.split()
  81. return tokens
  82. class BertTokenizer(object):
  83. """Runs end-to-end tokenization: punctuation splitting + wordpiece"""
  84. def __init__(self, vocab_file, do_lower_case=True, max_len=None,
  85. never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
  86. if not os.path.isfile(vocab_file):
  87. raise ValueError(
  88. "Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained "
  89. "model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`".format(vocab_file))
  90. self.vocab = load_vocab(vocab_file)
  91. self.ids_to_tokens = collections.OrderedDict(
  92. [(ids, tok) for tok, ids in self.vocab.items()])
  93. self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case,
  94. never_split=never_split)
  95. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
  96. self.max_len = max_len if max_len is not None else int(1e12)
  97. def tokenize(self, text):
  98. split_tokens = []
  99. for token in self.basic_tokenizer.tokenize(text):
  100. for sub_token in self.wordpiece_tokenizer.tokenize(token):
  101. split_tokens.append(sub_token)
  102. return split_tokens
  103. def convert_tokens_to_ids(self, tokens):
  104. """Converts a sequence of tokens into ids using the vocab."""
  105. ids = []
  106. for token in tokens:
  107. ids.append(self.vocab[token])
  108. if len(ids) > self.max_len:
  109. raise ValueError(
  110. "Token indices sequence length is longer than the specified maximum "
  111. " sequence length for this BERT model ({} > {}). Running this"
  112. " sequence through BERT will result in indexing errors".format(len(ids), self.max_len)
  113. )
  114. return ids
  115. def convert_ids_to_tokens(self, ids):
  116. """Converts a sequence of ids in wordpiece tokens using the vocab."""
  117. tokens = []
  118. for i in ids:
  119. tokens.append(self.ids_to_tokens[i])
  120. return tokens
  121. @classmethod
  122. def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
  123. """
  124. Instantiate a PreTrainedBertModel from a pre-trained model file.
  125. Download and cache the pre-trained model file if needed.
  126. """
  127. if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP:
  128. vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path]
  129. else:
  130. vocab_file = pretrained_model_name_or_path
  131. if os.path.isdir(vocab_file):
  132. vocab_file = os.path.join(vocab_file, VOCAB_NAME)
  133. # redirect to the cache, if necessary
  134. try:
  135. resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir)
  136. except EnvironmentError:
  137. logger.error(
  138. "Model name '{}' was not found in model name list ({}). "
  139. "We assumed '{}' was a path or url but couldn't find any file "
  140. "associated to this path or url.".format(
  141. pretrained_model_name_or_path,
  142. ', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()),
  143. vocab_file))
  144. return None
  145. if resolved_vocab_file == vocab_file:
  146. logger.info("loading vocabulary file {}".format(vocab_file))
  147. else:
  148. logger.info("loading vocabulary file {} from cache at {}".format(
  149. vocab_file, resolved_vocab_file))
  150. if pretrained_model_name_or_path in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP:
  151. # if we're using a pretrained model, ensure the tokenizer wont index sequences longer
  152. # than the number of positional embeddings
  153. max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name_or_path]
  154. kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)
  155. # Instantiate tokenizer.
  156. tokenizer = cls(resolved_vocab_file, *inputs, **kwargs)
  157. return tokenizer
  158. class BasicTokenizer(object):
  159. """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
  160. def __init__(self,
  161. do_lower_case=True,
  162. never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
  163. """Constructs a BasicTokenizer.
  164. Args:
  165. do_lower_case: Whether to lower case the input.
  166. """
  167. self.do_lower_case = do_lower_case
  168. self.never_split = never_split
  169. def tokenize(self, text):
  170. """Tokenizes a piece of text."""
  171. text = self._clean_text(text)
  172. # This was added on November 1st, 2018 for the multilingual and Chinese
  173. # models. This is also applied to the English models now, but it doesn't
  174. # matter since the English models were not trained on any Chinese data
  175. # and generally don't have any Chinese data in them (there are Chinese
  176. # characters in the vocabulary because Wikipedia does have some Chinese
  177. # words in the English Wikipedia.).
  178. text = self._tokenize_chinese_chars(text)
  179. orig_tokens = whitespace_tokenize(text)
  180. split_tokens = []
  181. for token in orig_tokens:
  182. if self.do_lower_case and token not in self.never_split:
  183. token = token.lower()
  184. token = self._run_strip_accents(token)
  185. split_tokens.extend(self._run_split_on_punc(token))
  186. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  187. return output_tokens
  188. def _run_strip_accents(self, text):
  189. """Strips accents from a piece of text."""
  190. text = unicodedata.normalize("NFD", text)
  191. output = []
  192. for char in text:
  193. cat = unicodedata.category(char)
  194. if cat == "Mn":
  195. continue
  196. output.append(char)
  197. return "".join(output)
  198. def _run_split_on_punc(self, text):
  199. """Splits punctuation on a piece of text."""
  200. if text in self.never_split:
  201. return [text]
  202. chars = list(text)
  203. i = 0
  204. start_new_word = True
  205. output = []
  206. while i < len(chars):
  207. char = chars[i]
  208. if _is_punctuation(char):
  209. output.append([char])
  210. start_new_word = True
  211. else:
  212. if start_new_word:
  213. output.append([])
  214. start_new_word = False
  215. output[-1].append(char)
  216. i += 1
  217. return ["".join(x) for x in output]
  218. def _tokenize_chinese_chars(self, text):
  219. """Adds whitespace around any CJK character."""
  220. output = []
  221. for char in text:
  222. cp = ord(char)
  223. if self._is_chinese_char(cp):
  224. output.append(" ")
  225. output.append(char)
  226. output.append(" ")
  227. else:
  228. output.append(char)
  229. return "".join(output)
  230. def _is_chinese_char(self, cp):
  231. """Checks whether CP is the codepoint of a CJK character."""
  232. # This defines a "chinese character" as anything in the CJK Unicode block:
  233. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  234. #
  235. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  236. # despite its name. The modern Korean Hangul alphabet is a different block,
  237. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  238. # space-separated words, so they are not treated specially and handled
  239. # like the all of the other languages.
  240. if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
  241. (cp >= 0x3400 and cp <= 0x4DBF) or #
  242. (cp >= 0x20000 and cp <= 0x2A6DF) or #
  243. (cp >= 0x2A700 and cp <= 0x2B73F) or #
  244. (cp >= 0x2B740 and cp <= 0x2B81F) or #
  245. (cp >= 0x2B820 and cp <= 0x2CEAF) or
  246. (cp >= 0xF900 and cp <= 0xFAFF) or #
  247. (cp >= 0x2F800 and cp <= 0x2FA1F)): #
  248. return True
  249. return False
  250. def _clean_text(self, text):
  251. """Performs invalid character removal and whitespace cleanup on text."""
  252. output = []
  253. for char in text:
  254. cp = ord(char)
  255. if cp == 0 or cp == 0xfffd or _is_control(char):
  256. continue
  257. if _is_whitespace(char):
  258. output.append(" ")
  259. else:
  260. output.append(char)
  261. return "".join(output)
  262. class WordpieceTokenizer(object):
  263. """Runs WordPiece tokenization."""
  264. def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100):
  265. self.vocab = vocab
  266. self.unk_token = unk_token
  267. self.max_input_chars_per_word = max_input_chars_per_word
  268. def tokenize(self, text):
  269. """Tokenizes a piece of text into its word pieces.
  270. This uses a greedy longest-match-first algorithm to perform tokenization
  271. using the given vocabulary.
  272. For example:
  273. input = "unaffable"
  274. output = ["un", "##aff", "##able"]
  275. Args:
  276. text: A single token or whitespace separated tokens. This should have
  277. already been passed through `BasicTokenizer`.
  278. Returns:
  279. A list of wordpiece tokens.
  280. """
  281. output_tokens = []
  282. for token in whitespace_tokenize(text):
  283. chars = list(token)
  284. if len(chars) > self.max_input_chars_per_word:
  285. output_tokens.append(self.unk_token)
  286. continue
  287. is_bad = False
  288. start = 0
  289. sub_tokens = []
  290. while start < len(chars):
  291. end = len(chars)
  292. cur_substr = None
  293. while start < end:
  294. substr = "".join(chars[start:end])
  295. if start > 0:
  296. substr = "##" + substr
  297. if substr in self.vocab:
  298. cur_substr = substr
  299. break
  300. end -= 1
  301. if cur_substr is None:
  302. is_bad = True
  303. break
  304. sub_tokens.append(cur_substr)
  305. start = end
  306. if is_bad:
  307. output_tokens.append(self.unk_token)
  308. else:
  309. output_tokens.extend(sub_tokens)
  310. return output_tokens
  311. def _is_whitespace(char):
  312. """Checks whether `chars` is a whitespace character."""
  313. # \t, \n, and \r are technically contorl characters but we treat them
  314. # as whitespace since they are generally considered as such.
  315. if char == " " or char == "\t" or char == "\n" or char == "\r":
  316. return True
  317. cat = unicodedata.category(char)
  318. if cat == "Zs":
  319. return True
  320. return False
  321. def _is_control(char):
  322. """Checks whether `chars` is a control character."""
  323. # These are technically control characters but we count them as whitespace
  324. # characters.
  325. if char == "\t" or char == "\n" or char == "\r":
  326. return False
  327. cat = unicodedata.category(char)
  328. if cat.startswith("C"):
  329. return True
  330. return False
  331. def _is_punctuation(char):
  332. """Checks whether `chars` is a punctuation character."""
  333. cp = ord(char)
  334. # We treat all non-letter/number ASCII as punctuation.
  335. # Characters such as "^", "$", and "`" are not in the Unicode
  336. # Punctuation class but we treat them as punctuation anyways, for
  337. # consistency.
  338. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
  339. (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
  340. return True
  341. cat = unicodedata.category(char)
  342. if cat.startswith("P"):
  343. return True
  344. return False