tokenization_deberta.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # Copyright 2020 Microsoft and the HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Fast Tokenization class for model DeBERTa."""
  15. from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, processors
  16. from tokenizers.models import BPE
  17. from ...tokenization_utils_tokenizers import TokenizersBackend
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
  21. class DebertaTokenizer(TokenizersBackend):
  22. """
  23. Construct a "fast" DeBERTa tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
  24. Byte-Pair-Encoding.
  25. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  26. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  27. ```python
  28. >>> from transformers import DebertaTokenizer
  29. >>> tokenizer = DebertaTokenizer.from_pretrained("microsoft/deberta-base")
  30. >>> tokenizer("Hello world")["input_ids"]
  31. [1, 31414, 232, 2]
  32. >>> tokenizer(" Hello world")["input_ids"]
  33. [1, 20920, 232, 2]
  34. ```
  35. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
  36. the model was not pretrained this way, it might yield a decrease in performance.
  37. <Tip>
  38. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  39. </Tip>
  40. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  41. refer to this superclass for more information regarding those methods.
  42. Args:
  43. vocab_file (`str`, *optional*):
  44. Path to the vocabulary file.
  45. merges_file (`str`, *optional*):
  46. Path to the merges file.
  47. tokenizer_file (`str`, *optional*):
  48. The path to a tokenizer file to use instead of the vocab file.
  49. errors (`str`, *optional*, defaults to `"replace"`):
  50. Paradigm to follow when decoding bytes to UTF-8. See
  51. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  52. bos_token (`str`, *optional*, defaults to `"[CLS]"`):
  53. The beginning of sequence token.
  54. eos_token (`str`, *optional*, defaults to `"[SEP]"`):
  55. The end of sequence token.
  56. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  57. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  58. sequence classification or for a text and a question for question answering. It is also used as the last
  59. token of a sequence built with special tokens.
  60. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  61. The classifier token which is used when doing sequence classification (classification of the whole sequence
  62. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  63. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  64. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  65. token instead.
  66. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  67. The token used for padding, for example when batching sequences of different lengths.
  68. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  69. The token used for masking values. This is the token used when training this model with masked language
  70. modeling. This is the token which the model will try to predict.
  71. add_prefix_space (`bool`, *optional*, defaults to `False`):
  72. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  73. other word. (Deberta tokenizer detect beginning of words by the preceding space).
  74. """
  75. vocab_files_names = VOCAB_FILES_NAMES
  76. model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
  77. model = BPE
  78. def __init__(
  79. self,
  80. vocab: str | dict[str, int] | None = None,
  81. merges: str | list[str] | None = None,
  82. errors="replace",
  83. bos_token="[CLS]",
  84. eos_token="[SEP]",
  85. sep_token="[SEP]",
  86. cls_token="[CLS]",
  87. unk_token="[UNK]",
  88. pad_token="[PAD]",
  89. mask_token="[MASK]",
  90. add_prefix_space=False,
  91. **kwargs,
  92. ):
  93. self.add_prefix_space = add_prefix_space
  94. self._vocab = (
  95. vocab
  96. if vocab is not None
  97. else {
  98. str(unk_token): 0,
  99. str(cls_token): 1,
  100. str(sep_token): 2,
  101. str(pad_token): 3,
  102. str(mask_token): 4,
  103. }
  104. )
  105. self._merges = merges or []
  106. self._tokenizer = Tokenizer(
  107. BPE(
  108. vocab=self._vocab,
  109. merges=self._merges,
  110. dropout=None,
  111. unk_token=None,
  112. continuing_subword_prefix="",
  113. end_of_word_suffix="",
  114. fuse_unk=False,
  115. )
  116. )
  117. self._tokenizer.normalizer = None
  118. self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
  119. self._tokenizer.decoder = decoders.ByteLevel()
  120. super().__init__(
  121. errors=errors,
  122. bos_token=bos_token,
  123. eos_token=eos_token,
  124. unk_token=unk_token,
  125. sep_token=sep_token,
  126. cls_token=cls_token,
  127. pad_token=pad_token,
  128. mask_token=mask_token,
  129. add_prefix_space=add_prefix_space,
  130. **kwargs,
  131. )
  132. self._tokenizer.post_processor = processors.TemplateProcessing(
  133. single=f"{self.cls_token} $A {self.sep_token}",
  134. pair=f"{self.cls_token} $A {self.sep_token} {self.sep_token} $B {self.sep_token}",
  135. special_tokens=[
  136. (self.cls_token, self.cls_token_id),
  137. (self.sep_token, self.sep_token_id),
  138. ],
  139. )
  140. @property
  141. def mask_token(self) -> str:
  142. """
  143. `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
  144. having been set.
  145. Deberta tokenizer has a special mask token to be used in the fill-mask pipeline. The mask token will greedily
  146. comprise the space before the *[MASK]*.
  147. """
  148. if self._mask_token is None:
  149. if self.verbose:
  150. logger.error("Using mask_token, but it is not set yet.")
  151. return None
  152. return str(self._mask_token)
  153. @mask_token.setter
  154. def mask_token(self, value):
  155. """
  156. Overriding the default behavior of the mask token to have it eat the space before it.
  157. """
  158. # Mask token behave like a normal word, i.e. include the space before it
  159. # So we set lstrip to True
  160. value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
  161. self._mask_token = value
  162. __all__ = ["DebertaTokenizer"]