tokenization_blenderbot.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
  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. """Tokenization class for Blenderbot."""
  15. from tokenizers import Tokenizer, decoders, pre_tokenizers
  16. from tokenizers.models import BPE
  17. from ...tokenization_utils_base import AddedToken
  18. from ...tokenization_utils_tokenizers import TokenizersBackend
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. VOCAB_FILES_NAMES = {
  22. "vocab_file": "vocab.json",
  23. "merges_file": "merges.txt",
  24. "tokenizer_config_file": "tokenizer_config.json",
  25. }
  26. class BlenderbotTokenizer(TokenizersBackend):
  27. """
  28. Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
  29. tokenizer, using byte-level Byte-Pair-Encoding.
  30. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  31. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  32. ```python
  33. >>> from transformers import BlenderbotTokenizerFast
  34. >>> tokenizer = BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B")
  35. >>> tokenizer("Hello world")["input_ids"]
  36. [6950, 1085, 2]
  37. >>> tokenizer(" Hello world")["input_ids"]
  38. [6950, 1085, 2]
  39. ```
  40. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  41. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  42. <Tip>
  43. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  44. </Tip>
  45. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  46. refer to this superclass for more information regarding those methods.
  47. Args:
  48. bos_token (`str`, *optional*, defaults to `"<s>"`):
  49. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  50. <Tip>
  51. When building a sequence using special tokens, this is not the token that is used for the beginning of
  52. sequence. The token used is the `cls_token`.
  53. </Tip>
  54. eos_token (`str`, *optional*, defaults to `"</s>"`):
  55. The end of sequence token.
  56. <Tip>
  57. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  58. The token used is the `sep_token`.
  59. </Tip>
  60. sep_token (`str`, *optional*, defaults to `"</s>"`):
  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 `"<s>"`):
  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 `True`):
  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. (Blenderbot tokenizer detect beginning of words by the preceding space).
  78. vocab (`str` or `dict[str, int]`, *optional*):
  79. Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
  80. merges (`str` or `list[str]`, *optional*):
  81. Custom merges list. If not provided, merges are loaded from `merges_file`.
  82. """
  83. vocab_files_names = VOCAB_FILES_NAMES
  84. model_input_names = ["input_ids", "attention_mask"]
  85. model = BPE
  86. def __init__(
  87. self,
  88. bos_token="<s>",
  89. eos_token="</s>",
  90. sep_token="</s>",
  91. cls_token="<s>",
  92. unk_token="<unk>",
  93. pad_token="<pad>",
  94. mask_token="<mask>",
  95. add_prefix_space=True,
  96. vocab=None,
  97. merges=None,
  98. **kwargs,
  99. ):
  100. self.add_prefix_space = add_prefix_space
  101. mask_token = (
  102. AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
  103. if isinstance(mask_token, str)
  104. else mask_token
  105. )
  106. # Initialize vocab and merges; when not provided fall back to minimal vocab
  107. self._vocab = (
  108. vocab
  109. if vocab is not None
  110. else {
  111. str(bos_token): 0,
  112. str(pad_token): 1,
  113. str(eos_token): 2,
  114. str(unk_token): 3,
  115. str(mask_token): 4,
  116. }
  117. )
  118. self._merges = merges or []
  119. self._tokenizer = Tokenizer(
  120. BPE(
  121. vocab=self._vocab,
  122. merges=self._merges,
  123. dropout=None,
  124. continuing_subword_prefix="",
  125. end_of_word_suffix="",
  126. fuse_unk=False,
  127. )
  128. )
  129. self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
  130. self._tokenizer.decoder = decoders.ByteLevel()
  131. super().__init__(
  132. bos_token=bos_token,
  133. eos_token=eos_token,
  134. sep_token=sep_token,
  135. cls_token=cls_token,
  136. unk_token=unk_token,
  137. pad_token=pad_token,
  138. mask_token=mask_token,
  139. add_prefix_space=add_prefix_space,
  140. **kwargs,
  141. )
  142. __all__ = ["BlenderbotTokenizer"]