tokenization_xlm.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. # Copyright 2019 The Open AI Team Authors and The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Tokenization classes for XLM."""
  15. import json
  16. import os
  17. import re
  18. import sys
  19. import unicodedata
  20. from ...tokenization_python import PreTrainedTokenizer
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {
  24. "vocab_file": "vocab.json",
  25. "merges_file": "merges.txt",
  26. }
  27. def get_pairs(word):
  28. """
  29. Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
  30. strings)
  31. """
  32. pairs = set()
  33. prev_char = word[0]
  34. for char in word[1:]:
  35. pairs.add((prev_char, char))
  36. prev_char = char
  37. return pairs
  38. def lowercase_and_remove_accent(text):
  39. """
  40. Lowercase and strips accents from a piece of text based on
  41. https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
  42. """
  43. text = " ".join(text)
  44. text = text.lower()
  45. text = unicodedata.normalize("NFD", text)
  46. output = []
  47. for char in text:
  48. cat = unicodedata.category(char)
  49. if cat == "Mn":
  50. continue
  51. output.append(char)
  52. return "".join(output).lower().split(" ")
  53. def replace_unicode_punct(text):
  54. """
  55. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
  56. """
  57. text = text.replace(",", ",")
  58. text = re.sub(r"。\s*", ". ", text)
  59. text = text.replace("、", ",")
  60. text = text.replace("”", '"')
  61. text = text.replace("“", '"')
  62. text = text.replace("∶", ":")
  63. text = text.replace(":", ":")
  64. text = text.replace("?", "?")
  65. text = text.replace("《", '"')
  66. text = text.replace("》", '"')
  67. text = text.replace(")", ")")
  68. text = text.replace("!", "!")
  69. text = text.replace("(", "(")
  70. text = text.replace(";", ";")
  71. text = text.replace("1", "1")
  72. text = text.replace("」", '"')
  73. text = text.replace("「", '"')
  74. text = text.replace("0", "0")
  75. text = text.replace("3", "3")
  76. text = text.replace("2", "2")
  77. text = text.replace("5", "5")
  78. text = text.replace("6", "6")
  79. text = text.replace("9", "9")
  80. text = text.replace("7", "7")
  81. text = text.replace("8", "8")
  82. text = text.replace("4", "4")
  83. text = re.sub(r".\s*", ". ", text)
  84. text = text.replace("~", "~")
  85. text = text.replace("’", "'")
  86. text = text.replace("…", "...")
  87. text = text.replace("━", "-")
  88. text = text.replace("〈", "<")
  89. text = text.replace("〉", ">")
  90. text = text.replace("【", "[")
  91. text = text.replace("】", "]")
  92. text = text.replace("%", "%")
  93. return text
  94. def remove_non_printing_char(text):
  95. """
  96. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
  97. """
  98. output = []
  99. for char in text:
  100. cat = unicodedata.category(char)
  101. if cat.startswith("C"):
  102. continue
  103. output.append(char)
  104. return "".join(output)
  105. def romanian_preprocessing(text):
  106. """Sennrich's WMT16 scripts for Romanian preprocessing, used by model `FacebookAI/xlm-mlm-enro-1024`"""
  107. # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/normalise-romanian.py
  108. text = text.replace("\u015e", "\u0218").replace("\u015f", "\u0219")
  109. text = text.replace("\u0162", "\u021a").replace("\u0163", "\u021b")
  110. # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/remove-diacritics.py
  111. text = text.replace("\u0218", "S").replace("\u0219", "s") # s-comma
  112. text = text.replace("\u021a", "T").replace("\u021b", "t") # t-comma
  113. text = text.replace("\u0102", "A").replace("\u0103", "a")
  114. text = text.replace("\u00c2", "A").replace("\u00e2", "a")
  115. text = text.replace("\u00ce", "I").replace("\u00ee", "i")
  116. return text
  117. class XLMTokenizer(PreTrainedTokenizer):
  118. """
  119. Construct an XLM tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
  120. - Moses preprocessing and tokenization for most supported languages.
  121. - Language specific tokenization for Chinese (Jieba), Japanese (KyTea) and Thai (PyThaiNLP).
  122. - Optionally lowercases and normalizes all inputs text.
  123. - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
  124. "__classify__") to a vocabulary.
  125. - The `lang2id` attribute maps the languages supported by the model with their IDs if provided (automatically set
  126. for pretrained vocabularies).
  127. - The `id2lang` attributes does reverse mapping if provided (automatically set for pretrained vocabularies).
  128. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  129. this superclass for more information regarding those methods.
  130. Args:
  131. vocab_file (`str`):
  132. Vocabulary file.
  133. merges_file (`str`):
  134. Merges file.
  135. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  136. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  137. token instead.
  138. bos_token (`str`, *optional*, defaults to `"<s>"`):
  139. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  140. <Tip>
  141. When building a sequence using special tokens, this is not the token that is used for the beginning of
  142. sequence. The token used is the `cls_token`.
  143. </Tip>
  144. sep_token (`str`, *optional*, defaults to `"</s>"`):
  145. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  146. sequence classification or for a text and a question for question answering. It is also used as the last
  147. token of a sequence built with special tokens.
  148. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  149. The token used for padding, for example when batching sequences of different lengths.
  150. cls_token (`str`, *optional*, defaults to `"</s>"`):
  151. The classifier token which is used when doing sequence classification (classification of the whole sequence
  152. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  153. mask_token (`str`, *optional*, defaults to `"<special1>"`):
  154. The token used for masking values. This is the token used when training this model with masked language
  155. modeling. This is the token which the model will try to predict.
  156. additional_special_tokens (`List[str]`, *optional*, defaults to `['<special0>', '<special1>', '<special2>', '<special3>', '<special4>', '<special5>', '<special6>', '<special7>', '<special8>', '<special9>']`):
  157. List of additional special tokens.
  158. lang2id (`Dict[str, int]`, *optional*):
  159. Dictionary mapping languages string identifiers to their IDs.
  160. id2lang (`Dict[int, str]`, *optional*):
  161. Dictionary mapping language IDs to their string identifiers.
  162. do_lowercase_and_remove_accent (`bool`, *optional*, defaults to `True`):
  163. Whether to lowercase and remove accents when tokenizing.
  164. """
  165. vocab_files_names = VOCAB_FILES_NAMES
  166. def __init__(
  167. self,
  168. vocab_file,
  169. merges_file,
  170. unk_token="<unk>",
  171. bos_token="<s>",
  172. sep_token="</s>",
  173. pad_token="<pad>",
  174. cls_token="</s>",
  175. mask_token="<special1>",
  176. additional_special_tokens=[
  177. "<special0>",
  178. "<special1>",
  179. "<special2>",
  180. "<special3>",
  181. "<special4>",
  182. "<special5>",
  183. "<special6>",
  184. "<special7>",
  185. "<special8>",
  186. "<special9>",
  187. ],
  188. lang2id=None,
  189. id2lang=None,
  190. do_lowercase_and_remove_accent=True,
  191. **kwargs,
  192. ):
  193. try:
  194. import sacremoses
  195. except ImportError:
  196. raise ImportError(
  197. "You need to install sacremoses to use XLMTokenizer. "
  198. "See https://pypi.org/project/sacremoses/ for installation."
  199. )
  200. self.sm = sacremoses
  201. # cache of sm.MosesPunctNormalizer instance
  202. self.cache_moses_punct_normalizer = {}
  203. # cache of sm.MosesTokenizer instance
  204. self.cache_moses_tokenizer = {}
  205. self.lang_with_custom_tokenizer = {"zh", "th", "ja"}
  206. # True for current supported model (v1.2.0), False for XLM-17 & 100
  207. self.do_lowercase_and_remove_accent = do_lowercase_and_remove_accent
  208. self.lang2id = lang2id
  209. self.id2lang = id2lang
  210. if lang2id is not None and id2lang is not None:
  211. assert len(lang2id) == len(id2lang)
  212. self.ja_word_tokenizer = None
  213. self.zh_word_tokenizer = None
  214. with open(vocab_file, encoding="utf-8") as vocab_handle:
  215. self.encoder = json.load(vocab_handle)
  216. self.decoder = {v: k for k, v in self.encoder.items()}
  217. with open(merges_file, encoding="utf-8") as merges_handle:
  218. merges = merges_handle.read().split("\n")[:-1]
  219. merges = [tuple(merge.split()[:2]) for merge in merges]
  220. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  221. self.cache = {}
  222. super().__init__(
  223. unk_token=unk_token,
  224. bos_token=bos_token,
  225. sep_token=sep_token,
  226. pad_token=pad_token,
  227. cls_token=cls_token,
  228. mask_token=mask_token,
  229. additional_special_tokens=additional_special_tokens,
  230. lang2id=lang2id,
  231. id2lang=id2lang,
  232. do_lowercase_and_remove_accent=do_lowercase_and_remove_accent,
  233. **kwargs,
  234. )
  235. @property
  236. def do_lower_case(self):
  237. return self.do_lowercase_and_remove_accent
  238. def moses_punct_norm(self, text, lang):
  239. if lang not in self.cache_moses_punct_normalizer:
  240. punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
  241. self.cache_moses_punct_normalizer[lang] = punct_normalizer
  242. else:
  243. punct_normalizer = self.cache_moses_punct_normalizer[lang]
  244. return punct_normalizer.normalize(text)
  245. def moses_tokenize(self, text, lang):
  246. if lang not in self.cache_moses_tokenizer:
  247. moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
  248. self.cache_moses_tokenizer[lang] = moses_tokenizer
  249. else:
  250. moses_tokenizer = self.cache_moses_tokenizer[lang]
  251. return moses_tokenizer.tokenize(text, return_str=False, escape=False)
  252. def moses_pipeline(self, text, lang):
  253. text = replace_unicode_punct(text)
  254. text = self.moses_punct_norm(text, lang)
  255. text = remove_non_printing_char(text)
  256. return text
  257. def ja_tokenize(self, text):
  258. if self.ja_word_tokenizer is None:
  259. try:
  260. import Mykytea
  261. self.ja_word_tokenizer = Mykytea.Mykytea(
  262. f"-model {os.path.expanduser('~')}/local/share/kytea/model.bin"
  263. )
  264. except (AttributeError, ImportError):
  265. logger.error(
  266. "Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper"
  267. " (https://github.com/chezou/Mykytea-python) with the following steps"
  268. )
  269. logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea")
  270. logger.error("2. autoreconf -i")
  271. logger.error("3. ./configure --prefix=$HOME/local")
  272. logger.error("4. make && make install")
  273. logger.error("5. pip install kytea")
  274. raise
  275. return list(self.ja_word_tokenizer.getWS(text))
  276. @property
  277. def vocab_size(self):
  278. return len(self.encoder)
  279. def get_vocab(self):
  280. return dict(self.encoder, **self.added_tokens_encoder)
  281. def bpe(self, token):
  282. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  283. if token in self.cache:
  284. return self.cache[token]
  285. pairs = get_pairs(word)
  286. if not pairs:
  287. return token + "</w>"
  288. while True:
  289. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  290. if bigram not in self.bpe_ranks:
  291. break
  292. first, second = bigram
  293. new_word = []
  294. i = 0
  295. while i < len(word):
  296. try:
  297. j = word.index(first, i)
  298. except ValueError:
  299. new_word.extend(word[i:])
  300. break
  301. else:
  302. new_word.extend(word[i:j])
  303. i = j
  304. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  305. new_word.append(first + second)
  306. i += 2
  307. else:
  308. new_word.append(word[i])
  309. i += 1
  310. new_word = tuple(new_word)
  311. word = new_word
  312. if len(word) == 1:
  313. break
  314. else:
  315. pairs = get_pairs(word)
  316. word = " ".join(word)
  317. if word == "\n </w>":
  318. word = "\n</w>"
  319. self.cache[token] = word
  320. return word
  321. def _tokenize(self, text, lang="en", bypass_tokenizer=False):
  322. """
  323. Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific tokenizer.
  324. Otherwise, we use Moses.
  325. Details of tokenization:
  326. - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
  327. - Install with `pip install sacremoses`
  328. - [pythainlp](https://github.com/PyThaiNLP/pythainlp): Thai tokenizer
  329. - Install with `pip install pythainlp`
  330. - [kytea](https://github.com/chezou/Mykytea-python): Japanese tokenizer, wrapper of
  331. [KyTea](https://github.com/neubig/kytea)
  332. - Install with the following steps:
  333. ::
  334. git clone git@github.com:neubig/kytea.git && cd kytea autoreconf -i ./configure --prefix=$HOME/local
  335. make && make install pip install kytea
  336. - [rjieba](https://github.com/messense/rjieba-py): Chinese tokenizer (*)
  337. - Install with `pip install rjieba`
  338. (*) The original XLM used [Stanford
  339. Segmenter](https://nlp.stanford.edu/software/stanford-segmenter-2018-10-16.zip). However, the wrapper
  340. (`nltk.tokenize.stanford_segmenter`) is slow due to JVM overhead, and it will be deprecated. Jieba is a lot
  341. faster and pip-installable. Note there is some mismatch with the Stanford Segmenter. It should be fine if you
  342. fine-tune the model with Chinese supervisionself. If you want the same exact behaviour, use the original XLM
  343. [preprocessing script](https://github.com/facebookresearch/XLM/tree/master/tools) to tokenize the sentence
  344. externally, and set `bypass_tokenizer=True` to bypass the tokenizer.
  345. Args:
  346. - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported
  347. languages. However, we don't enforce it.
  348. - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
  349. (bool). If True, we only apply BPE.
  350. Returns:
  351. List of tokens.
  352. """
  353. if lang and self.lang2id and lang not in self.lang2id:
  354. logger.error(
  355. "Supplied language code not found in lang2id mapping. Please check that your language is supported by"
  356. " the loaded pretrained model."
  357. )
  358. if bypass_tokenizer:
  359. text = text.split()
  360. elif lang not in self.lang_with_custom_tokenizer:
  361. text = self.moses_pipeline(text, lang=lang)
  362. # TODO: make sure we are using `FacebookAI/xlm-mlm-enro-1024`, since XLM-100 doesn't have this step
  363. if lang == "ro":
  364. text = romanian_preprocessing(text)
  365. text = self.moses_tokenize(text, lang=lang)
  366. elif lang == "th":
  367. text = self.moses_pipeline(text, lang=lang)
  368. try:
  369. if "pythainlp" not in sys.modules:
  370. from pythainlp.tokenize import word_tokenize as th_word_tokenize
  371. else:
  372. th_word_tokenize = sys.modules["pythainlp"].word_tokenize
  373. except (AttributeError, ImportError):
  374. logger.error(
  375. "Make sure you install PyThaiNLP (https://github.com/PyThaiNLP/pythainlp) with the following steps"
  376. )
  377. logger.error("1. pip install pythainlp")
  378. raise
  379. text = th_word_tokenize(text)
  380. elif lang == "zh":
  381. try:
  382. if "rjieba" not in sys.modules:
  383. import rjieba
  384. else:
  385. rjieba = sys.modules["rjieba"]
  386. except (AttributeError, ImportError):
  387. logger.error(
  388. "Make sure you install rjieba (https://github.com/messense/rjieba-py) with the following steps"
  389. )
  390. logger.error("1. pip install rjieba")
  391. raise
  392. text = " ".join(rjieba.cut(text))
  393. text = self.moses_pipeline(text, lang=lang)
  394. text = text.split()
  395. elif lang == "ja":
  396. text = self.moses_pipeline(text, lang=lang)
  397. text = self.ja_tokenize(text)
  398. else:
  399. raise ValueError("It should not reach here")
  400. if self.do_lowercase_and_remove_accent and not bypass_tokenizer:
  401. text = lowercase_and_remove_accent(text)
  402. split_tokens = []
  403. for token in text:
  404. if token:
  405. split_tokens.extend(list(self.bpe(token).split(" ")))
  406. return split_tokens
  407. def _convert_token_to_id(self, token):
  408. """Converts a token (str) in an id using the vocab."""
  409. return self.encoder.get(token, self.encoder.get(self.unk_token))
  410. def _convert_id_to_token(self, index):
  411. """Converts an index (integer) in a token (str) using the vocab."""
  412. return self.decoder.get(index, self.unk_token)
  413. def convert_tokens_to_string(self, tokens):
  414. """Converts a sequence of tokens (string) in a single string."""
  415. out_string = "".join(tokens).replace("</w>", " ").strip()
  416. return out_string
  417. def build_inputs_with_special_tokens(
  418. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  419. ) -> list[int]:
  420. """
  421. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  422. adding special tokens. An XLM sequence has the following format:
  423. - single sequence: `<s> X </s>`
  424. - pair of sequences: `<s> A </s> B </s>`
  425. Args:
  426. token_ids_0 (`List[int]`):
  427. List of IDs to which the special tokens will be added.
  428. token_ids_1 (`List[int]`, *optional*):
  429. Optional second list of IDs for sequence pairs.
  430. Returns:
  431. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  432. """
  433. bos = [self.bos_token_id]
  434. sep = [self.sep_token_id]
  435. if token_ids_1 is None:
  436. return bos + token_ids_0 + sep
  437. return bos + token_ids_0 + sep + token_ids_1 + sep
  438. def get_special_tokens_mask(
  439. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  440. ) -> list[int]:
  441. """
  442. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  443. special tokens using the tokenizer `prepare_for_model` method.
  444. Args:
  445. token_ids_0 (`List[int]`):
  446. List of IDs.
  447. token_ids_1 (`List[int]`, *optional*):
  448. Optional second list of IDs for sequence pairs.
  449. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  450. Whether or not the token list is already formatted with special tokens for the model.
  451. Returns:
  452. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  453. """
  454. if already_has_special_tokens:
  455. return super().get_special_tokens_mask(
  456. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  457. )
  458. if token_ids_1 is not None:
  459. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  460. return [1] + ([0] * len(token_ids_0)) + [1]
  461. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  462. if not os.path.isdir(save_directory):
  463. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  464. return
  465. vocab_file = os.path.join(
  466. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  467. )
  468. merge_file = os.path.join(
  469. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  470. )
  471. with open(vocab_file, "w", encoding="utf-8") as f:
  472. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  473. index = 0
  474. with open(merge_file, "w", encoding="utf-8") as writer:
  475. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  476. if index != token_index:
  477. logger.warning(
  478. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  479. " Please check that the tokenizer is not corrupted!"
  480. )
  481. index = token_index
  482. writer.write(" ".join(bpe_tokens) + "\n")
  483. index += 1
  484. return vocab_file, merge_file
  485. def __getstate__(self):
  486. state = self.__dict__.copy()
  487. state["sm"] = None
  488. return state
  489. def __setstate__(self, d):
  490. self.__dict__ = d
  491. try:
  492. import sacremoses
  493. except ImportError:
  494. raise ImportError(
  495. "You need to install sacremoses to use XLMTokenizer. "
  496. "See https://pypi.org/project/sacremoses/ for installation."
  497. )
  498. self.sm = sacremoses
  499. __all__ = ["XLMTokenizer"]