tokenization_mpnet.py 22 KB

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