tokenization_mpnet.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
  2. # Copyright (c) 2018, NVIDIA CORPORATION. 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 MPNet."""
  16. from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
  17. from tokenizers.models import WordPiece
  18. from ...tokenization_python import AddedToken
  19. from ...tokenization_utils_tokenizers import TokenizersBackend
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
  23. class MPNetTokenizer(TokenizersBackend):
  24. r"""
  25. Construct a MPNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
  26. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  27. refer to this superclass for more information regarding those methods.
  28. Args:
  29. vocab (`str` or `dict[str, int]`, *optional*):
  30. Dictionary mapping tokens to their IDs. If not provided, an empty vocab is initialized.
  31. do_lower_case (`bool`, *optional*, defaults to `True`):
  32. Whether or not to lowercase the input when tokenizing.
  33. bos_token (`str`, *optional*, defaults to `"<s>"`):
  34. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  35. <Tip>
  36. When building a sequence using special tokens, this is not the token that is used for the beginning of
  37. sequence. The token used is the `cls_token`.
  38. </Tip>
  39. eos_token (`str`, *optional*, defaults to `"</s>"`):
  40. The end of sequence token.
  41. <Tip>
  42. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  43. The token used is the `sep_token`.
  44. </Tip>
  45. sep_token (`str`, *optional*, defaults to `"</s>"`):
  46. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  47. sequence classification or for a text and a question for question answering. It is also used as the last
  48. token of a sequence built with special tokens.
  49. cls_token (`str`, *optional*, defaults to `"<s>"`):
  50. The classifier token which is used when doing sequence classification (classification of the whole sequence
  51. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  52. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  53. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  54. token instead.
  55. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  56. The token used for padding, for example when batching sequences of different lengths.
  57. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  58. The token used for masking values. This is the token used when training this model with masked language
  59. modeling. This is the token which the model will try to predict.
  60. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  61. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
  62. issue](https://github.com/huggingface/transformers/issues/328)).
  63. strip_accents (`bool`, *optional*):
  64. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  65. value for `lowercase` (as in the original BERT).
  66. """
  67. vocab_files_names = VOCAB_FILES_NAMES
  68. model_input_names = ["input_ids", "attention_mask"]
  69. model = WordPiece
  70. def __init__(
  71. self,
  72. vocab: str | dict[str, int] | None = None,
  73. do_lower_case=True,
  74. bos_token="<s>",
  75. eos_token="</s>",
  76. sep_token="</s>",
  77. cls_token="<s>",
  78. unk_token="[UNK]",
  79. pad_token="<pad>",
  80. mask_token="<mask>",
  81. tokenize_chinese_chars=True,
  82. strip_accents=None,
  83. **kwargs,
  84. ):
  85. # Initialize vocab
  86. self._vocab = vocab if vocab is not None else {}
  87. # Initialize the tokenizer with WordPiece model
  88. self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
  89. # Set normalizer based on MPNetConverter logic
  90. self._tokenizer.normalizer = normalizers.BertNormalizer(
  91. clean_text=True,
  92. handle_chinese_chars=tokenize_chinese_chars,
  93. strip_accents=strip_accents,
  94. lowercase=do_lower_case,
  95. )
  96. # Set pre-tokenizer
  97. self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
  98. # Set decoder
  99. self._tokenizer.decoder = decoders.WordPiece(prefix="##")
  100. # Store do_lower_case for later use
  101. self.do_lower_case = do_lower_case
  102. # Handle special token initialization
  103. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  104. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  105. sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
  106. cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
  107. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  108. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  109. # Mask token behave like a normal word, i.e. include the space before it
  110. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  111. super().__init__(
  112. do_lower_case=do_lower_case,
  113. bos_token=bos_token,
  114. eos_token=eos_token,
  115. sep_token=sep_token,
  116. cls_token=cls_token,
  117. unk_token=unk_token,
  118. pad_token=pad_token,
  119. mask_token=mask_token,
  120. tokenize_chinese_chars=tokenize_chinese_chars,
  121. strip_accents=strip_accents,
  122. **kwargs,
  123. )
  124. # Set post_processor after super().__init__ to ensure we have token IDs
  125. cls_str = str(self.cls_token)
  126. sep_str = str(self.sep_token)
  127. cls_token_id = self.cls_token_id if self.cls_token_id is not None else 0
  128. sep_token_id = self.sep_token_id if self.sep_token_id is not None else 2
  129. self._tokenizer.post_processor = processors.TemplateProcessing(
  130. single=f"{cls_str}:0 $A:0 {sep_str}:0",
  131. pair=f"{cls_str}:0 $A:0 {sep_str}:0 {sep_str}:0 $B:1 {sep_str}:1", # MPNet uses two [SEP] tokens
  132. special_tokens=[
  133. (cls_str, cls_token_id),
  134. (sep_str, sep_token_id),
  135. ],
  136. )
  137. @property
  138. def mask_token(self) -> str:
  139. """
  140. `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
  141. having been set.
  142. MPNet tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
  143. comprise the space before the *<mask>*.
  144. """
  145. if self._mask_token is None:
  146. if self.verbose:
  147. logger.error("Using mask_token, but it is not set yet.")
  148. return None
  149. return str(self._mask_token)
  150. @mask_token.setter
  151. def mask_token(self, value):
  152. """
  153. Overriding the default behavior of the mask token to have it eat the space before it.
  154. This is needed to preserve backward compatibility with all the previously used models based on MPNet.
  155. """
  156. # Mask token behave like a normal word, i.e. include the space before it
  157. # So we set lstrip to True
  158. value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
  159. self._mask_token = value
  160. __all__ = ["MPNetTokenizer"]