tokenization_blenderbot_fast.py 13 KB

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