tokenization_flaubert.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. # Copyright 2019-present CNRS, Facebook Inc. 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 Flaubert."""
  15. import json
  16. import os
  17. import re
  18. import unicodedata
  19. from ...tokenization_python import PreTrainedTokenizer
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. VOCAB_FILES_NAMES = {
  23. "vocab_file": "vocab.json",
  24. "merges_file": "merges.txt",
  25. }
  26. def convert_to_unicode(text):
  27. """
  28. Converts `text` to Unicode (if it's not already), assuming UTF-8 input.
  29. """
  30. def ensure_text(s, encoding="utf-8", errors="strict"):
  31. if isinstance(s, bytes):
  32. return s.decode(encoding, errors)
  33. elif isinstance(s, str):
  34. return s
  35. else:
  36. raise TypeError(f"not expecting type '{type(s)}'")
  37. return ensure_text(text, encoding="utf-8", errors="ignore")
  38. # Copied from transformers.models.xlm.tokenization_xlm.get_pairs
  39. def get_pairs(word):
  40. """
  41. Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
  42. strings)
  43. """
  44. pairs = set()
  45. prev_char = word[0]
  46. for char in word[1:]:
  47. pairs.add((prev_char, char))
  48. prev_char = char
  49. return pairs
  50. # Copied from transformers.models.xlm.tokenization_xlm.replace_unicode_punct
  51. def replace_unicode_punct(text):
  52. """
  53. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
  54. """
  55. text = text.replace(",", ",")
  56. text = re.sub(r"。\s*", ". ", text)
  57. text = text.replace("、", ",")
  58. text = text.replace("”", '"')
  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("1", "1")
  70. text = text.replace("」", '"')
  71. text = text.replace("「", '"')
  72. text = text.replace("0", "0")
  73. text = text.replace("3", "3")
  74. text = text.replace("2", "2")
  75. text = text.replace("5", "5")
  76. text = text.replace("6", "6")
  77. text = text.replace("9", "9")
  78. text = text.replace("7", "7")
  79. text = text.replace("8", "8")
  80. text = text.replace("4", "4")
  81. text = re.sub(r".\s*", ". ", text)
  82. text = text.replace("~", "~")
  83. text = text.replace("’", "'")
  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. return text
  92. # Copied from transformers.models.xlm.tokenization_xlm.remove_non_printing_char
  93. def remove_non_printing_char(text):
  94. """
  95. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
  96. """
  97. output = []
  98. for char in text:
  99. cat = unicodedata.category(char)
  100. if cat.startswith("C"):
  101. continue
  102. output.append(char)
  103. return "".join(output)
  104. class FlaubertTokenizer(PreTrainedTokenizer):
  105. """
  106. Construct a Flaubert tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
  107. - Moses preprocessing and tokenization.
  108. - Normalizing all inputs text.
  109. - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
  110. "__classify__") to a vocabulary.
  111. - The argument `do_lowercase` controls lower casing (automatically set for pretrained vocabularies).
  112. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  113. this superclass for more information regarding those methods.
  114. Args:
  115. vocab_file (`str`):
  116. Vocabulary file.
  117. merges_file (`str`):
  118. Merges file.
  119. do_lowercase (`bool`, *optional*, defaults to `False`):
  120. Controls lower casing.
  121. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  122. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  123. token instead.
  124. bos_token (`str`, *optional*, defaults to `"<s>"`):
  125. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  126. <Tip>
  127. When building a sequence using special tokens, this is not the token that is used for the beginning of
  128. sequence. The token used is the `cls_token`.
  129. </Tip>
  130. sep_token (`str`, *optional*, defaults to `"</s>"`):
  131. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  132. sequence classification or for a text and a question for question answering. It is also used as the last
  133. token of a sequence built with special tokens.
  134. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  135. The token used for padding, for example when batching sequences of different lengths.
  136. cls_token (`str`, *optional*, defaults to `"</s>"`):
  137. The classifier token which is used when doing sequence classification (classification of the whole sequence
  138. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  139. mask_token (`str`, *optional*, defaults to `"<special1>"`):
  140. The token used for masking values. This is the token used when training this model with masked language
  141. modeling. This is the token which the model will try to predict.
  142. additional_special_tokens (`List[str]`, *optional*, defaults to `['<special0>', '<special1>', '<special2>', '<special3>', '<special4>', '<special5>', '<special6>', '<special7>', '<special8>', '<special9>']`):
  143. List of additional special tokens.
  144. lang2id (`Dict[str, int]`, *optional*):
  145. Dictionary mapping languages string identifiers to their IDs.
  146. id2lang (`Dict[int, str]`, *optional*):
  147. Dictionary mapping language IDs to their string identifiers.
  148. """
  149. vocab_files_names = VOCAB_FILES_NAMES
  150. def __init__(
  151. self,
  152. vocab_file,
  153. merges_file,
  154. do_lowercase=False,
  155. unk_token="<unk>",
  156. bos_token="<s>",
  157. sep_token="</s>",
  158. pad_token="<pad>",
  159. cls_token="</s>",
  160. mask_token="<special1>",
  161. additional_special_tokens=[
  162. "<special0>",
  163. "<special1>",
  164. "<special2>",
  165. "<special3>",
  166. "<special4>",
  167. "<special5>",
  168. "<special6>",
  169. "<special7>",
  170. "<special8>",
  171. "<special9>",
  172. ],
  173. lang2id=None,
  174. id2lang=None,
  175. **kwargs,
  176. ):
  177. do_lowercase_and_remove_accent = kwargs.pop("do_lowercase_and_remove_accent", None)
  178. if do_lowercase_and_remove_accent is not None:
  179. logger.warning(
  180. "`do_lowercase_and_remove_accent` is passed as a keyword argument, but this won't do anything."
  181. " `FlaubertTokenizer` will always set it to `False`."
  182. )
  183. # always `False`
  184. self.do_lowercase_and_remove_accent = False
  185. self.do_lowercase = do_lowercase
  186. try:
  187. import sacremoses
  188. except ImportError:
  189. raise ImportError(
  190. "You need to install sacremoses to use FlaubertTokenizer. "
  191. "See https://pypi.org/project/sacremoses/ for installation."
  192. )
  193. self.sm = sacremoses
  194. # cache of sm.MosesPunctNormalizer instance
  195. self.cache_moses_punct_normalizer = {}
  196. # cache of sm.MosesTokenizer instance
  197. self.cache_moses_tokenizer = {}
  198. self.lang_with_custom_tokenizer = {"zh", "th", "ja"}
  199. self.lang2id = lang2id
  200. self.id2lang = id2lang
  201. if lang2id is not None and id2lang is not None:
  202. assert len(lang2id) == len(id2lang)
  203. self.ja_word_tokenizer = None
  204. self.zh_word_tokenizer = None
  205. with open(vocab_file, encoding="utf-8") as vocab_handle:
  206. self.encoder = json.load(vocab_handle)
  207. self.decoder = {v: k for k, v in self.encoder.items()}
  208. with open(merges_file, encoding="utf-8") as merges_handle:
  209. merges = merges_handle.read().split("\n")[:-1]
  210. merges = [tuple(merge.split()[:2]) for merge in merges]
  211. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  212. self.cache = {}
  213. super().__init__(
  214. do_lowercase=do_lowercase,
  215. unk_token=unk_token,
  216. bos_token=bos_token,
  217. sep_token=sep_token,
  218. pad_token=pad_token,
  219. cls_token=cls_token,
  220. mask_token=mask_token,
  221. additional_special_tokens=additional_special_tokens,
  222. lang2id=lang2id,
  223. id2lang=id2lang,
  224. **kwargs,
  225. )
  226. @property
  227. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.do_lower_case
  228. def do_lower_case(self):
  229. return self.do_lowercase_and_remove_accent
  230. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_punct_norm
  231. def moses_punct_norm(self, text, lang):
  232. if lang not in self.cache_moses_punct_normalizer:
  233. punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
  234. self.cache_moses_punct_normalizer[lang] = punct_normalizer
  235. else:
  236. punct_normalizer = self.cache_moses_punct_normalizer[lang]
  237. return punct_normalizer.normalize(text)
  238. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_tokenize
  239. def moses_tokenize(self, text, lang):
  240. if lang not in self.cache_moses_tokenizer:
  241. moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
  242. self.cache_moses_tokenizer[lang] = moses_tokenizer
  243. else:
  244. moses_tokenizer = self.cache_moses_tokenizer[lang]
  245. return moses_tokenizer.tokenize(text, return_str=False, escape=False)
  246. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_pipeline
  247. def moses_pipeline(self, text, lang):
  248. text = replace_unicode_punct(text)
  249. text = self.moses_punct_norm(text, lang)
  250. text = remove_non_printing_char(text)
  251. return text
  252. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.ja_tokenize
  253. def ja_tokenize(self, text):
  254. if self.ja_word_tokenizer is None:
  255. try:
  256. import Mykytea
  257. self.ja_word_tokenizer = Mykytea.Mykytea(
  258. f"-model {os.path.expanduser('~')}/local/share/kytea/model.bin"
  259. )
  260. except (AttributeError, ImportError):
  261. logger.error(
  262. "Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper"
  263. " (https://github.com/chezou/Mykytea-python) with the following steps"
  264. )
  265. logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea")
  266. logger.error("2. autoreconf -i")
  267. logger.error("3. ./configure --prefix=$HOME/local")
  268. logger.error("4. make && make install")
  269. logger.error("5. pip install kytea")
  270. raise
  271. return list(self.ja_word_tokenizer.getWS(text))
  272. @property
  273. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.vocab_size
  274. def vocab_size(self):
  275. return len(self.encoder)
  276. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.get_vocab
  277. def get_vocab(self):
  278. return dict(self.encoder, **self.added_tokens_encoder)
  279. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.bpe
  280. def bpe(self, token):
  281. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  282. if token in self.cache:
  283. return self.cache[token]
  284. pairs = get_pairs(word)
  285. if not pairs:
  286. return token + "</w>"
  287. while True:
  288. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  289. if bigram not in self.bpe_ranks:
  290. break
  291. first, second = bigram
  292. new_word = []
  293. i = 0
  294. while i < len(word):
  295. try:
  296. j = word.index(first, i)
  297. except ValueError:
  298. new_word.extend(word[i:])
  299. break
  300. else:
  301. new_word.extend(word[i:j])
  302. i = j
  303. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  304. new_word.append(first + second)
  305. i += 2
  306. else:
  307. new_word.append(word[i])
  308. i += 1
  309. new_word = tuple(new_word)
  310. word = new_word
  311. if len(word) == 1:
  312. break
  313. else:
  314. pairs = get_pairs(word)
  315. word = " ".join(word)
  316. if word == "\n </w>":
  317. word = "\n</w>"
  318. self.cache[token] = word
  319. return word
  320. def preprocess_text(self, text):
  321. text = text.replace("``", '"').replace("''", '"')
  322. text = convert_to_unicode(text)
  323. text = unicodedata.normalize("NFC", text)
  324. if self.do_lowercase:
  325. text = text.lower()
  326. return text
  327. def _tokenize(self, text, bypass_tokenizer=False):
  328. """
  329. Tokenize a string given language code using Moses.
  330. Details of tokenization:
  331. - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
  332. - Install with `pip install sacremoses`
  333. Args:
  334. - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
  335. (bool). If True, we only apply BPE.
  336. Returns:
  337. List of tokens.
  338. """
  339. lang = "fr"
  340. if lang and self.lang2id and lang not in self.lang2id:
  341. logger.error(
  342. "Supplied language code not found in lang2id mapping. Please check that your language is supported by"
  343. " the loaded pretrained model."
  344. )
  345. if bypass_tokenizer:
  346. text = text.split()
  347. else:
  348. text = self.preprocess_text(text)
  349. text = self.moses_pipeline(text, lang=lang)
  350. text = self.moses_tokenize(text, lang=lang)
  351. split_tokens = []
  352. for token in text:
  353. if token:
  354. split_tokens.extend(list(self.bpe(token).split(" ")))
  355. return split_tokens
  356. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer._convert_token_to_id
  357. def _convert_token_to_id(self, token):
  358. """Converts a token (str) in an id using the vocab."""
  359. return self.encoder.get(token, self.encoder.get(self.unk_token))
  360. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer._convert_id_to_token
  361. def _convert_id_to_token(self, index):
  362. """Converts an index (integer) in a token (str) using the vocab."""
  363. return self.decoder.get(index, self.unk_token)
  364. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.convert_tokens_to_string
  365. def convert_tokens_to_string(self, tokens):
  366. """Converts a sequence of tokens (string) in a single string."""
  367. out_string = "".join(tokens).replace("</w>", " ").strip()
  368. return out_string
  369. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.build_inputs_with_special_tokens
  370. def build_inputs_with_special_tokens(
  371. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  372. ) -> list[int]:
  373. """
  374. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  375. adding special tokens. An XLM sequence has the following format:
  376. - single sequence: `<s> X </s>`
  377. - pair of sequences: `<s> A </s> B </s>`
  378. Args:
  379. token_ids_0 (`List[int]`):
  380. List of IDs to which the special tokens will be added.
  381. token_ids_1 (`List[int]`, *optional*):
  382. Optional second list of IDs for sequence pairs.
  383. Returns:
  384. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  385. """
  386. bos = [self.bos_token_id]
  387. sep = [self.sep_token_id]
  388. if token_ids_1 is None:
  389. return bos + token_ids_0 + sep
  390. return bos + token_ids_0 + sep + token_ids_1 + sep
  391. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.get_special_tokens_mask
  392. def get_special_tokens_mask(
  393. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  394. ) -> list[int]:
  395. """
  396. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  397. special tokens using the tokenizer `prepare_for_model` method.
  398. Args:
  399. token_ids_0 (`List[int]`):
  400. List of IDs.
  401. token_ids_1 (`List[int]`, *optional*):
  402. Optional second list of IDs for sequence pairs.
  403. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  404. Whether or not the token list is already formatted with special tokens for the model.
  405. Returns:
  406. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  407. """
  408. if already_has_special_tokens:
  409. return super().get_special_tokens_mask(
  410. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  411. )
  412. if token_ids_1 is not None:
  413. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  414. return [1] + ([0] * len(token_ids_0)) + [1]
  415. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.save_vocabulary
  416. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  417. if not os.path.isdir(save_directory):
  418. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  419. return
  420. vocab_file = os.path.join(
  421. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  422. )
  423. merge_file = os.path.join(
  424. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  425. )
  426. with open(vocab_file, "w", encoding="utf-8") as f:
  427. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  428. index = 0
  429. with open(merge_file, "w", encoding="utf-8") as writer:
  430. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  431. if index != token_index:
  432. logger.warning(
  433. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  434. " Please check that the tokenizer is not corrupted!"
  435. )
  436. index = token_index
  437. writer.write(" ".join(bpe_tokens) + "\n")
  438. index += 1
  439. return vocab_file, merge_file
  440. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.__getstate__
  441. def __getstate__(self):
  442. state = self.__dict__.copy()
  443. state["sm"] = None
  444. return state
  445. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.__setstate__
  446. def __setstate__(self, d):
  447. self.__dict__ = d
  448. try:
  449. import sacremoses
  450. except ImportError:
  451. raise ImportError(
  452. "You need to install sacremoses to use XLMTokenizer. "
  453. "See https://pypi.org/project/sacremoses/ for installation."
  454. )
  455. self.sm = sacremoses
  456. __all__ = ["FlaubertTokenizer"]