tokenization_mpnet_fast.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. # coding=utf-8
  2. # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Fast Tokenization classes for MPNet."""
  17. import json
  18. from typing import List, Optional, Tuple
  19. from tokenizers import normalizers
  20. from ...tokenization_utils import AddedToken
  21. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  22. from ...utils import logging
  23. from .tokenization_mpnet import MPNetTokenizer
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
  26. class MPNetTokenizerFast(PreTrainedTokenizerFast):
  27. r"""
  28. Construct a "fast" MPNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
  29. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  30. refer to this superclass for more information regarding those methods.
  31. Args:
  32. vocab_file (`str`):
  33. File containing the vocabulary.
  34. do_lower_case (`bool`, *optional*, defaults to `True`):
  35. Whether or not to lowercase the input when tokenizing.
  36. bos_token (`str`, *optional*, defaults to `"<s>"`):
  37. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  38. <Tip>
  39. When building a sequence using special tokens, this is not the token that is used for the beginning of
  40. sequence. The token used is the `cls_token`.
  41. </Tip>
  42. eos_token (`str`, *optional*, defaults to `"</s>"`):
  43. The end of sequence token.
  44. <Tip>
  45. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  46. The token used is the `sep_token`.
  47. </Tip>
  48. sep_token (`str`, *optional*, defaults to `"</s>"`):
  49. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  50. sequence classification or for a text and a question for question answering. It is also used as the last
  51. token of a sequence built with special tokens.
  52. cls_token (`str`, *optional*, defaults to `"<s>"`):
  53. The classifier token which is used when doing sequence classification (classification of the whole sequence
  54. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  55. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  56. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  57. token instead.
  58. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  59. The token used for padding, for example when batching sequences of different lengths.
  60. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  61. The token used for masking values. This is the token used when training this model with masked language
  62. modeling. This is the token which the model will try to predict.
  63. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  64. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
  65. issue](https://github.com/huggingface/transformers/issues/328)).
  66. strip_accents (`bool`, *optional*):
  67. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  68. value for `lowercase` (as in the original BERT).
  69. """
  70. vocab_files_names = VOCAB_FILES_NAMES
  71. slow_tokenizer_class = MPNetTokenizer
  72. model_input_names = ["input_ids", "attention_mask"]
  73. def __init__(
  74. self,
  75. vocab_file=None,
  76. tokenizer_file=None,
  77. do_lower_case=True,
  78. bos_token="<s>",
  79. eos_token="</s>",
  80. sep_token="</s>",
  81. cls_token="<s>",
  82. unk_token="[UNK]",
  83. pad_token="<pad>",
  84. mask_token="<mask>",
  85. tokenize_chinese_chars=True,
  86. strip_accents=None,
  87. **kwargs,
  88. ):
  89. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  90. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  91. sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
  92. cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
  93. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  94. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  95. # Mask token behave like a normal word, i.e. include the space before it
  96. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  97. super().__init__(
  98. vocab_file,
  99. tokenizer_file=tokenizer_file,
  100. do_lower_case=do_lower_case,
  101. bos_token=bos_token,
  102. eos_token=eos_token,
  103. sep_token=sep_token,
  104. cls_token=cls_token,
  105. unk_token=unk_token,
  106. pad_token=pad_token,
  107. mask_token=mask_token,
  108. tokenize_chinese_chars=tokenize_chinese_chars,
  109. strip_accents=strip_accents,
  110. **kwargs,
  111. )
  112. pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
  113. if (
  114. pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
  115. or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
  116. ):
  117. pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
  118. pre_tok_state["lowercase"] = do_lower_case
  119. pre_tok_state["strip_accents"] = strip_accents
  120. self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)
  121. self.do_lower_case = do_lower_case
  122. @property
  123. def mask_token(self) -> str:
  124. """
  125. `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
  126. having been set.
  127. MPNet tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
  128. comprise the space before the *<mask>*.
  129. """
  130. if self._mask_token is None:
  131. if self.verbose:
  132. logger.error("Using mask_token, but it is not set yet.")
  133. return None
  134. return str(self._mask_token)
  135. @mask_token.setter
  136. def mask_token(self, value):
  137. """
  138. Overriding the default behavior of the mask token to have it eat the space before it.
  139. This is needed to preserve backward compatibility with all the previously used models based on MPNet.
  140. """
  141. # Mask token behave like a normal word, i.e. include the space before it
  142. # So we set lstrip to True
  143. value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
  144. self._mask_token = value
  145. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  146. output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
  147. if token_ids_1 is None:
  148. return output
  149. return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
  150. def create_token_type_ids_from_sequences(
  151. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  152. ) -> List[int]:
  153. """
  154. Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not
  155. make use of token type ids, therefore a list of zeros is returned
  156. Args:
  157. token_ids_0 (`List[int]`):
  158. List of ids.
  159. token_ids_1 (`List[int]`, *optional*):
  160. Optional second list of IDs for sequence pairs
  161. Returns:
  162. `List[int]`: List of zeros.
  163. """
  164. sep = [self.sep_token_id]
  165. cls = [self.cls_token_id]
  166. if token_ids_1 is None:
  167. return len(cls + token_ids_0 + sep) * [0]
  168. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  169. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  170. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  171. return tuple(files)