tokenization_rembert.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # coding=utf-8
  2. # Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
  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 RemBERT."""
  16. import os
  17. from shutil import copyfile
  18. from typing import 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.model"}
  25. @requires(backends=("sentencepiece",))
  26. class RemBertTokenizer(PreTrainedTokenizer):
  27. """
  28. Construct a RemBERT tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
  29. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  30. this superclass for more information regarding those methods.
  31. Args:
  32. vocab_file (`str`):
  33. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  34. contains the vocabulary necessary to instantiate a tokenizer.
  35. bos_token (`str`, *optional*, defaults to `"[CLS]"`):
  36. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  37. <Tip>
  38. When building a sequence using special tokens, this is not the token that is used for the beginning of
  39. sequence. The token used is the `cls_token`.
  40. </Tip>
  41. eos_token (`str`, *optional*, defaults to `"[SEP]"`):
  42. The end of sequence token.
  43. <Tip>
  44. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  45. The token used is the `sep_token`.
  46. </Tip>
  47. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  48. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  49. token instead.
  50. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  51. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  52. sequence classification or for a text and a question for question answering. It is also used as the last
  53. token of a sequence built with special tokens.
  54. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  55. The token used for padding, for example when batching sequences of different lengths.
  56. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  57. The classifier token which is used when doing sequence classification (classification of the whole sequence
  58. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  59. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  60. The token used for masking values. This is the token used when training this model with masked language
  61. modeling. This is the token which the model will try to predict.
  62. Attributes:
  63. sp_model (`SentencePieceProcessor`):
  64. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  65. """
  66. vocab_files_names = VOCAB_FILES_NAMES
  67. def __init__(
  68. self,
  69. vocab_file,
  70. do_lower_case=False,
  71. remove_space=True,
  72. keep_accents=True,
  73. bos_token="[CLS]",
  74. eos_token="[SEP]",
  75. unk_token="[UNK]",
  76. sep_token="[SEP]",
  77. pad_token="[PAD]",
  78. cls_token="[CLS]",
  79. mask_token="[MASK]",
  80. **kwargs,
  81. ):
  82. # Mask token behave like a normal word, i.e. include the space before it
  83. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  84. self.do_lower_case = do_lower_case
  85. self.remove_space = remove_space
  86. self.keep_accents = keep_accents
  87. self.vocab_file = vocab_file
  88. self.sp_model = spm.SentencePieceProcessor()
  89. self.sp_model.Load(vocab_file)
  90. super().__init__(
  91. do_lower_case=do_lower_case,
  92. remove_space=remove_space,
  93. keep_accents=keep_accents,
  94. bos_token=bos_token,
  95. eos_token=eos_token,
  96. unk_token=unk_token,
  97. sep_token=sep_token,
  98. pad_token=pad_token,
  99. cls_token=cls_token,
  100. mask_token=mask_token,
  101. **kwargs,
  102. )
  103. @property
  104. def vocab_size(self):
  105. return len(self.sp_model)
  106. def get_vocab(self):
  107. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  108. vocab.update(self.added_tokens_encoder)
  109. return vocab
  110. def __getstate__(self):
  111. state = self.__dict__.copy()
  112. state["sp_model"] = None
  113. return state
  114. def __setstate__(self, d):
  115. self.__dict__ = d
  116. self.sp_model = spm.SentencePieceProcessor()
  117. self.sp_model.Load(self.vocab_file)
  118. def _tokenize(self, text, sample=False):
  119. """Tokenize a string."""
  120. pieces = self.sp_model.EncodeAsPieces(text)
  121. return pieces
  122. def _convert_token_to_id(self, token):
  123. """Converts a token (str) in an id using the vocab."""
  124. return self.sp_model.PieceToId(token)
  125. def _convert_id_to_token(self, index):
  126. """Converts an index (integer) in a token (str) using the vocab."""
  127. return self.sp_model.IdToPiece(index)
  128. def convert_tokens_to_string(self, tokens):
  129. out_string = self.sp_model.decode_pieces(tokens)
  130. return out_string
  131. def build_inputs_with_special_tokens(
  132. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  133. ) -> list[int]:
  134. """
  135. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  136. adding special tokens. A REMBERT sequence has the following format:
  137. - single sequence: `[CLS] X [SEP]`
  138. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  139. Args:
  140. token_ids_0 (`List[int]`):
  141. List of IDs to which the special tokens will be added.
  142. token_ids_1 (`List[int]`, *optional*):
  143. Optional second list of IDs for sequence pairs.
  144. Returns:
  145. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  146. """
  147. sep = [self.sep_token_id]
  148. cls = [self.cls_token_id]
  149. if token_ids_1 is None:
  150. return cls + token_ids_0 + sep
  151. return cls + token_ids_0 + sep + token_ids_1 + sep
  152. def get_special_tokens_mask(
  153. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  154. ) -> list[int]:
  155. """
  156. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  157. special tokens using the tokenizer `prepare_for_model` method.
  158. Args:
  159. token_ids_0 (`List[int]`):
  160. List of IDs.
  161. token_ids_1 (`List[int]`, *optional*):
  162. Optional second list of IDs for sequence pairs.
  163. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  164. Whether or not the token list is already formatted with special tokens for the model.
  165. Returns:
  166. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  167. """
  168. if already_has_special_tokens:
  169. if token_ids_1 is not None:
  170. raise ValueError(
  171. "You should not supply a second sequence if the provided sequence of "
  172. "ids is already formatted with special tokens for the model."
  173. )
  174. return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_0]
  175. if token_ids_1 is not None:
  176. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  177. return [1] + ([0] * len(token_ids_0)) + [1]
  178. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  179. if not os.path.isdir(save_directory):
  180. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  181. return
  182. out_vocab_file = os.path.join(
  183. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  184. )
  185. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  186. copyfile(self.vocab_file, out_vocab_file)
  187. elif not os.path.isfile(self.vocab_file):
  188. with open(out_vocab_file, "wb") as fi:
  189. content_spiece_model = self.sp_model.serialized_model_proto()
  190. fi.write(content_spiece_model)
  191. return (out_vocab_file,)
  192. __all__ = ["RemBertTokenizer"]