tokenization.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. # https://github.com/mlcommons/training/blob/1c8a098ae3e70962a4f7422c0b0bd35ae639e357/language_model/tensorflow/bert/cleanup_scripts/tokenization.py
  2. # NOTE: This is a direct copy of the original script
  3. """Tokenization classes."""
  4. from __future__ import absolute_import
  5. from __future__ import division
  6. from __future__ import print_function
  7. import collections
  8. import re
  9. import unicodedata
  10. from absl import flags
  11. import six
  12. import tensorflow.compat.v1 as tf
  13. FLAGS = flags.FLAGS
  14. flags.DEFINE_bool(
  15. "preserve_unused_tokens", False,
  16. "If True, Wordpiece tokenization will not be applied to words in the vocab."
  17. )
  18. _UNUSED_TOKEN_RE = re.compile("^\\[unused\\d+\\]$")
  19. def preserve_token(token, vocab):
  20. """Returns True if the token should forgo tokenization and be preserved."""
  21. if not FLAGS.preserve_unused_tokens:
  22. return False
  23. if token not in vocab:
  24. return False
  25. return bool(_UNUSED_TOKEN_RE.search(token))
  26. def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
  27. """Checks whether the casing config is consistent with the checkpoint name."""
  28. # The casing has to be passed in by the user and there is no explicit check
  29. # as to whether it matches the checkpoint. The casing information probably
  30. # should have been stored in the bert_config.json file, but it's not, so
  31. # we have to heuristically detect it to validate.
  32. if not init_checkpoint:
  33. return
  34. m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint)
  35. if m is None:
  36. return
  37. model_name = m.group(1)
  38. lower_models = [
  39. "uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12",
  40. "multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12"
  41. ]
  42. cased_models = [
  43. "cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16",
  44. "multi_cased_L-12_H-768_A-12"
  45. ]
  46. is_bad_config = False
  47. if model_name in lower_models and not do_lower_case:
  48. is_bad_config = True
  49. actual_flag = "False"
  50. case_name = "lowercased"
  51. opposite_flag = "True"
  52. if model_name in cased_models and do_lower_case:
  53. is_bad_config = True
  54. actual_flag = "True"
  55. case_name = "cased"
  56. opposite_flag = "False"
  57. if is_bad_config:
  58. raise ValueError(
  59. "You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. "
  60. "However, `%s` seems to be a %s model, so you "
  61. "should pass in `--do_lower_case=%s` so that the fine-tuning matches "
  62. "how the model was pre-training. If this error is wrong, please "
  63. "just comment out this check." % (actual_flag, init_checkpoint,
  64. model_name, case_name, opposite_flag))
  65. def convert_to_unicode(text):
  66. """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
  67. if six.PY3:
  68. if isinstance(text, str):
  69. return text
  70. elif isinstance(text, bytes):
  71. return text.decode("utf-8", "ignore")
  72. else:
  73. raise ValueError("Unsupported string type: %s" % (type(text)))
  74. elif six.PY2:
  75. if isinstance(text, str):
  76. return text.decode("utf-8", "ignore")
  77. elif isinstance(text, unicode): # noqa: F821
  78. return text
  79. else:
  80. raise ValueError("Unsupported string type: %s" % (type(text)))
  81. else:
  82. raise ValueError("Not running on Python2 or Python 3?")
  83. def printable_text(text):
  84. """Returns text encoded in a way suitable for print or `tf.logging`."""
  85. # These functions want `str` for both Python2 and Python3, but in one case
  86. # it's a Unicode string and in the other it's a byte string.
  87. if six.PY3:
  88. if isinstance(text, str):
  89. return text
  90. elif isinstance(text, bytes):
  91. return text.decode("utf-8", "ignore")
  92. else:
  93. raise ValueError("Unsupported string type: %s" % (type(text)))
  94. elif six.PY2:
  95. if isinstance(text, str):
  96. return text
  97. elif isinstance(text, unicode): # noqa: F821
  98. return text.encode("utf-8")
  99. else:
  100. raise ValueError("Unsupported string type: %s" % (type(text)))
  101. else:
  102. raise ValueError("Not running on Python2 or Python 3?")
  103. def load_vocab(vocab_file):
  104. """Loads a vocabulary file into a dictionary."""
  105. vocab = collections.OrderedDict()
  106. with tf.gfile.GFile(vocab_file, "r") as reader:
  107. while True:
  108. token = convert_to_unicode(reader.readline())
  109. if not token:
  110. break
  111. token = token.strip()
  112. if token not in vocab:
  113. vocab[token] = len(vocab)
  114. return vocab
  115. def convert_by_vocab(vocab, items):
  116. """Converts a sequence of [tokens|ids] using the vocab."""
  117. output = []
  118. for item in items:
  119. output.append(vocab[item])
  120. return output
  121. def convert_tokens_to_ids(vocab, tokens):
  122. return convert_by_vocab(vocab, tokens)
  123. def convert_ids_to_tokens(inv_vocab, ids):
  124. return convert_by_vocab(inv_vocab, ids)
  125. def whitespace_tokenize(text):
  126. """Runs basic whitespace cleaning and splitting on a piece of text."""
  127. text = text.strip()
  128. if not text:
  129. return []
  130. tokens = text.split()
  131. return tokens
  132. class FullTokenizer(object):
  133. """Runs end-to-end tokenziation."""
  134. def __init__(self, vocab_file, do_lower_case=True):
  135. self.vocab = load_vocab(vocab_file)
  136. self.inv_vocab = {v: k for k, v in self.vocab.items()}
  137. self.basic_tokenizer = BasicTokenizer(
  138. do_lower_case=do_lower_case, vocab=self.vocab)
  139. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
  140. def tokenize(self, text):
  141. split_tokens = []
  142. for token in self.basic_tokenizer.tokenize(text):
  143. if preserve_token(token, self.vocab):
  144. split_tokens.append(token)
  145. continue
  146. for sub_token in self.wordpiece_tokenizer.tokenize(token):
  147. split_tokens.append(sub_token)
  148. return split_tokens
  149. def convert_tokens_to_ids(self, tokens):
  150. return convert_by_vocab(self.vocab, tokens)
  151. def convert_ids_to_tokens(self, ids):
  152. return convert_by_vocab(self.inv_vocab, ids)
  153. class BasicTokenizer(object):
  154. """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
  155. def __init__(self, do_lower_case=True, vocab=tuple()):
  156. """Constructs a BasicTokenizer.
  157. Args:
  158. do_lower_case: Whether to lower case the input.
  159. vocab: A container of tokens to not mutate during tokenization.
  160. """
  161. self.do_lower_case = do_lower_case
  162. self.vocab = vocab
  163. def tokenize(self, text):
  164. """Tokenizes a piece of text."""
  165. text = convert_to_unicode(text)
  166. text = self._clean_text(text)
  167. # This was added on November 1st, 2018 for the multilingual and Chinese
  168. # models. This is also applied to the English models now, but it doesn't
  169. # matter since the English models were not trained on any Chinese data
  170. # and generally don't have any Chinese data in them (there are Chinese
  171. # characters in the vocabulary because Wikipedia does have some Chinese
  172. # words in the English Wikipedia.).
  173. text = self._tokenize_chinese_chars(text)
  174. orig_tokens = whitespace_tokenize(text)
  175. split_tokens = []
  176. for token in orig_tokens:
  177. if preserve_token(token, self.vocab):
  178. split_tokens.append(token)
  179. continue
  180. if self.do_lower_case:
  181. token = token.lower()
  182. token = self._run_strip_accents(token)
  183. split_tokens.extend(self._run_split_on_punc(token))
  184. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  185. return output_tokens
  186. def _run_strip_accents(self, text):
  187. """Strips accents from a piece of text."""
  188. text = unicodedata.normalize("NFD", text)
  189. output = []
  190. for char in text:
  191. cat = unicodedata.category(char)
  192. if cat == "Mn":
  193. continue
  194. output.append(char)
  195. return "".join(output)
  196. def _run_split_on_punc(self, text):
  197. """Splits punctuation on a piece of text."""
  198. chars = list(text)
  199. i = 0
  200. start_new_word = True
  201. output = []
  202. while i < len(chars):
  203. char = chars[i]
  204. if _is_punctuation(char):
  205. output.append([char])
  206. start_new_word = True
  207. else:
  208. if start_new_word:
  209. output.append([])
  210. start_new_word = False
  211. output[-1].append(char)
  212. i += 1
  213. return ["".join(x) for x in output]
  214. def _tokenize_chinese_chars(self, text):
  215. """Adds whitespace around any CJK character."""
  216. output = []
  217. for char in text:
  218. cp = ord(char)
  219. if self._is_chinese_char(cp):
  220. output.append(" ")
  221. output.append(char)
  222. output.append(" ")
  223. else:
  224. output.append(char)
  225. return "".join(output)
  226. def _is_chinese_char(self, cp):
  227. """Checks whether CP is the codepoint of a CJK character."""
  228. # This defines a "chinese character" as anything in the CJK Unicode block:
  229. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  230. #
  231. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  232. # despite its name. The modern Korean Hangul alphabet is a different block,
  233. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  234. # space-separated words, so they are not treated specially and handled
  235. # like all of the other languages.
  236. if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
  237. (cp >= 0x3400 and cp <= 0x4DBF) or #
  238. (cp >= 0x20000 and cp <= 0x2A6DF) or #
  239. (cp >= 0x2A700 and cp <= 0x2B73F) or #
  240. (cp >= 0x2B740 and cp <= 0x2B81F) or #
  241. (cp >= 0x2B820 and cp <= 0x2CEAF) or
  242. (cp >= 0xF900 and cp <= 0xFAFF) or #
  243. (cp >= 0x2F800 and cp <= 0x2FA1F)): #
  244. return True
  245. return False
  246. def _clean_text(self, text):
  247. """Performs invalid character removal and whitespace cleanup on text."""
  248. output = []
  249. for char in text:
  250. cp = ord(char)
  251. if cp == 0 or cp == 0xfffd or _is_control(char):
  252. continue
  253. if _is_whitespace(char):
  254. output.append(" ")
  255. else:
  256. output.append(char)
  257. return "".join(output)
  258. class WordpieceTokenizer(object):
  259. """Runs WordPiece tokenziation."""
  260. def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200):
  261. self.vocab = vocab
  262. self.unk_token = unk_token
  263. self.max_input_chars_per_word = max_input_chars_per_word
  264. def tokenize(self, text):
  265. """Tokenizes a piece of text into its word pieces.
  266. This uses a greedy longest-match-first algorithm to perform tokenization
  267. using the given vocabulary.
  268. For example:
  269. input = "unaffable"
  270. output = ["un", "##aff", "##able"]
  271. Args:
  272. text: A single token or whitespace separated tokens. This should have
  273. already been passed through `BasicTokenizer.
  274. Returns:
  275. A list of wordpiece tokens.
  276. """
  277. text = convert_to_unicode(text)
  278. output_tokens = []
  279. for token in whitespace_tokenize(text):
  280. chars = list(token)
  281. if len(chars) > self.max_input_chars_per_word:
  282. output_tokens.append(self.unk_token)
  283. continue
  284. is_bad = False
  285. start = 0
  286. sub_tokens = []
  287. while start < len(chars):
  288. end = len(chars)
  289. cur_substr = None
  290. while start < end:
  291. substr = "".join(chars[start:end])
  292. if start > 0:
  293. substr = "##" + substr
  294. if substr in self.vocab:
  295. cur_substr = substr
  296. break
  297. end -= 1
  298. if cur_substr is None:
  299. is_bad = True
  300. break
  301. sub_tokens.append(cur_substr)
  302. start = end
  303. if is_bad:
  304. output_tokens.append(self.unk_token)
  305. else:
  306. output_tokens.extend(sub_tokens)
  307. return output_tokens
  308. def _is_whitespace(char):
  309. """Checks whether `chars` is a whitespace character."""
  310. # \t, \n, and \r are technically control characters but we treat them
  311. # as whitespace since they are generally considered as such.
  312. if char == " " or char == "\t" or char == "\n" or char == "\r":
  313. return True
  314. cat = unicodedata.category(char)
  315. if cat == "Zs":
  316. return True
  317. return False
  318. def _is_control(char):
  319. """Checks whether `chars` is a control character."""
  320. # These are technically control characters but we count them as whitespace
  321. # characters.
  322. if char == "\t" or char == "\n" or char == "\r":
  323. return False
  324. cat = unicodedata.category(char)
  325. if cat in ("Cc", "Cf"):
  326. return True
  327. return False
  328. def _is_punctuation(char):
  329. """Checks whether `chars` is a punctuation character."""
  330. cp = ord(char)
  331. # We treat all non-letter/number ASCII as punctuation.
  332. # Characters such as "^", "$", and "`" are not in the Unicode
  333. # Punctuation class but we treat them as punctuation anyways, for
  334. # consistency.
  335. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
  336. (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
  337. return True
  338. cat = unicodedata.category(char)
  339. if cat.startswith("P"):
  340. return True
  341. return False