tokenization_deberta_fast.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # coding=utf-8
  2. # Copyright 2020 Microsoft 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. """Fast Tokenization class for model DeBERTa."""
  16. import json
  17. from typing import List, Optional, Tuple
  18. from tokenizers import pre_tokenizers
  19. from ...tokenization_utils_base import AddedToken, BatchEncoding
  20. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  21. from ...utils import logging
  22. from .tokenization_deberta import DebertaTokenizer
  23. logger = logging.get_logger(__name__)
  24. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
  25. class DebertaTokenizerFast(PreTrainedTokenizerFast):
  26. """
  27. Construct a "fast" DeBERTa tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
  28. Byte-Pair-Encoding.
  29. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  30. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  31. ```python
  32. >>> from transformers import DebertaTokenizerFast
  33. >>> tokenizer = DebertaTokenizerFast.from_pretrained("microsoft/deberta-base")
  34. >>> tokenizer("Hello world")["input_ids"]
  35. [1, 31414, 232, 2]
  36. >>> tokenizer(" Hello world")["input_ids"]
  37. [1, 20920, 232, 2]
  38. ```
  39. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
  40. the model was not pretrained this way, it might yield a decrease in performance.
  41. <Tip>
  42. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  43. </Tip>
  44. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  45. refer to this superclass for more information regarding those methods.
  46. Args:
  47. vocab_file (`str`, *optional*):
  48. Path to the vocabulary file.
  49. merges_file (`str`, *optional*):
  50. Path to the merges file.
  51. tokenizer_file (`str`, *optional*):
  52. The path to a tokenizer file to use instead of the vocab file.
  53. errors (`str`, *optional*, defaults to `"replace"`):
  54. Paradigm to follow when decoding bytes to UTF-8. See
  55. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  56. bos_token (`str`, *optional*, defaults to `"[CLS]"`):
  57. The beginning of sequence token.
  58. eos_token (`str`, *optional*, defaults to `"[SEP]"`):
  59. The end of sequence token.
  60. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  61. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  62. sequence classification or for a text and a question for question answering. It is also used as the last
  63. token of a sequence built with special tokens.
  64. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  65. The classifier token which is used when doing sequence classification (classification of the whole sequence
  66. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  67. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  68. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  69. token instead.
  70. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  71. The token used for padding, for example when batching sequences of different lengths.
  72. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  73. The token used for masking values. This is the token used when training this model with masked language
  74. modeling. This is the token which the model will try to predict.
  75. add_prefix_space (`bool`, *optional*, defaults to `False`):
  76. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  77. other word. (Deberta tokenizer detect beginning of words by the preceding space).
  78. """
  79. vocab_files_names = VOCAB_FILES_NAMES
  80. model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
  81. slow_tokenizer_class = DebertaTokenizer
  82. def __init__(
  83. self,
  84. vocab_file=None,
  85. merges_file=None,
  86. tokenizer_file=None,
  87. errors="replace",
  88. bos_token="[CLS]",
  89. eos_token="[SEP]",
  90. sep_token="[SEP]",
  91. cls_token="[CLS]",
  92. unk_token="[UNK]",
  93. pad_token="[PAD]",
  94. mask_token="[MASK]",
  95. add_prefix_space=False,
  96. **kwargs,
  97. ):
  98. super().__init__(
  99. vocab_file,
  100. merges_file,
  101. tokenizer_file=tokenizer_file,
  102. errors=errors,
  103. bos_token=bos_token,
  104. eos_token=eos_token,
  105. unk_token=unk_token,
  106. sep_token=sep_token,
  107. cls_token=cls_token,
  108. pad_token=pad_token,
  109. mask_token=mask_token,
  110. add_prefix_space=add_prefix_space,
  111. **kwargs,
  112. )
  113. self.add_bos_token = kwargs.pop("add_bos_token", False)
  114. pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
  115. if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
  116. pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
  117. pre_tok_state["add_prefix_space"] = add_prefix_space
  118. self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
  119. self.add_prefix_space = add_prefix_space
  120. @property
  121. def mask_token(self) -> str:
  122. """
  123. `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
  124. having been set.
  125. Deberta tokenizer has a special mask token to be used in the fill-mask pipeline. The mask token will greedily
  126. comprise the space before the *[MASK]*.
  127. """
  128. if self._mask_token is None:
  129. if self.verbose:
  130. logger.error("Using mask_token, but it is not set yet.")
  131. return None
  132. return str(self._mask_token)
  133. @mask_token.setter
  134. def mask_token(self, value):
  135. """
  136. Overriding the default behavior of the mask token to have it eat the space before it.
  137. """
  138. # Mask token behave like a normal word, i.e. include the space before it
  139. # So we set lstrip to True
  140. value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
  141. self._mask_token = value
  142. def build_inputs_with_special_tokens(
  143. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  144. ) -> List[int]:
  145. """
  146. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  147. adding special tokens. A DeBERTa sequence has the following format:
  148. - single sequence: [CLS] X [SEP]
  149. - pair of sequences: [CLS] A [SEP] B [SEP]
  150. Args:
  151. token_ids_0 (`List[int]`):
  152. List of IDs to which the special tokens will be added.
  153. token_ids_1 (`List[int]`, *optional*):
  154. Optional second list of IDs for sequence pairs.
  155. Returns:
  156. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  157. """
  158. if token_ids_1 is None:
  159. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  160. cls = [self.cls_token_id]
  161. sep = [self.sep_token_id]
  162. return cls + token_ids_0 + sep + token_ids_1 + sep
  163. def create_token_type_ids_from_sequences(
  164. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  165. ) -> List[int]:
  166. """
  167. Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
  168. sequence pair mask has the following format:
  169. ```
  170. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  171. | first sequence | second sequence |
  172. ```
  173. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  174. Args:
  175. token_ids_0 (`List[int]`):
  176. List of IDs.
  177. token_ids_1 (`List[int]`, *optional*):
  178. Optional second list of IDs for sequence pairs.
  179. Returns:
  180. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  181. """
  182. sep = [self.sep_token_id]
  183. cls = [self.cls_token_id]
  184. if token_ids_1 is None:
  185. return len(cls + token_ids_0 + sep) * [0]
  186. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  187. # Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast._batch_encode_plus
  188. def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
  189. is_split_into_words = kwargs.get("is_split_into_words", False)
  190. assert self.add_prefix_space or not is_split_into_words, (
  191. f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
  192. "to use it with pretokenized inputs."
  193. )
  194. return super()._batch_encode_plus(*args, **kwargs)
  195. # Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast._encode_plus
  196. def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
  197. is_split_into_words = kwargs.get("is_split_into_words", False)
  198. assert self.add_prefix_space or not is_split_into_words, (
  199. f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
  200. "to use it with pretokenized inputs."
  201. )
  202. return super()._encode_plus(*args, **kwargs)
  203. # Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast.save_vocabulary
  204. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  205. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  206. return tuple(files)