tokenization_prophetnet.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. # coding=utf-8
  2. # Copyright 2020 The Microsoft 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. import collections
  16. import os
  17. import unicodedata
  18. from collections.abc import Iterable
  19. from typing import Optional
  20. from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {"vocab_file": "prophetnet.tokenizer"}
  24. # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
  25. def whitespace_tokenize(text):
  26. """Runs basic whitespace cleaning and splitting on a piece of text."""
  27. text = text.strip()
  28. if not text:
  29. return []
  30. tokens = text.split()
  31. return tokens
  32. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  33. class BasicTokenizer:
  34. """
  35. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  36. Args:
  37. do_lower_case (`bool`, *optional*, defaults to `True`):
  38. Whether or not to lowercase the input when tokenizing.
  39. never_split (`Iterable`, *optional*):
  40. Collection of tokens which will never be split during tokenization. Only has an effect when
  41. `do_basic_tokenize=True`
  42. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  43. Whether or not to tokenize Chinese characters.
  44. This should likely be deactivated for Japanese (see this
  45. [issue](https://github.com/huggingface/transformers/issues/328)).
  46. strip_accents (`bool`, *optional*):
  47. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  48. value for `lowercase` (as in the original BERT).
  49. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  50. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  51. the full context of the words, such as contractions.
  52. """
  53. def __init__(
  54. self,
  55. do_lower_case=True,
  56. never_split=None,
  57. tokenize_chinese_chars=True,
  58. strip_accents=None,
  59. do_split_on_punc=True,
  60. ):
  61. if never_split is None:
  62. never_split = []
  63. self.do_lower_case = do_lower_case
  64. self.never_split = set(never_split)
  65. self.tokenize_chinese_chars = tokenize_chinese_chars
  66. self.strip_accents = strip_accents
  67. self.do_split_on_punc = do_split_on_punc
  68. def tokenize(self, text, never_split=None):
  69. """
  70. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  71. Args:
  72. never_split (`List[str]`, *optional*)
  73. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  74. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  75. """
  76. # union() returns a new set by concatenating the two sets.
  77. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
  78. text = self._clean_text(text)
  79. # This was added on November 1st, 2018 for the multilingual and Chinese
  80. # models. This is also applied to the English models now, but it doesn't
  81. # matter since the English models were not trained on any Chinese data
  82. # and generally don't have any Chinese data in them (there are Chinese
  83. # characters in the vocabulary because Wikipedia does have some Chinese
  84. # words in the English Wikipedia.).
  85. if self.tokenize_chinese_chars:
  86. text = self._tokenize_chinese_chars(text)
  87. # prevents treating the same character with different unicode codepoints as different characters
  88. unicode_normalized_text = unicodedata.normalize("NFC", text)
  89. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  90. split_tokens = []
  91. for token in orig_tokens:
  92. if token not in never_split:
  93. if self.do_lower_case:
  94. token = token.lower()
  95. if self.strip_accents is not False:
  96. token = self._run_strip_accents(token)
  97. elif self.strip_accents:
  98. token = self._run_strip_accents(token)
  99. split_tokens.extend(self._run_split_on_punc(token, never_split))
  100. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  101. return output_tokens
  102. def _run_strip_accents(self, text):
  103. """Strips accents from a piece of text."""
  104. text = unicodedata.normalize("NFD", text)
  105. output = []
  106. for char in text:
  107. cat = unicodedata.category(char)
  108. if cat == "Mn":
  109. continue
  110. output.append(char)
  111. return "".join(output)
  112. def _run_split_on_punc(self, text, never_split=None):
  113. """Splits punctuation on a piece of text."""
  114. if not self.do_split_on_punc or (never_split is not None and text in never_split):
  115. return [text]
  116. chars = list(text)
  117. i = 0
  118. start_new_word = True
  119. output = []
  120. while i < len(chars):
  121. char = chars[i]
  122. if _is_punctuation(char):
  123. output.append([char])
  124. start_new_word = True
  125. else:
  126. if start_new_word:
  127. output.append([])
  128. start_new_word = False
  129. output[-1].append(char)
  130. i += 1
  131. return ["".join(x) for x in output]
  132. def _tokenize_chinese_chars(self, text):
  133. """Adds whitespace around any CJK character."""
  134. output = []
  135. for char in text:
  136. cp = ord(char)
  137. if self._is_chinese_char(cp):
  138. output.append(" ")
  139. output.append(char)
  140. output.append(" ")
  141. else:
  142. output.append(char)
  143. return "".join(output)
  144. def _is_chinese_char(self, cp):
  145. """Checks whether CP is the codepoint of a CJK character."""
  146. # This defines a "chinese character" as anything in the CJK Unicode block:
  147. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  148. #
  149. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  150. # despite its name. The modern Korean Hangul alphabet is a different block,
  151. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  152. # space-separated words, so they are not treated specially and handled
  153. # like the all of the other languages.
  154. if (
  155. (cp >= 0x4E00 and cp <= 0x9FFF)
  156. or (cp >= 0x3400 and cp <= 0x4DBF)
  157. or (cp >= 0x20000 and cp <= 0x2A6DF)
  158. or (cp >= 0x2A700 and cp <= 0x2B73F)
  159. or (cp >= 0x2B740 and cp <= 0x2B81F)
  160. or (cp >= 0x2B820 and cp <= 0x2CEAF)
  161. or (cp >= 0xF900 and cp <= 0xFAFF)
  162. or (cp >= 0x2F800 and cp <= 0x2FA1F)
  163. ):
  164. return True
  165. return False
  166. def _clean_text(self, text):
  167. """Performs invalid character removal and whitespace cleanup on text."""
  168. output = []
  169. for char in text:
  170. cp = ord(char)
  171. if cp == 0 or cp == 0xFFFD or _is_control(char):
  172. continue
  173. if _is_whitespace(char):
  174. output.append(" ")
  175. else:
  176. output.append(char)
  177. return "".join(output)
  178. # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
  179. class WordpieceTokenizer:
  180. """Runs WordPiece tokenization."""
  181. def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
  182. self.vocab = vocab
  183. self.unk_token = unk_token
  184. self.max_input_chars_per_word = max_input_chars_per_word
  185. def tokenize(self, text):
  186. """
  187. Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
  188. tokenization using the given vocabulary.
  189. For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
  190. Args:
  191. text: A single token or whitespace separated tokens. This should have
  192. already been passed through *BasicTokenizer*.
  193. Returns:
  194. A list of wordpiece tokens.
  195. """
  196. output_tokens = []
  197. for token in whitespace_tokenize(text):
  198. chars = list(token)
  199. if len(chars) > self.max_input_chars_per_word:
  200. output_tokens.append(self.unk_token)
  201. continue
  202. is_bad = False
  203. start = 0
  204. sub_tokens = []
  205. while start < len(chars):
  206. end = len(chars)
  207. cur_substr = None
  208. while start < end:
  209. substr = "".join(chars[start:end])
  210. if start > 0:
  211. substr = "##" + substr
  212. if substr in self.vocab:
  213. cur_substr = substr
  214. break
  215. end -= 1
  216. if cur_substr is None:
  217. is_bad = True
  218. break
  219. sub_tokens.append(cur_substr)
  220. start = end
  221. if is_bad:
  222. output_tokens.append(self.unk_token)
  223. else:
  224. output_tokens.extend(sub_tokens)
  225. return output_tokens
  226. def load_vocab(vocab_file):
  227. """Loads a vocabulary file into a dictionary."""
  228. vocab = collections.OrderedDict()
  229. with open(vocab_file, "r", encoding="utf-8") as reader:
  230. tokens = reader.readlines()
  231. for index, token in enumerate(tokens):
  232. token = token.rstrip("\n")
  233. vocab[token] = index
  234. return vocab
  235. class ProphetNetTokenizer(PreTrainedTokenizer):
  236. r"""
  237. Construct a ProphetNetTokenizer. Based on WordPiece.
  238. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  239. this superclass for more information regarding those methods.
  240. Args:
  241. vocab_file (`str`):
  242. File containing the vocabulary.
  243. do_lower_case (`bool`, *optional*, defaults to `True`):
  244. Whether or not to lowercase the input when tokenizing.
  245. do_basic_tokenize (`bool`, *optional*, defaults to `True`):
  246. Whether or not to do basic tokenization before WordPiece.
  247. never_split (`Iterable`, *optional*):
  248. Collection of tokens which will never be split during tokenization. Only has an effect when
  249. `do_basic_tokenize=True`
  250. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  251. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  252. token instead.
  253. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  254. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  255. sequence classification or for a text and a question for question answering. It is also used as the last
  256. token of a sequence built with special tokens.
  257. x_sep_token (`str`, *optional*, defaults to `"[X_SEP]"`):
  258. Special second separator token, which can be generated by [`ProphetNetForConditionalGeneration`]. It is
  259. used to separate bullet-point like sentences in summarization, *e.g.*.
  260. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  261. The token used for padding, for example when batching sequences of different lengths.
  262. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  263. The token used for masking values. This is the token used when training this model with masked language
  264. modeling. This is the token which the model will try to predict.
  265. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  266. Whether or not to tokenize Chinese characters.
  267. This should likely be deactivated for Japanese (see this
  268. [issue](https://github.com/huggingface/transformers/issues/328)).
  269. strip_accents (`bool`, *optional*):
  270. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  271. value for `lowercase` (as in the original BERT).
  272. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  273. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  274. extra spaces.
  275. """
  276. vocab_files_names = VOCAB_FILES_NAMES
  277. # first name has to correspond to main model input name
  278. # to make sure `tokenizer.pad(...)` works correctly
  279. # `ProphetNet` doesn't have `token_type_ids` as argument.
  280. model_input_names: list[str] = ["input_ids", "attention_mask"]
  281. def __init__(
  282. self,
  283. vocab_file: str,
  284. do_lower_case: Optional[bool] = True,
  285. do_basic_tokenize: Optional[bool] = True,
  286. never_split: Optional[Iterable] = None,
  287. unk_token: Optional[str] = "[UNK]",
  288. sep_token: Optional[str] = "[SEP]",
  289. x_sep_token: Optional[str] = "[X_SEP]",
  290. pad_token: Optional[str] = "[PAD]",
  291. mask_token: Optional[str] = "[MASK]",
  292. tokenize_chinese_chars: Optional[bool] = True,
  293. strip_accents: Optional[bool] = None,
  294. clean_up_tokenization_spaces: bool = True,
  295. **kwargs,
  296. ):
  297. if not os.path.isfile(vocab_file):
  298. raise ValueError(
  299. f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
  300. " model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
  301. )
  302. self.vocab = load_vocab(vocab_file)
  303. self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
  304. self.do_basic_tokenize = do_basic_tokenize
  305. if do_basic_tokenize:
  306. self.basic_tokenizer = BasicTokenizer(
  307. do_lower_case=do_lower_case,
  308. never_split=never_split,
  309. tokenize_chinese_chars=tokenize_chinese_chars,
  310. strip_accents=strip_accents,
  311. )
  312. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
  313. super().__init__(
  314. do_lower_case=do_lower_case,
  315. do_basic_tokenize=do_basic_tokenize,
  316. never_split=never_split,
  317. unk_token=unk_token,
  318. sep_token=sep_token,
  319. x_sep_token=x_sep_token,
  320. pad_token=pad_token,
  321. mask_token=mask_token,
  322. tokenize_chinese_chars=tokenize_chinese_chars,
  323. strip_accents=strip_accents,
  324. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  325. **kwargs,
  326. )
  327. @property
  328. def vocab_size(self):
  329. return len(self.vocab)
  330. def get_vocab(self):
  331. return dict(self.vocab, **self.added_tokens_encoder)
  332. def _tokenize(self, text):
  333. split_tokens = []
  334. if self.do_basic_tokenize:
  335. for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
  336. # If the token is part of the never_split set
  337. if token in self.basic_tokenizer.never_split:
  338. split_tokens.append(token)
  339. else:
  340. split_tokens += self.wordpiece_tokenizer.tokenize(token)
  341. else:
  342. split_tokens = self.wordpiece_tokenizer.tokenize(text)
  343. return split_tokens
  344. def _convert_token_to_id(self, token: str):
  345. """Converts a token (str) in an id using the vocab."""
  346. return self.vocab.get(token, self.vocab.get(self.unk_token))
  347. def _convert_id_to_token(self, index: int):
  348. """Converts an index (integer) in a token (str) using the vocab."""
  349. return self.ids_to_tokens.get(index, self.unk_token)
  350. def convert_tokens_to_string(self, tokens: str):
  351. """Converts a sequence of tokens (string) in a single string."""
  352. out_string = " ".join(tokens).replace(" ##", "").strip()
  353. return out_string
  354. def get_special_tokens_mask(
  355. self,
  356. token_ids_0: list[int],
  357. token_ids_1: Optional[list[int]] = None,
  358. already_has_special_tokens: Optional[bool] = False,
  359. ) -> list[int]:
  360. """
  361. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  362. special tokens using the tokenizer `prepare_for_model` method.
  363. Args:
  364. token_ids_0 (`List[int]`):
  365. List of IDs.
  366. token_ids_1 (`List[int]`, *optional*):
  367. Optional second list of IDs for sequence pairs.
  368. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  369. Whether or not the token list is already formatted with special tokens for the model.
  370. Returns:
  371. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  372. """
  373. if already_has_special_tokens:
  374. return super().get_special_tokens_mask(
  375. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  376. )
  377. if token_ids_1 is None:
  378. return ([0] * len(token_ids_0)) + [1]
  379. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  380. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  381. index = 0
  382. if os.path.isdir(save_directory):
  383. vocab_file = os.path.join(
  384. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  385. )
  386. else:
  387. vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
  388. with open(vocab_file, "w", encoding="utf-8") as writer:
  389. for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
  390. if index != token_index:
  391. logger.warning(
  392. f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
  393. " Please check that the vocabulary is not corrupted!"
  394. )
  395. index = token_index
  396. writer.write(token + "\n")
  397. index += 1
  398. return (vocab_file,)
  399. def build_inputs_with_special_tokens(
  400. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  401. ) -> list[int]:
  402. """
  403. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  404. adding special tokens. A BERT sequence has the following format:
  405. - single sequence: `[CLS] X [SEP]`
  406. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  407. Args:
  408. token_ids_0 (`List[int]`):
  409. List of IDs to which the special tokens will be added.
  410. token_ids_1 (`List[int]`, *optional*):
  411. Optional second list of IDs for sequence pairs.
  412. Returns:
  413. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  414. """
  415. if token_ids_1 is None:
  416. return token_ids_0 + [self.sep_token_id]
  417. sep = [self.sep_token_id]
  418. return token_ids_0 + sep + token_ids_1 + sep
  419. __all__ = ["ProphetNetTokenizer"]