tokenization_fnet.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. # coding=utf-8
  2. # Copyright 2021 Google Research, Google AI, Google Brain 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 FNet model."""
  16. import os
  17. import unicodedata
  18. from shutil import copyfile
  19. from typing import Any, Optional
  20. import sentencepiece as spm
  21. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  22. from ...utils import logging
  23. from ...utils.import_utils import requires
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
  26. SPIECE_UNDERLINE = "▁"
  27. @requires(backends=("sentencepiece",))
  28. class FNetTokenizer(PreTrainedTokenizer):
  29. """
  30. Construct an FNet tokenizer. Adapted from [`AlbertTokenizer`]. Based on
  31. [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`]
  32. which contains most of the main methods. Users should refer to this superclass for more information regarding those
  33. methods.
  34. Args:
  35. vocab_file (`str`):
  36. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  37. contains the vocabulary necessary to instantiate a tokenizer.
  38. do_lower_case (`bool`, *optional*, defaults to `False`):
  39. Whether or not to lowercase the input when tokenizing.
  40. remove_space (`bool`, *optional*, defaults to `True`):
  41. Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
  42. keep_accents (`bool`, *optional*, defaults to `True`):
  43. Whether or not to keep accents when tokenizing.
  44. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  45. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  46. token instead.
  47. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  48. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  49. sequence classification or for a text and a question for question answering. It is also used as the last
  50. token of a sequence built with special tokens.
  51. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  52. The token used for padding, for example when batching sequences of different lengths.
  53. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  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. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  57. The token used for masking values. This is the token used when training this model with masked language
  58. modeling. This is the token which the model will try to predict.
  59. sp_model_kwargs (`dict`, *optional*):
  60. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  61. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  62. to set:
  63. - `enable_sampling`: Enable subword regularization.
  64. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  65. - `nbest_size = {0,1}`: No sampling is performed.
  66. - `nbest_size > 1`: samples from the nbest_size results.
  67. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  68. using forward-filtering-and-backward-sampling algorithm.
  69. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  70. BPE-dropout.
  71. Attributes:
  72. sp_model (`SentencePieceProcessor`):
  73. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  74. """
  75. vocab_files_names = VOCAB_FILES_NAMES
  76. model_input_names = ["input_ids", "token_type_ids"]
  77. def __init__(
  78. self,
  79. vocab_file,
  80. do_lower_case=False,
  81. remove_space=True,
  82. keep_accents=True,
  83. unk_token="<unk>",
  84. sep_token="[SEP]",
  85. pad_token="<pad>",
  86. cls_token="[CLS]",
  87. mask_token="[MASK]",
  88. sp_model_kwargs: Optional[dict[str, Any]] = None,
  89. **kwargs,
  90. ) -> None:
  91. # Mask token behave like a normal word, i.e. include the space before it and
  92. # is included in the raw text, there should be a match in a non-normalized sentence.
  93. mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
  94. cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
  95. sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
  96. mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token
  97. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  98. self.do_lower_case = do_lower_case
  99. self.remove_space = remove_space
  100. self.keep_accents = keep_accents
  101. self.vocab_file = vocab_file
  102. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  103. self.sp_model.Load(vocab_file)
  104. super().__init__(
  105. do_lower_case=do_lower_case,
  106. remove_space=remove_space,
  107. keep_accents=keep_accents,
  108. unk_token=unk_token,
  109. sep_token=sep_token,
  110. pad_token=pad_token,
  111. cls_token=cls_token,
  112. mask_token=mask_token,
  113. sp_model_kwargs=self.sp_model_kwargs,
  114. **kwargs,
  115. )
  116. @property
  117. def vocab_size(self):
  118. return len(self.sp_model)
  119. def get_vocab(self):
  120. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  121. vocab.update(self.added_tokens_encoder)
  122. return vocab
  123. def __getstate__(self):
  124. state = self.__dict__.copy()
  125. state["sp_model"] = None
  126. return state
  127. def __setstate__(self, d):
  128. self.__dict__ = d
  129. # for backward compatibility
  130. if not hasattr(self, "sp_model_kwargs"):
  131. self.sp_model_kwargs = {}
  132. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  133. self.sp_model.Load(self.vocab_file)
  134. def preprocess_text(self, inputs):
  135. if self.remove_space:
  136. outputs = " ".join(inputs.strip().split())
  137. else:
  138. outputs = inputs
  139. outputs = outputs.replace("``", '"').replace("''", '"')
  140. if not self.keep_accents:
  141. outputs = unicodedata.normalize("NFKD", outputs)
  142. outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
  143. if self.do_lower_case:
  144. outputs = outputs.lower()
  145. return outputs
  146. def _tokenize(self, text: str) -> list[str]:
  147. """Tokenize a string."""
  148. text = self.preprocess_text(text)
  149. pieces = self.sp_model.encode(text, out_type=str)
  150. new_pieces = []
  151. for piece in pieces:
  152. if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
  153. cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
  154. if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
  155. if len(cur_pieces[0]) == 1:
  156. cur_pieces = cur_pieces[1:]
  157. else:
  158. cur_pieces[0] = cur_pieces[0][1:]
  159. cur_pieces.append(piece[-1])
  160. new_pieces.extend(cur_pieces)
  161. else:
  162. new_pieces.append(piece)
  163. return new_pieces
  164. def _convert_token_to_id(self, token):
  165. """Converts a token (str) in an id using the vocab."""
  166. return self.sp_model.PieceToId(token)
  167. def _convert_id_to_token(self, index):
  168. """Converts an index (integer) in a token (str) using the vocab."""
  169. return self.sp_model.IdToPiece(index)
  170. # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
  171. def convert_tokens_to_string(self, tokens):
  172. """Converts a sequence of tokens (string) in a single string."""
  173. current_sub_tokens = []
  174. out_string = ""
  175. prev_is_special = False
  176. for token in tokens:
  177. # make sure that special tokens are not decoded using sentencepiece model
  178. if token in self.all_special_tokens:
  179. if not prev_is_special:
  180. out_string += " "
  181. out_string += self.sp_model.decode(current_sub_tokens) + token
  182. prev_is_special = True
  183. current_sub_tokens = []
  184. else:
  185. current_sub_tokens.append(token)
  186. prev_is_special = False
  187. out_string += self.sp_model.decode(current_sub_tokens)
  188. return out_string.strip()
  189. def _decode(
  190. self,
  191. token_ids: list[int],
  192. skip_special_tokens: bool = False,
  193. clean_up_tokenization_spaces: Optional[bool] = None,
  194. spaces_between_special_tokens: bool = False,
  195. **kwargs,
  196. ) -> str:
  197. text = super()._decode(
  198. token_ids=token_ids,
  199. skip_special_tokens=skip_special_tokens,
  200. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  201. spaces_between_special_tokens=spaces_between_special_tokens,
  202. **kwargs,
  203. )
  204. # Mimic the behavior of the Rust tokenizer:
  205. # No space after <unk>
  206. if not spaces_between_special_tokens:
  207. text = text.replace("<unk> ", "<unk>")
  208. return text
  209. def build_inputs_with_special_tokens(
  210. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  211. ) -> list[int]:
  212. """
  213. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  214. adding special tokens. An FNet sequence has the following format:
  215. - single sequence: `[CLS] X [SEP]`
  216. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  217. Args:
  218. token_ids_0 (`List[int]`):
  219. List of IDs to which the special tokens will be added.
  220. token_ids_1 (`List[int]`, *optional*):
  221. Optional second list of IDs for sequence pairs.
  222. Returns:
  223. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  224. """
  225. sep = [self.sep_token_id]
  226. cls = [self.cls_token_id]
  227. if token_ids_1 is None:
  228. return cls + token_ids_0 + sep
  229. return cls + token_ids_0 + sep + token_ids_1 + sep
  230. def get_special_tokens_mask(
  231. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  232. ) -> list[int]:
  233. """
  234. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  235. special tokens using the tokenizer `prepare_for_model` method.
  236. Args:
  237. token_ids_0 (`List[int]`):
  238. List of IDs.
  239. token_ids_1 (`List[int]`, *optional*):
  240. Optional second list of IDs for sequence pairs.
  241. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  242. Whether or not the token list is already formatted with special tokens for the model.
  243. Returns:
  244. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  245. """
  246. if already_has_special_tokens:
  247. return super().get_special_tokens_mask(
  248. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  249. )
  250. if token_ids_1 is not None:
  251. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  252. return [1] + ([0] * len(token_ids_0)) + [1]
  253. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  254. if not os.path.isdir(save_directory):
  255. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  256. return
  257. out_vocab_file = os.path.join(
  258. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  259. )
  260. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  261. copyfile(self.vocab_file, out_vocab_file)
  262. elif not os.path.isfile(self.vocab_file):
  263. with open(out_vocab_file, "wb") as fi:
  264. content_spiece_model = self.sp_model.serialized_model_proto()
  265. fi.write(content_spiece_model)
  266. return (out_vocab_file,)
  267. __all__ = ["FNetTokenizer"]