tokenization_herbert.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. # coding=utf-8
  2. # Copyright 2020 The Google AI Language Team Authors, Allegro.pl, Facebook Inc. 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 json
  16. import os
  17. import re
  18. import unicodedata
  19. from typing import List, Optional, Tuple
  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 = {
  24. "vocab_file": "vocab.json",
  25. "merges_file": "merges.txt",
  26. }
  27. # Copied from transformers.models.xlm.tokenization_xlm.get_pairs
  28. def get_pairs(word):
  29. """
  30. Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
  31. strings)
  32. """
  33. pairs = set()
  34. prev_char = word[0]
  35. for char in word[1:]:
  36. pairs.add((prev_char, char))
  37. prev_char = char
  38. return pairs
  39. # Copied from transformers.models.xlm.tokenization_xlm.replace_unicode_punct
  40. def replace_unicode_punct(text):
  41. """
  42. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
  43. """
  44. text = text.replace(",", ",")
  45. text = re.sub(r"。\s*", ". ", text)
  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("(", "(")
  57. text = text.replace(";", ";")
  58. text = text.replace("1", "1")
  59. text = text.replace("」", '"')
  60. text = text.replace("「", '"')
  61. text = text.replace("0", "0")
  62. text = text.replace("3", "3")
  63. text = text.replace("2", "2")
  64. text = text.replace("5", "5")
  65. text = text.replace("6", "6")
  66. text = text.replace("9", "9")
  67. text = text.replace("7", "7")
  68. text = text.replace("8", "8")
  69. text = text.replace("4", "4")
  70. text = re.sub(r".\s*", ". ", text)
  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. text = text.replace("】", "]")
  79. text = text.replace("%", "%")
  80. return text
  81. # Copied from transformers.models.xlm.tokenization_xlm.remove_non_printing_char
  82. def remove_non_printing_char(text):
  83. """
  84. Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
  85. """
  86. output = []
  87. for char in text:
  88. cat = unicodedata.category(char)
  89. if cat.startswith("C"):
  90. continue
  91. output.append(char)
  92. return "".join(output)
  93. # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
  94. def whitespace_tokenize(text):
  95. """Runs basic whitespace cleaning and splitting on a piece of text."""
  96. text = text.strip()
  97. if not text:
  98. return []
  99. tokens = text.split()
  100. return tokens
  101. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  102. class BasicTokenizer:
  103. """
  104. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  105. Args:
  106. do_lower_case (`bool`, *optional*, defaults to `True`):
  107. Whether or not to lowercase the input when tokenizing.
  108. never_split (`Iterable`, *optional*):
  109. Collection of tokens which will never be split during tokenization. Only has an effect when
  110. `do_basic_tokenize=True`
  111. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  112. Whether or not to tokenize Chinese characters.
  113. This should likely be deactivated for Japanese (see this
  114. [issue](https://github.com/huggingface/transformers/issues/328)).
  115. strip_accents (`bool`, *optional*):
  116. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  117. value for `lowercase` (as in the original BERT).
  118. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  119. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  120. the full context of the words, such as contractions.
  121. """
  122. def __init__(
  123. self,
  124. do_lower_case=True,
  125. never_split=None,
  126. tokenize_chinese_chars=True,
  127. strip_accents=None,
  128. do_split_on_punc=True,
  129. ):
  130. if never_split is None:
  131. never_split = []
  132. self.do_lower_case = do_lower_case
  133. self.never_split = set(never_split)
  134. self.tokenize_chinese_chars = tokenize_chinese_chars
  135. self.strip_accents = strip_accents
  136. self.do_split_on_punc = do_split_on_punc
  137. def tokenize(self, text, never_split=None):
  138. """
  139. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  140. Args:
  141. never_split (`List[str]`, *optional*)
  142. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  143. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  144. """
  145. # union() returns a new set by concatenating the two sets.
  146. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
  147. text = self._clean_text(text)
  148. # This was added on November 1st, 2018 for the multilingual and Chinese
  149. # models. This is also applied to the English models now, but it doesn't
  150. # matter since the English models were not trained on any Chinese data
  151. # and generally don't have any Chinese data in them (there are Chinese
  152. # characters in the vocabulary because Wikipedia does have some Chinese
  153. # words in the English Wikipedia.).
  154. if self.tokenize_chinese_chars:
  155. text = self._tokenize_chinese_chars(text)
  156. # prevents treating the same character with different unicode codepoints as different characters
  157. unicode_normalized_text = unicodedata.normalize("NFC", text)
  158. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  159. split_tokens = []
  160. for token in orig_tokens:
  161. if token not in never_split:
  162. if self.do_lower_case:
  163. token = token.lower()
  164. if self.strip_accents is not False:
  165. token = self._run_strip_accents(token)
  166. elif self.strip_accents:
  167. token = self._run_strip_accents(token)
  168. split_tokens.extend(self._run_split_on_punc(token, never_split))
  169. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  170. return output_tokens
  171. def _run_strip_accents(self, text):
  172. """Strips accents from a piece of text."""
  173. text = unicodedata.normalize("NFD", text)
  174. output = []
  175. for char in text:
  176. cat = unicodedata.category(char)
  177. if cat == "Mn":
  178. continue
  179. output.append(char)
  180. return "".join(output)
  181. def _run_split_on_punc(self, text, never_split=None):
  182. """Splits punctuation on a piece of text."""
  183. if not self.do_split_on_punc or (never_split is not None and text in never_split):
  184. return [text]
  185. chars = list(text)
  186. i = 0
  187. start_new_word = True
  188. output = []
  189. while i < len(chars):
  190. char = chars[i]
  191. if _is_punctuation(char):
  192. output.append([char])
  193. start_new_word = True
  194. else:
  195. if start_new_word:
  196. output.append([])
  197. start_new_word = False
  198. output[-1].append(char)
  199. i += 1
  200. return ["".join(x) for x in output]
  201. def _tokenize_chinese_chars(self, text):
  202. """Adds whitespace around any CJK character."""
  203. output = []
  204. for char in text:
  205. cp = ord(char)
  206. if self._is_chinese_char(cp):
  207. output.append(" ")
  208. output.append(char)
  209. output.append(" ")
  210. else:
  211. output.append(char)
  212. return "".join(output)
  213. def _is_chinese_char(self, cp):
  214. """Checks whether CP is the codepoint of a CJK character."""
  215. # This defines a "chinese character" as anything in the CJK Unicode block:
  216. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  217. #
  218. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  219. # despite its name. The modern Korean Hangul alphabet is a different block,
  220. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  221. # space-separated words, so they are not treated specially and handled
  222. # like the all of the other languages.
  223. if (
  224. (cp >= 0x4E00 and cp <= 0x9FFF)
  225. or (cp >= 0x3400 and cp <= 0x4DBF) #
  226. or (cp >= 0x20000 and cp <= 0x2A6DF) #
  227. or (cp >= 0x2A700 and cp <= 0x2B73F) #
  228. or (cp >= 0x2B740 and cp <= 0x2B81F) #
  229. or (cp >= 0x2B820 and cp <= 0x2CEAF) #
  230. or (cp >= 0xF900 and cp <= 0xFAFF)
  231. or (cp >= 0x2F800 and cp <= 0x2FA1F) #
  232. ): #
  233. return True
  234. return False
  235. def _clean_text(self, text):
  236. """Performs invalid character removal and whitespace cleanup on text."""
  237. output = []
  238. for char in text:
  239. cp = ord(char)
  240. if cp == 0 or cp == 0xFFFD or _is_control(char):
  241. continue
  242. if _is_whitespace(char):
  243. output.append(" ")
  244. else:
  245. output.append(char)
  246. return "".join(output)
  247. class HerbertTokenizer(PreTrainedTokenizer):
  248. """
  249. Construct a BPE tokenizer for HerBERT.
  250. Peculiarities:
  251. - uses BERT's pre-tokenizer: BaseTokenizer splits tokens on spaces, and also on punctuation. Each occurrence of a
  252. punctuation character will be treated separately.
  253. - Such pretokenized input is BPE subtokenized
  254. This tokenizer inherits from [`XLMTokenizer`] which contains most of the methods. Users should refer to the
  255. superclass for more information regarding methods.
  256. """
  257. vocab_files_names = VOCAB_FILES_NAMES
  258. def __init__(
  259. self,
  260. vocab_file,
  261. merges_file,
  262. tokenizer_file=None,
  263. cls_token="<s>",
  264. unk_token="<unk>",
  265. pad_token="<pad>",
  266. mask_token="<mask>",
  267. sep_token="</s>",
  268. bos_token="<s>",
  269. do_lowercase_and_remove_accent=False,
  270. additional_special_tokens=[
  271. "<special0>",
  272. "<special1>",
  273. "<special2>",
  274. "<special3>",
  275. "<special4>",
  276. "<special5>",
  277. "<special6>",
  278. "<special7>",
  279. "<special8>",
  280. "<special9>",
  281. ],
  282. lang2id=None,
  283. id2lang=None,
  284. **kwargs,
  285. ):
  286. try:
  287. import sacremoses
  288. except ImportError:
  289. raise ImportError(
  290. "You need to install sacremoses to use HerbertTokenizer. "
  291. "See https://pypi.org/project/sacremoses/ for installation."
  292. )
  293. self.sm = sacremoses
  294. # cache of sm.MosesPunctNormalizer instance
  295. self.cache_moses_punct_normalizer = {}
  296. # cache of sm.MosesTokenizer instance
  297. self.cache_moses_tokenizer = {}
  298. self.lang_with_custom_tokenizer = {"zh", "th", "ja"}
  299. # True for current supported model (v1.2.0), False for XLM-17 & 100
  300. self.do_lowercase_and_remove_accent = do_lowercase_and_remove_accent
  301. self.lang2id = lang2id
  302. self.id2lang = id2lang
  303. if lang2id is not None and id2lang is not None:
  304. assert len(lang2id) == len(id2lang)
  305. self.ja_word_tokenizer = None
  306. self.zh_word_tokenizer = None
  307. with open(vocab_file, encoding="utf-8") as vocab_handle:
  308. self.encoder = json.load(vocab_handle)
  309. self.decoder = {v: k for k, v in self.encoder.items()}
  310. with open(merges_file, encoding="utf-8") as merges_handle:
  311. merges = merges_handle.read().split("\n")[:-1]
  312. merges = [tuple(merge.split()[:2]) for merge in merges]
  313. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  314. self.cache = {}
  315. super().__init__(
  316. unk_token=unk_token,
  317. bos_token=bos_token,
  318. sep_token=sep_token,
  319. pad_token=pad_token,
  320. cls_token=cls_token,
  321. mask_token=mask_token,
  322. additional_special_tokens=additional_special_tokens,
  323. lang2id=lang2id,
  324. id2lang=id2lang,
  325. do_lowercase_and_remove_accent=do_lowercase_and_remove_accent,
  326. tokenizer_file=None,
  327. **kwargs,
  328. )
  329. self.bert_pre_tokenizer = BasicTokenizer(
  330. do_lower_case=False,
  331. never_split=self.all_special_tokens,
  332. tokenize_chinese_chars=False,
  333. strip_accents=False,
  334. )
  335. @property
  336. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.do_lower_case
  337. def do_lower_case(self):
  338. return self.do_lowercase_and_remove_accent
  339. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_punct_norm
  340. def moses_punct_norm(self, text, lang):
  341. if lang not in self.cache_moses_punct_normalizer:
  342. punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
  343. self.cache_moses_punct_normalizer[lang] = punct_normalizer
  344. else:
  345. punct_normalizer = self.cache_moses_punct_normalizer[lang]
  346. return punct_normalizer.normalize(text)
  347. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_tokenize
  348. def moses_tokenize(self, text, lang):
  349. if lang not in self.cache_moses_tokenizer:
  350. moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
  351. self.cache_moses_tokenizer[lang] = moses_tokenizer
  352. else:
  353. moses_tokenizer = self.cache_moses_tokenizer[lang]
  354. return moses_tokenizer.tokenize(text, return_str=False, escape=False)
  355. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_pipeline
  356. def moses_pipeline(self, text, lang):
  357. text = replace_unicode_punct(text)
  358. text = self.moses_punct_norm(text, lang)
  359. text = remove_non_printing_char(text)
  360. return text
  361. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.ja_tokenize
  362. def ja_tokenize(self, text):
  363. if self.ja_word_tokenizer is None:
  364. try:
  365. import Mykytea
  366. self.ja_word_tokenizer = Mykytea.Mykytea(
  367. f"-model {os.path.expanduser('~')}/local/share/kytea/model.bin"
  368. )
  369. except (AttributeError, ImportError):
  370. logger.error(
  371. "Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper"
  372. " (https://github.com/chezou/Mykytea-python) with the following steps"
  373. )
  374. logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea")
  375. logger.error("2. autoreconf -i")
  376. logger.error("3. ./configure --prefix=$HOME/local")
  377. logger.error("4. make && make install")
  378. logger.error("5. pip install kytea")
  379. raise
  380. return list(self.ja_word_tokenizer.getWS(text))
  381. @property
  382. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.vocab_size
  383. def vocab_size(self):
  384. return len(self.encoder)
  385. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.get_vocab
  386. def get_vocab(self):
  387. return dict(self.encoder, **self.added_tokens_encoder)
  388. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.bpe
  389. def bpe(self, token):
  390. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  391. if token in self.cache:
  392. return self.cache[token]
  393. pairs = get_pairs(word)
  394. if not pairs:
  395. return token + "</w>"
  396. while True:
  397. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  398. if bigram not in self.bpe_ranks:
  399. break
  400. first, second = bigram
  401. new_word = []
  402. i = 0
  403. while i < len(word):
  404. try:
  405. j = word.index(first, i)
  406. except ValueError:
  407. new_word.extend(word[i:])
  408. break
  409. else:
  410. new_word.extend(word[i:j])
  411. i = j
  412. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  413. new_word.append(first + second)
  414. i += 2
  415. else:
  416. new_word.append(word[i])
  417. i += 1
  418. new_word = tuple(new_word)
  419. word = new_word
  420. if len(word) == 1:
  421. break
  422. else:
  423. pairs = get_pairs(word)
  424. word = " ".join(word)
  425. if word == "\n </w>":
  426. word = "\n</w>"
  427. self.cache[token] = word
  428. return word
  429. def _tokenize(self, text):
  430. pre_tokens = self.bert_pre_tokenizer.tokenize(text)
  431. split_tokens = []
  432. for token in pre_tokens:
  433. if token:
  434. split_tokens.extend(list(self.bpe(token).split(" ")))
  435. return split_tokens
  436. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer._convert_token_to_id
  437. def _convert_token_to_id(self, token):
  438. """Converts a token (str) in an id using the vocab."""
  439. return self.encoder.get(token, self.encoder.get(self.unk_token))
  440. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer._convert_id_to_token
  441. def _convert_id_to_token(self, index):
  442. """Converts an index (integer) in a token (str) using the vocab."""
  443. return self.decoder.get(index, self.unk_token)
  444. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.convert_tokens_to_string
  445. def convert_tokens_to_string(self, tokens):
  446. """Converts a sequence of tokens (string) in a single string."""
  447. out_string = "".join(tokens).replace("</w>", " ").strip()
  448. return out_string
  449. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.build_inputs_with_special_tokens
  450. def build_inputs_with_special_tokens(
  451. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  452. ) -> List[int]:
  453. """
  454. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  455. adding special tokens. An XLM sequence has the following format:
  456. - single sequence: `<s> X </s>`
  457. - pair of sequences: `<s> A </s> B </s>`
  458. Args:
  459. token_ids_0 (`List[int]`):
  460. List of IDs to which the special tokens will be added.
  461. token_ids_1 (`List[int]`, *optional*):
  462. Optional second list of IDs for sequence pairs.
  463. Returns:
  464. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  465. """
  466. bos = [self.bos_token_id]
  467. sep = [self.sep_token_id]
  468. if token_ids_1 is None:
  469. return bos + token_ids_0 + sep
  470. return bos + token_ids_0 + sep + token_ids_1 + sep
  471. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.get_special_tokens_mask
  472. def get_special_tokens_mask(
  473. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  474. ) -> List[int]:
  475. """
  476. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  477. special tokens using the tokenizer `prepare_for_model` method.
  478. Args:
  479. token_ids_0 (`List[int]`):
  480. List of IDs.
  481. token_ids_1 (`List[int]`, *optional*):
  482. Optional second list of IDs for sequence pairs.
  483. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  484. Whether or not the token list is already formatted with special tokens for the model.
  485. Returns:
  486. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  487. """
  488. if already_has_special_tokens:
  489. return super().get_special_tokens_mask(
  490. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  491. )
  492. if token_ids_1 is not None:
  493. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  494. return [1] + ([0] * len(token_ids_0)) + [1]
  495. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.create_token_type_ids_from_sequences
  496. def create_token_type_ids_from_sequences(
  497. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  498. ) -> List[int]:
  499. """
  500. Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLM sequence
  501. pair mask has the following format:
  502. ```
  503. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  504. | first sequence | second sequence |
  505. ```
  506. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  507. Args:
  508. token_ids_0 (`List[int]`):
  509. List of IDs.
  510. token_ids_1 (`List[int]`, *optional*):
  511. Optional second list of IDs for sequence pairs.
  512. Returns:
  513. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  514. """
  515. sep = [self.sep_token_id]
  516. cls = [self.cls_token_id]
  517. if token_ids_1 is None:
  518. return len(cls + token_ids_0 + sep) * [0]
  519. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  520. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.save_vocabulary
  521. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  522. if not os.path.isdir(save_directory):
  523. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  524. return
  525. vocab_file = os.path.join(
  526. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  527. )
  528. merge_file = os.path.join(
  529. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  530. )
  531. with open(vocab_file, "w", encoding="utf-8") as f:
  532. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  533. index = 0
  534. with open(merge_file, "w", encoding="utf-8") as writer:
  535. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  536. if index != token_index:
  537. logger.warning(
  538. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  539. " Please check that the tokenizer is not corrupted!"
  540. )
  541. index = token_index
  542. writer.write(" ".join(bpe_tokens) + "\n")
  543. index += 1
  544. return vocab_file, merge_file
  545. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.__getstate__
  546. def __getstate__(self):
  547. state = self.__dict__.copy()
  548. state["sm"] = None
  549. return state
  550. # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.__setstate__
  551. def __setstate__(self, d):
  552. self.__dict__ = d
  553. try:
  554. import sacremoses
  555. except ImportError:
  556. raise ImportError(
  557. "You need to install sacremoses to use XLMTokenizer. "
  558. "See https://pypi.org/project/sacremoses/ for installation."
  559. )
  560. self.sm = sacremoses