tokenization_barthez.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # coding=utf-8
  2. # Copyright 2020 Ecole Polytechnique 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 the BARThez model."""
  16. import os
  17. from shutil import copyfile
  18. from typing import Any, Dict, List, Optional, Tuple
  19. import sentencepiece as spm
  20. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
  24. SPIECE_UNDERLINE = "▁"
  25. # TODO this class is useless. This is the most standard sentencpiece model. Let's find which one is closest and nuke this.
  26. class BarthezTokenizer(PreTrainedTokenizer):
  27. """
  28. Adapted from [`CamembertTokenizer`] and [`BartTokenizer`]. Construct a BARThez tokenizer. Based on
  29. [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. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  35. contains the vocabulary necessary to instantiate a tokenizer.
  36. bos_token (`str`, *optional*, defaults to `"<s>"`):
  37. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  38. <Tip>
  39. When building a sequence using special tokens, this is not the token that is used for the beginning of
  40. sequence. The token used is the `cls_token`.
  41. </Tip>
  42. eos_token (`str`, *optional*, defaults to `"</s>"`):
  43. The end of sequence token.
  44. <Tip>
  45. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  46. The token used is the `sep_token`.
  47. </Tip>
  48. sep_token (`str`, *optional*, defaults to `"</s>"`):
  49. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  50. sequence classification or for a text and a question for question answering. It is also used as the last
  51. token of a sequence built with special tokens.
  52. cls_token (`str`, *optional*, defaults to `"<s>"`):
  53. The classifier token which is used when doing sequence classification (classification of the whole sequence
  54. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  55. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  56. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  57. token instead.
  58. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  59. The token used for padding, for example when batching sequences of different lengths.
  60. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  61. The token used for masking values. This is the token used when training this model with masked language
  62. modeling. This is the token which the model will try to predict.
  63. sp_model_kwargs (`dict`, *optional*):
  64. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  65. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  66. to set:
  67. - `enable_sampling`: Enable subword regularization.
  68. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  69. - `nbest_size = {0,1}`: No sampling is performed.
  70. - `nbest_size > 1`: samples from the nbest_size results.
  71. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  72. using forward-filtering-and-backward-sampling algorithm.
  73. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  74. BPE-dropout.
  75. Attributes:
  76. sp_model (`SentencePieceProcessor`):
  77. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  78. """
  79. vocab_files_names = VOCAB_FILES_NAMES
  80. model_input_names = ["input_ids", "attention_mask"]
  81. def __init__(
  82. self,
  83. vocab_file,
  84. bos_token="<s>",
  85. eos_token="</s>",
  86. sep_token="</s>",
  87. cls_token="<s>",
  88. unk_token="<unk>",
  89. pad_token="<pad>",
  90. mask_token="<mask>",
  91. sp_model_kwargs: Optional[Dict[str, Any]] = None,
  92. **kwargs,
  93. ) -> None:
  94. # Mask token behave like a normal word, i.e. include the space before it. Will have normalized=False by default this way
  95. mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
  96. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  97. self.vocab_file = vocab_file
  98. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  99. self.sp_model.Load(str(vocab_file))
  100. super().__init__(
  101. bos_token=bos_token,
  102. eos_token=eos_token,
  103. unk_token=unk_token,
  104. sep_token=sep_token,
  105. cls_token=cls_token,
  106. pad_token=pad_token,
  107. mask_token=mask_token,
  108. sp_model_kwargs=self.sp_model_kwargs,
  109. **kwargs,
  110. )
  111. def build_inputs_with_special_tokens(
  112. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  113. ) -> List[int]:
  114. """
  115. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  116. adding special tokens. A BARThez sequence has the following format:
  117. - single sequence: `<s> X </s>`
  118. - pair of sequences: `<s> A </s></s> B </s>`
  119. Args:
  120. token_ids_0 (`List[int]`):
  121. List of IDs to which the special tokens will be added.
  122. token_ids_1 (`List[int]`, *optional*):
  123. Optional second list of IDs for sequence pairs.
  124. Returns:
  125. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  126. """
  127. if token_ids_1 is None:
  128. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  129. cls = [self.cls_token_id]
  130. sep = [self.sep_token_id]
  131. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  132. def get_special_tokens_mask(
  133. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  134. ) -> List[int]:
  135. """
  136. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  137. special tokens using the tokenizer `prepare_for_model` method.
  138. Args:
  139. token_ids_0 (`List[int]`):
  140. List of IDs.
  141. token_ids_1 (`List[int]`, *optional*):
  142. Optional second list of IDs for sequence pairs.
  143. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  144. Whether or not the token list is already formatted with special tokens for the model.
  145. Returns:
  146. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  147. """
  148. if already_has_special_tokens:
  149. return super().get_special_tokens_mask(
  150. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  151. )
  152. if token_ids_1 is None:
  153. return [1] + ([0] * len(token_ids_0)) + [1]
  154. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  155. def create_token_type_ids_from_sequences(
  156. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  157. ) -> List[int]:
  158. """
  159. Create a mask from the two sequences passed to be used in a sequence-pair classification task.
  160. Args:
  161. token_ids_0 (`List[int]`):
  162. List of IDs.
  163. token_ids_1 (`List[int]`, *optional*):
  164. Optional second list of IDs for sequence pairs.
  165. Returns:
  166. `List[int]`: List of zeros.
  167. """
  168. sep = [self.sep_token_id]
  169. cls = [self.cls_token_id]
  170. if token_ids_1 is None:
  171. return len(cls + token_ids_0 + sep) * [0]
  172. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  173. @property
  174. def vocab_size(self):
  175. return len(self.sp_model)
  176. def get_vocab(self):
  177. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  178. vocab.update(self.added_tokens_encoder)
  179. return vocab
  180. def _tokenize(self, text: str) -> List[str]:
  181. return self.sp_model.encode(text, out_type=str)
  182. def _convert_token_to_id(self, token):
  183. """Converts a token (str) in an id using the vocab."""
  184. return self.sp_model.PieceToId(token)
  185. def _convert_id_to_token(self, index):
  186. """Converts an index (integer) in a token (str) using the vocab."""
  187. return self.sp_model.IdToPiece(index)
  188. # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
  189. def convert_tokens_to_string(self, tokens):
  190. """Converts a sequence of tokens (string) in a single string."""
  191. current_sub_tokens = []
  192. out_string = ""
  193. prev_is_special = False
  194. for token in tokens:
  195. # make sure that special tokens are not decoded using sentencepiece model
  196. if token in self.all_special_tokens:
  197. if not prev_is_special:
  198. out_string += " "
  199. out_string += self.sp_model.decode(current_sub_tokens) + token
  200. prev_is_special = True
  201. current_sub_tokens = []
  202. else:
  203. current_sub_tokens.append(token)
  204. prev_is_special = False
  205. out_string += self.sp_model.decode(current_sub_tokens)
  206. return out_string.strip()
  207. def __getstate__(self):
  208. state = self.__dict__.copy()
  209. state["sp_model"] = None
  210. return state
  211. def __setstate__(self, d):
  212. self.__dict__ = d
  213. # for backward compatibility
  214. if not hasattr(self, "sp_model_kwargs"):
  215. self.sp_model_kwargs = {}
  216. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  217. self.sp_model.Load(self.vocab_file)
  218. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  219. if not os.path.isdir(save_directory):
  220. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  221. return
  222. out_vocab_file = os.path.join(
  223. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  224. )
  225. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  226. copyfile(self.vocab_file, out_vocab_file)
  227. elif not os.path.isfile(self.vocab_file):
  228. with open(out_vocab_file, "wb") as fi:
  229. content_spiece_model = self.sp_model.serialized_model_proto()
  230. fi.write(content_spiece_model)
  231. return (out_vocab_file,)