tokenization_fsmt.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 FSMT."""
  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. "src_vocab_file": "vocab-src.json",
  24. "tgt_vocab_file": "vocab-tgt.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 replace_unicode_punct(text):
  39. """
  40. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
  41. """
  42. text = text.replace(",", ",")
  43. text = re.sub(r"。\s*", ". ", text)
  44. text = text.replace("、", ",")
  45. text = text.replace("”", '"')
  46. text = text.replace("“", '"')
  47. text = text.replace("∶", ":")
  48. text = text.replace(":", ":")
  49. text = text.replace("?", "?")
  50. text = text.replace("《", '"')
  51. text = text.replace("》", '"')
  52. text = text.replace(")", ")")
  53. text = text.replace("!", "!")
  54. text = text.replace("(", "(")
  55. text = text.replace(";", ";")
  56. text = text.replace("1", "1")
  57. text = text.replace("」", '"')
  58. text = text.replace("「", '"')
  59. text = text.replace("0", "0")
  60. text = text.replace("3", "3")
  61. text = text.replace("2", "2")
  62. text = text.replace("5", "5")
  63. text = text.replace("6", "6")
  64. text = text.replace("9", "9")
  65. text = text.replace("7", "7")
  66. text = text.replace("8", "8")
  67. text = text.replace("4", "4")
  68. text = re.sub(r".\s*", ". ", text)
  69. text = text.replace("~", "~")
  70. text = text.replace("’", "'")
  71. text = text.replace("…", "...")
  72. text = text.replace("━", "-")
  73. text = text.replace("〈", "<")
  74. text = text.replace("〉", ">")
  75. text = text.replace("【", "[")
  76. text = text.replace("】", "]")
  77. text = text.replace("%", "%")
  78. return text
  79. def remove_non_printing_char(text):
  80. """
  81. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
  82. """
  83. output = []
  84. for char in text:
  85. cat = unicodedata.category(char)
  86. if cat.startswith("C"):
  87. continue
  88. output.append(char)
  89. return "".join(output)
  90. # Porting notes:
  91. # this one is modeled after XLMTokenizer
  92. #
  93. # added:
  94. # - src_vocab_file,
  95. # - tgt_vocab_file,
  96. # - langs,
  97. class FSMTTokenizer(PreTrainedTokenizer):
  98. """
  99. Construct an FAIRSEQ Transformer tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
  100. - Moses preprocessing and tokenization.
  101. - Normalizing all inputs text.
  102. - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
  103. "__classify__") to a vocabulary.
  104. - The argument `langs` defines a pair of languages.
  105. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  106. this superclass for more information regarding those methods.
  107. Args:
  108. langs (`List[str]`, *optional*):
  109. A list of two languages to translate from and to, for instance `["en", "ru"]`.
  110. src_vocab_file (`str`, *optional*):
  111. File containing the vocabulary for the source language.
  112. tgt_vocab_file (`st`, *optional*):
  113. File containing the vocabulary for the target language.
  114. merges_file (`str`, *optional*):
  115. File containing the merges.
  116. do_lower_case (`bool`, *optional*, defaults to `False`):
  117. Whether or not to lowercase the input when tokenizing.
  118. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  119. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  120. token instead.
  121. bos_token (`str`, *optional*, defaults to `"<s>"`):
  122. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  123. <Tip>
  124. When building a sequence using special tokens, this is not the token that is used for the beginning of
  125. sequence. The token used is the `cls_token`.
  126. </Tip>
  127. sep_token (`str`, *optional*, defaults to `"</s>"`):
  128. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  129. sequence classification or for a text and a question for question answering. It is also used as the last
  130. token of a sequence built with special tokens.
  131. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  132. The token used for padding, for example when batching sequences of different lengths.
  133. """
  134. vocab_files_names = VOCAB_FILES_NAMES
  135. model_input_names = ["input_ids", "attention_mask"]
  136. def __init__(
  137. self,
  138. langs=None,
  139. src_vocab_file=None,
  140. tgt_vocab_file=None,
  141. merges_file=None,
  142. do_lower_case=False,
  143. unk_token="<unk>",
  144. bos_token="<s>",
  145. sep_token="</s>",
  146. pad_token="<pad>",
  147. **kwargs,
  148. ):
  149. try:
  150. import sacremoses
  151. except ImportError:
  152. raise ImportError(
  153. "You need to install sacremoses to use XLMTokenizer. "
  154. "See https://pypi.org/project/sacremoses/ for installation."
  155. )
  156. self.sm = sacremoses
  157. self.src_vocab_file = src_vocab_file
  158. self.tgt_vocab_file = tgt_vocab_file
  159. self.merges_file = merges_file
  160. self.do_lower_case = do_lower_case
  161. # cache of sm.MosesPunctNormalizer instance
  162. self.cache_moses_punct_normalizer = {}
  163. # cache of sm.MosesTokenizer instance
  164. self.cache_moses_tokenizer = {}
  165. self.cache_moses_detokenizer = {}
  166. if langs and len(langs) == 2:
  167. self.src_lang, self.tgt_lang = langs
  168. else:
  169. raise ValueError(
  170. f"arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. "
  171. "Usually that means that tokenizer can't find a mapping for the given model path "
  172. "in and other maps of this tokenizer."
  173. )
  174. with open(src_vocab_file, encoding="utf-8") as src_vocab_handle:
  175. self.encoder = json.load(src_vocab_handle)
  176. with open(tgt_vocab_file, encoding="utf-8") as tgt_vocab_handle:
  177. tgt_vocab = json.load(tgt_vocab_handle)
  178. self.decoder = {v: k for k, v in tgt_vocab.items()}
  179. with open(merges_file, encoding="utf-8") as merges_handle:
  180. merges = merges_handle.read().split("\n")[:-1]
  181. merges = [tuple(merge.split()[:2]) for merge in merges]
  182. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  183. self.cache = {}
  184. super().__init__(
  185. langs=langs,
  186. src_vocab_file=src_vocab_file,
  187. tgt_vocab_file=tgt_vocab_file,
  188. merges_file=merges_file,
  189. do_lower_case=do_lower_case,
  190. unk_token=unk_token,
  191. bos_token=bos_token,
  192. sep_token=sep_token,
  193. pad_token=pad_token,
  194. **kwargs,
  195. )
  196. # hack override
  197. def get_vocab(self) -> dict[str, int]:
  198. return self.get_src_vocab()
  199. # hack override
  200. @property
  201. def vocab_size(self) -> int:
  202. return self.src_vocab_size
  203. def moses_punct_norm(self, text, lang):
  204. if lang not in self.cache_moses_punct_normalizer:
  205. punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
  206. self.cache_moses_punct_normalizer[lang] = punct_normalizer
  207. return self.cache_moses_punct_normalizer[lang].normalize(text)
  208. def moses_tokenize(self, text, lang):
  209. if lang not in self.cache_moses_tokenizer:
  210. moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
  211. self.cache_moses_tokenizer[lang] = moses_tokenizer
  212. return self.cache_moses_tokenizer[lang].tokenize(
  213. text, aggressive_dash_splits=True, return_str=False, escape=True
  214. )
  215. def moses_detokenize(self, tokens, lang):
  216. if lang not in self.cache_moses_detokenizer:
  217. moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
  218. self.cache_moses_detokenizer[lang] = moses_detokenizer
  219. return self.cache_moses_detokenizer[lang].detokenize(tokens)
  220. def moses_pipeline(self, text, lang):
  221. text = replace_unicode_punct(text)
  222. text = self.moses_punct_norm(text, lang)
  223. text = remove_non_printing_char(text)
  224. return text
  225. @property
  226. def src_vocab_size(self):
  227. return len(self.encoder)
  228. @property
  229. def tgt_vocab_size(self):
  230. return len(self.decoder)
  231. def get_src_vocab(self):
  232. return dict(self.encoder, **self.added_tokens_encoder)
  233. def get_tgt_vocab(self):
  234. return dict(self.decoder, **self.added_tokens_decoder)
  235. def bpe(self, token):
  236. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  237. if token in self.cache:
  238. return self.cache[token]
  239. pairs = get_pairs(word)
  240. if not pairs:
  241. return token + "</w>"
  242. while True:
  243. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  244. if bigram not in self.bpe_ranks:
  245. break
  246. first, second = bigram
  247. new_word = []
  248. i = 0
  249. while i < len(word):
  250. try:
  251. j = word.index(first, i)
  252. except ValueError:
  253. new_word.extend(word[i:])
  254. break
  255. else:
  256. new_word.extend(word[i:j])
  257. i = j
  258. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  259. new_word.append(first + second)
  260. i += 2
  261. else:
  262. new_word.append(word[i])
  263. i += 1
  264. new_word = tuple(new_word)
  265. word = new_word
  266. if len(word) == 1:
  267. break
  268. else:
  269. pairs = get_pairs(word)
  270. word = " ".join(word)
  271. if word == "\n </w>":
  272. word = "\n</w>"
  273. self.cache[token] = word
  274. return word
  275. def _tokenize(self, text, lang="en", bypass_tokenizer=False):
  276. """
  277. Tokenize a string given language code using Moses.
  278. Details of tokenization:
  279. - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
  280. - Install with `pip install sacremoses`
  281. Args:
  282. - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported
  283. languages. However, we don't enforce it.
  284. - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
  285. (bool). If True, we only apply BPE.
  286. Returns:
  287. List of tokens.
  288. """
  289. # ignore `lang` which is currently isn't explicitly passed in tokenization_utils.py and always results in lang=en
  290. # if lang != self.src_lang:
  291. # raise ValueError(f"Expected lang={self.src_lang}, but got {lang}")
  292. lang = self.src_lang
  293. if self.do_lower_case:
  294. text = text.lower()
  295. if bypass_tokenizer:
  296. text = text.split()
  297. else:
  298. text = self.moses_pipeline(text, lang=lang)
  299. text = self.moses_tokenize(text, lang=lang)
  300. split_tokens = []
  301. for token in text:
  302. if token:
  303. split_tokens.extend(list(self.bpe(token).split(" ")))
  304. return split_tokens
  305. def _convert_token_to_id(self, token):
  306. """Converts a token (str) in an id using the vocab."""
  307. return self.encoder.get(token, self.encoder.get(self.unk_token))
  308. def _convert_id_to_token(self, index):
  309. """Converts an index (integer) in a token (str) using the vocab."""
  310. return self.decoder.get(index, self.unk_token)
  311. def convert_tokens_to_string(self, tokens):
  312. """Converts a sequence of tokens (string) in a single string."""
  313. # remove BPE
  314. tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens]
  315. tokens = "".join(tokens).split()
  316. # detokenize
  317. text = self.moses_detokenize(tokens, self.tgt_lang)
  318. return text
  319. def build_inputs_with_special_tokens(
  320. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  321. ) -> list[int]:
  322. """
  323. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  324. adding special tokens. A FAIRSEQ Transformer sequence has the following format:
  325. - single sequence: `<s> X </s>`
  326. - pair of sequences: `<s> A </s> B </s>`
  327. Args:
  328. token_ids_0 (`List[int]`):
  329. List of IDs to which the special tokens will be added.
  330. token_ids_1 (`List[int]`, *optional*):
  331. Optional second list of IDs for sequence pairs.
  332. Returns:
  333. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  334. """
  335. sep = [self.sep_token_id]
  336. # no bos used in fairseq
  337. if token_ids_1 is None:
  338. return token_ids_0 + sep
  339. return token_ids_0 + sep + token_ids_1 + sep
  340. def get_special_tokens_mask(
  341. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  342. ) -> list[int]:
  343. """
  344. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  345. special tokens using the tokenizer `prepare_for_model` method.
  346. Args:
  347. token_ids_0 (`List[int]`):
  348. List of IDs.
  349. token_ids_1 (`List[int]`, *optional*):
  350. Optional second list of IDs for sequence pairs.
  351. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  352. Whether or not the token list is already formatted with special tokens for the model.
  353. Returns:
  354. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  355. """
  356. if already_has_special_tokens:
  357. return super().get_special_tokens_mask(
  358. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  359. )
  360. # no bos used in fairseq
  361. if token_ids_1 is not None:
  362. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  363. return ([0] * len(token_ids_0)) + [1]
  364. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  365. if not os.path.isdir(save_directory):
  366. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  367. return
  368. src_vocab_file = os.path.join(
  369. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["src_vocab_file"]
  370. )
  371. tgt_vocab_file = os.path.join(
  372. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["tgt_vocab_file"]
  373. )
  374. merges_file = os.path.join(
  375. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  376. )
  377. with open(src_vocab_file, "w", encoding="utf-8") as f:
  378. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  379. with open(tgt_vocab_file, "w", encoding="utf-8") as f:
  380. tgt_vocab = {v: k for k, v in self.decoder.items()}
  381. f.write(json.dumps(tgt_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  382. index = 0
  383. with open(merges_file, "w", encoding="utf-8") as writer:
  384. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  385. if index != token_index:
  386. logger.warning(
  387. f"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
  388. " Please check that the tokenizer is not corrupted!"
  389. )
  390. index = token_index
  391. writer.write(" ".join(bpe_tokens) + "\n")
  392. index += 1
  393. return src_vocab_file, tgt_vocab_file, merges_file
  394. def __getstate__(self):
  395. state = self.__dict__.copy()
  396. state["sm"] = None
  397. return state
  398. def __setstate__(self, d):
  399. self.__dict__ = d
  400. try:
  401. import sacremoses
  402. except ImportError:
  403. raise ImportError(
  404. "You need to install sacremoses to use XLMTokenizer. "
  405. "See https://pypi.org/project/sacremoses/ for installation."
  406. )
  407. self.sm = sacremoses
  408. __all__ = ["FSMTTokenizer"]