tokenization_camembert.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # coding=utf-8
  2. # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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. """Tokenization classes for Camembert model."""
  16. import os
  17. from shutil import copyfile
  18. from typing import Any, Optional
  19. import sentencepiece as spm
  20. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  21. from ...utils import logging
  22. from ...utils.import_utils import requires
  23. logger = logging.get_logger(__name__)
  24. VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
  25. SPIECE_UNDERLINE = "▁"
  26. @requires(backends=("sentencepiece",))
  27. class CamembertTokenizer(PreTrainedTokenizer):
  28. """
  29. Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Construct a CamemBERT tokenizer. Based on
  30. [SentencePiece](https://github.com/google/sentencepiece).
  31. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  32. this superclass for more information regarding those methods.
  33. Args:
  34. vocab_file (`str`):
  35. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  36. contains the vocabulary necessary to instantiate a tokenizer.
  37. bos_token (`str`, *optional*, defaults to `"<s>"`):
  38. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  39. <Tip>
  40. When building a sequence using special tokens, this is not the token that is used for the beginning of
  41. sequence. The token used is the `cls_token`.
  42. </Tip>
  43. eos_token (`str`, *optional*, defaults to `"</s>"`):
  44. The end of sequence token.
  45. <Tip>
  46. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  47. The token used is the `sep_token`.
  48. </Tip>
  49. sep_token (`str`, *optional*, defaults to `"</s>"`):
  50. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  51. sequence classification or for a text and a question for question answering. It is also used as the last
  52. token of a sequence built with special tokens.
  53. cls_token (`str`, *optional*, defaults to `"<s>"`):
  54. The classifier token which is used when doing sequence classification (classification of the whole sequence
  55. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  56. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  57. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  58. token instead.
  59. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  60. The token used for padding, for example when batching sequences of different lengths.
  61. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  62. The token used for masking values. This is the token used when training this model with masked language
  63. modeling. This is the token which the model will try to predict.
  64. additional_special_tokens (`list[str]`, *optional*, defaults to `['<s>NOTUSED', '</s>NOTUSED', '<unk>NOTUSED']`):
  65. Additional special tokens used by the tokenizer.
  66. sp_model_kwargs (`dict`, *optional*):
  67. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  68. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  69. to set:
  70. - `enable_sampling`: Enable subword regularization.
  71. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  72. - `nbest_size = {0,1}`: No sampling is performed.
  73. - `nbest_size > 1`: samples from the nbest_size results.
  74. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  75. using forward-filtering-and-backward-sampling algorithm.
  76. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  77. BPE-dropout.
  78. Attributes:
  79. sp_model (`SentencePieceProcessor`):
  80. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  81. """
  82. vocab_files_names = VOCAB_FILES_NAMES
  83. model_input_names = ["input_ids", "attention_mask"]
  84. def __init__(
  85. self,
  86. vocab_file,
  87. bos_token="<s>",
  88. eos_token="</s>",
  89. sep_token="</s>",
  90. cls_token="<s>",
  91. unk_token="<unk>",
  92. pad_token="<pad>",
  93. mask_token="<mask>",
  94. additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"],
  95. sp_model_kwargs: Optional[dict[str, Any]] = None,
  96. **kwargs,
  97. ) -> None:
  98. # Mask token behave like a normal word, i.e. include the space before it
  99. mask_token = (
  100. AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False, special=True)
  101. if isinstance(mask_token, str)
  102. else mask_token
  103. )
  104. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  105. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  106. self.sp_model.Load(str(vocab_file))
  107. self.vocab_file = vocab_file
  108. # HACK: These tokens were added by the author for an obscure reason as they were already part of the
  109. # sentencepiece vocabulary (this is the case for <s> and </s> and <unk>).
  110. # In this case it is recommended to properly set the tokens by hand.
  111. self._added_tokens_decoder = {
  112. 0: AddedToken("<s>NOTUSED", special=True),
  113. 1: AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token,
  114. 2: AddedToken("</s>NOTUSED", special=True),
  115. 3: AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token,
  116. 4: AddedToken("<unk>NOTUSED", special=True),
  117. }
  118. self.fairseq_offset = 4 # 3 tokens are newly added, but the offset starts from 4
  119. # legacy: camemebert is a particular case were we have to make sure `"<unk>NOTUSED"` is here
  120. if "added_tokens_decoder" in kwargs:
  121. # this is the only class that requires this unfortunately.....
  122. # the reason is that the fast version has a whole.
  123. kwargs["added_tokens_decoder"].update(self._added_tokens_decoder)
  124. super().__init__(
  125. bos_token=bos_token,
  126. eos_token=eos_token,
  127. unk_token=unk_token,
  128. sep_token=sep_token,
  129. cls_token=cls_token,
  130. pad_token=pad_token,
  131. mask_token=mask_token,
  132. additional_special_tokens=additional_special_tokens,
  133. sp_model_kwargs=self.sp_model_kwargs,
  134. **kwargs,
  135. )
  136. @property
  137. def vocab_size(self):
  138. # The length of the vocabulary without added tokens is len(self.sp_model) but the added tokens are added at the beginning.
  139. return len(self.sp_model)
  140. def get_vocab(self):
  141. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.fairseq_offset)}
  142. vocab.update(self.added_tokens_encoder)
  143. return vocab
  144. def _tokenize(self, text: str) -> list[str]:
  145. return self.sp_model.encode(text, out_type=str)
  146. def _convert_token_to_id(self, token):
  147. """Converts a token (str) in an id using the vocab."""
  148. # specific to camembert, both 3 and 4 point to the unk token.
  149. if self.sp_model.PieceToId(token) == 0:
  150. # Convert sentence piece unk token to fairseq unk token index
  151. return self.unk_token_id
  152. return self.fairseq_offset + self.sp_model.PieceToId(token)
  153. def _convert_id_to_token(self, index):
  154. """Converts an index (integer) in a token (str) using the vocab."""
  155. return self.sp_model.IdToPiece(index - self.fairseq_offset)
  156. def convert_tokens_to_string(self, tokens):
  157. """Converts a sequence of tokens (string) in a single string."""
  158. # TODO decode outputs do not match between fast and slow
  159. current_sub_tokens = []
  160. out_string = ""
  161. prev_is_special = False
  162. for token in tokens:
  163. # make sure that special tokens are not decoded using sentencepiece model
  164. if token in self.all_special_tokens:
  165. if not prev_is_special:
  166. out_string += " "
  167. out_string += self.sp_model.decode(current_sub_tokens) + token
  168. prev_is_special = True
  169. current_sub_tokens = []
  170. else:
  171. current_sub_tokens.append(token)
  172. prev_is_special = False
  173. out_string += self.sp_model.decode(current_sub_tokens)
  174. return out_string.strip()
  175. def __getstate__(self):
  176. state = self.__dict__.copy()
  177. state["sp_model"] = None
  178. return state
  179. def __setstate__(self, d):
  180. self.__dict__ = d
  181. # for backward compatibility
  182. if not hasattr(self, "sp_model_kwargs"):
  183. self.sp_model_kwargs = {}
  184. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  185. self.sp_model.Load(self.vocab_file)
  186. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  187. if not os.path.isdir(save_directory):
  188. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  189. return
  190. out_vocab_file = os.path.join(
  191. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  192. )
  193. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  194. copyfile(self.vocab_file, out_vocab_file)
  195. elif not os.path.isfile(self.vocab_file):
  196. with open(out_vocab_file, "wb") as fi:
  197. content_spiece_model = self.sp_model.serialized_model_proto()
  198. fi.write(content_spiece_model)
  199. return (out_vocab_file,)
  200. def build_inputs_with_special_tokens(
  201. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  202. ) -> list[int]:
  203. """
  204. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  205. adding special tokens. An CamemBERT sequence has the following format:
  206. - single sequence: `<s> X </s>`
  207. - pair of sequences: `<s> A </s></s> B </s>`
  208. Args:
  209. token_ids_0 (`list[int]`):
  210. List of IDs to which the special tokens will be added.
  211. token_ids_1 (`list[int]`, *optional*):
  212. Optional second list of IDs for sequence pairs.
  213. Returns:
  214. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  215. """
  216. if token_ids_1 is None:
  217. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  218. cls = [self.cls_token_id]
  219. sep = [self.sep_token_id]
  220. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  221. def get_special_tokens_mask(
  222. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  223. ) -> list[int]:
  224. """
  225. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  226. special tokens using the tokenizer `prepare_for_model` method.
  227. Args:
  228. token_ids_0 (`list[int]`):
  229. List of IDs.
  230. token_ids_1 (`list[int]`, *optional*):
  231. Optional second list of IDs for sequence pairs.
  232. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  233. Whether or not the token list is already formatted with special tokens for the model.
  234. Returns:
  235. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  236. """
  237. if already_has_special_tokens:
  238. return super().get_special_tokens_mask(
  239. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  240. )
  241. if token_ids_1 is None:
  242. return [1] + ([0] * len(token_ids_0)) + [1]
  243. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  244. def create_token_type_ids_from_sequences(
  245. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  246. ) -> list[int]:
  247. """
  248. Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
  249. RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
  250. Args:
  251. token_ids_0 (`list[int]`):
  252. List of IDs.
  253. token_ids_1 (`list[int]`, *optional*):
  254. Optional second list of IDs for sequence pairs.
  255. Returns:
  256. `list[int]`: List of zeros.
  257. """
  258. sep = [self.sep_token_id]
  259. cls = [self.cls_token_id]
  260. if token_ids_1 is None:
  261. return len(cls + token_ids_0 + sep) * [0]
  262. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  263. __all__ = ["CamembertTokenizer"]