tokenization_mbart50.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. # coding=utf-8
  2. # Copyright 2021 The Facebook AI Research Team Authors 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 os
  16. from shutil import copyfile
  17. from typing import Any, Optional
  18. import sentencepiece as spm
  19. from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
  20. from ...utils import logging
  21. from ...utils.import_utils import requires
  22. logger = logging.get_logger(__name__)
  23. SPIECE_UNDERLINE = "▁"
  24. VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
  25. FAIRSEQ_LANGUAGE_CODES = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] # fmt: skip
  26. @requires(backends=("sentencepiece",))
  27. class MBart50Tokenizer(PreTrainedTokenizer):
  28. """
  29. Construct a MBart50 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
  30. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  31. this superclass for more information regarding those methods.
  32. Args:
  33. vocab_file (`str`):
  34. Path to the vocabulary file.
  35. src_lang (`str`, *optional*):
  36. A string representing the source language.
  37. tgt_lang (`str`, *optional*):
  38. A string representing the target language.
  39. eos_token (`str`, *optional*, defaults to `"</s>"`):
  40. The end of sequence token.
  41. sep_token (`str`, *optional*, defaults to `"</s>"`):
  42. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  43. sequence classification or for a text and a question for question answering. It is also used as the last
  44. token of a sequence built with special tokens.
  45. cls_token (`str`, *optional*, defaults to `"<s>"`):
  46. The classifier token which is used when doing sequence classification (classification of the whole sequence
  47. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  48. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  49. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  50. token instead.
  51. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  52. The token used for padding, for example when batching sequences of different lengths.
  53. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  54. The token used for masking values. This is the token used when training this model with masked language
  55. modeling. This is the token which the model will try to predict.
  56. sp_model_kwargs (`dict`, *optional*):
  57. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  58. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  59. to set:
  60. - `enable_sampling`: Enable subword regularization.
  61. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  62. - `nbest_size = {0,1}`: No sampling is performed.
  63. - `nbest_size > 1`: samples from the nbest_size results.
  64. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  65. using forward-filtering-and-backward-sampling algorithm.
  66. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  67. BPE-dropout.
  68. Examples:
  69. ```python
  70. >>> from transformers import MBart50Tokenizer
  71. >>> tokenizer = MBart50Tokenizer.from_pretrained("facebook/mbart-large-50", src_lang="en_XX", tgt_lang="ro_RO")
  72. >>> src_text = " UN Chief Says There Is No Military Solution in Syria"
  73. >>> tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria"
  74. >>> model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt")
  75. >>> # model(**model_inputs) should work
  76. ```"""
  77. vocab_files_names = VOCAB_FILES_NAMES
  78. model_input_names = ["input_ids", "attention_mask"]
  79. prefix_tokens: list[int] = []
  80. suffix_tokens: list[int] = []
  81. def __init__(
  82. self,
  83. vocab_file,
  84. src_lang=None,
  85. tgt_lang=None,
  86. eos_token="</s>",
  87. sep_token="</s>",
  88. cls_token="<s>",
  89. unk_token="<unk>",
  90. pad_token="<pad>",
  91. mask_token="<mask>",
  92. sp_model_kwargs: Optional[dict[str, Any]] = None,
  93. **kwargs,
  94. ) -> None:
  95. # Mask token behave like a normal word, i.e. include the space before it
  96. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  97. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  98. kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) or []
  99. kwargs["additional_special_tokens"] += [
  100. code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
  101. ]
  102. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  103. self.sp_model.Load(str(vocab_file))
  104. self.vocab_file = vocab_file
  105. # Original fairseq vocab and spm vocab must be "aligned":
  106. # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  107. # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
  108. # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
  109. # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
  110. # Mimic fairseq token-to-id alignment for the first 4 token
  111. self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
  112. # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
  113. self.fairseq_offset = 1
  114. self.sp_model_size = len(self.sp_model)
  115. self.lang_code_to_id = {
  116. code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(FAIRSEQ_LANGUAGE_CODES)
  117. }
  118. self.id_to_lang_code = {v: k for k, v in self.lang_code_to_id.items()}
  119. self.fairseq_tokens_to_ids["<mask>"] = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset
  120. self.fairseq_tokens_to_ids.update(self.lang_code_to_id)
  121. self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
  122. super().__init__(
  123. src_lang=src_lang,
  124. tgt_lang=tgt_lang,
  125. eos_token=eos_token,
  126. unk_token=unk_token,
  127. sep_token=sep_token,
  128. cls_token=cls_token,
  129. pad_token=pad_token,
  130. mask_token=mask_token,
  131. sp_model_kwargs=self.sp_model_kwargs,
  132. **kwargs,
  133. )
  134. self._src_lang = src_lang if src_lang is not None else "en_XX"
  135. self.cur_lang_code_id = self.lang_code_to_id[self._src_lang]
  136. self.tgt_lang = tgt_lang
  137. self.set_src_lang_special_tokens(self._src_lang)
  138. @property
  139. def vocab_size(self) -> int:
  140. return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1 # Plus 1 for the mask token
  141. @property
  142. def src_lang(self) -> str:
  143. return self._src_lang
  144. @src_lang.setter
  145. def src_lang(self, new_src_lang: str) -> None:
  146. self._src_lang = new_src_lang
  147. self.set_src_lang_special_tokens(self._src_lang)
  148. def __getstate__(self) -> dict:
  149. state = self.__dict__.copy()
  150. state["sp_model"] = None
  151. return state
  152. def __setstate__(self, d: dict) -> None:
  153. self.__dict__ = d
  154. # for backward compatibility
  155. if not hasattr(self, "sp_model_kwargs"):
  156. self.sp_model_kwargs = {}
  157. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  158. self.sp_model.Load(self.vocab_file)
  159. def get_vocab(self) -> dict:
  160. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  161. vocab.update(self.added_tokens_encoder)
  162. return vocab
  163. def _tokenize(self, text: str) -> list[str]:
  164. return self.sp_model.encode(text, out_type=str)
  165. def _convert_token_to_id(self, token: str) -> int:
  166. """Converts a token (str) in an id using the vocab."""
  167. if token in self.fairseq_tokens_to_ids:
  168. return self.fairseq_tokens_to_ids[token]
  169. spm_id = self.sp_model.PieceToId(token)
  170. # Need to return unknown token if the SP model returned 0
  171. return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
  172. def _convert_id_to_token(self, index: int) -> str:
  173. """Converts an index (integer) in a token (str) using the vocab."""
  174. if index in self.fairseq_ids_to_tokens:
  175. return self.fairseq_ids_to_tokens[index]
  176. return self.sp_model.IdToPiece(index - self.fairseq_offset)
  177. # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
  178. def convert_tokens_to_string(self, tokens):
  179. """Converts a sequence of tokens (string) in a single string."""
  180. current_sub_tokens = []
  181. out_string = ""
  182. prev_is_special = False
  183. for token in tokens:
  184. # make sure that special tokens are not decoded using sentencepiece model
  185. if token in self.all_special_tokens:
  186. if not prev_is_special:
  187. out_string += " "
  188. out_string += self.sp_model.decode(current_sub_tokens) + token
  189. prev_is_special = True
  190. current_sub_tokens = []
  191. else:
  192. current_sub_tokens.append(token)
  193. prev_is_special = False
  194. out_string += self.sp_model.decode(current_sub_tokens)
  195. return out_string.strip()
  196. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  197. if not os.path.isdir(save_directory):
  198. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  199. return
  200. out_vocab_file = os.path.join(
  201. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  202. )
  203. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  204. copyfile(self.vocab_file, out_vocab_file)
  205. elif not os.path.isfile(self.vocab_file):
  206. with open(out_vocab_file, "wb") as fi:
  207. content_spiece_model = self.sp_model.serialized_model_proto()
  208. fi.write(content_spiece_model)
  209. return (out_vocab_file,)
  210. def get_special_tokens_mask(
  211. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  212. ) -> list[int]:
  213. """
  214. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  215. special tokens using the tokenizer `prepare_for_model` method.
  216. Args:
  217. token_ids_0 (`list[int]`):
  218. List of IDs.
  219. token_ids_1 (`list[int]`, *optional*):
  220. Optional second list of IDs for sequence pairs.
  221. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  222. Whether or not the token list is already formatted with special tokens for the model.
  223. Returns:
  224. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  225. """
  226. if already_has_special_tokens:
  227. return super().get_special_tokens_mask(
  228. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  229. )
  230. prefix_ones = [1] * len(self.prefix_tokens)
  231. suffix_ones = [1] * len(self.suffix_tokens)
  232. if token_ids_1 is None:
  233. return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones
  234. return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
  235. def build_inputs_with_special_tokens(
  236. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  237. ) -> list[int]:
  238. """
  239. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  240. adding special tokens. An MBART-50 sequence has the following format, where `X` represents the sequence:
  241. - `input_ids` (for encoder) `[src_lang_code] X [eos]`
  242. - `labels`: (for decoder) `[tgt_lang_code] X [eos]`
  243. BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
  244. separator.
  245. Args:
  246. token_ids_0 (`list[int]`):
  247. List of IDs to which the special tokens will be added.
  248. token_ids_1 (`list[int]`, *optional*):
  249. Optional second list of IDs for sequence pairs.
  250. Returns:
  251. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  252. """
  253. if token_ids_1 is None:
  254. return self.prefix_tokens + token_ids_0 + self.suffix_tokens
  255. # We don't expect to process pairs, but leave the pair logic for API consistency
  256. return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens
  257. def _build_translation_inputs(
  258. self, raw_inputs, return_tensors: str, src_lang: Optional[str], tgt_lang: Optional[str], **extra_kwargs
  259. ):
  260. """Used by translation pipeline, to prepare inputs for the generate function"""
  261. if src_lang is None or tgt_lang is None:
  262. raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model")
  263. self.src_lang = src_lang
  264. inputs = self(raw_inputs, add_special_tokens=True, return_tensors=return_tensors, **extra_kwargs)
  265. tgt_lang_id = self.convert_tokens_to_ids(tgt_lang)
  266. inputs["forced_bos_token_id"] = tgt_lang_id
  267. return inputs
  268. def prepare_seq2seq_batch(
  269. self,
  270. src_texts: list[str],
  271. src_lang: str = "en_XX",
  272. tgt_texts: Optional[list[str]] = None,
  273. tgt_lang: str = "ro_RO",
  274. **kwargs,
  275. ) -> BatchEncoding:
  276. self.src_lang = src_lang
  277. self.tgt_lang = tgt_lang
  278. return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs)
  279. def _switch_to_input_mode(self):
  280. return self.set_src_lang_special_tokens(self.src_lang)
  281. def _switch_to_target_mode(self):
  282. return self.set_tgt_lang_special_tokens(self.tgt_lang)
  283. def set_src_lang_special_tokens(self, src_lang: str) -> None:
  284. """Reset the special tokens to the source lang setting. prefix=[src_lang_code] and suffix=[eos]."""
  285. self.cur_lang_code_id = self.lang_code_to_id[src_lang]
  286. self.prefix_tokens = [self.cur_lang_code_id]
  287. self.suffix_tokens = [self.eos_token_id]
  288. def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None:
  289. """Reset the special tokens to the target language setting. prefix=[tgt_lang_code] and suffix=[eos]."""
  290. self.cur_lang_code_id = self.lang_code_to_id[tgt_lang]
  291. self.prefix_tokens = [self.cur_lang_code_id]
  292. self.suffix_tokens = [self.eos_token_id]
  293. __all__ = ["MBart50Tokenizer"]