tokenization_bloom_fast.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # coding=utf-8
  2. # Copyright 2022 The HuggingFace Inc. team.
  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 Bloom."""
  16. import pickle
  17. from typing import Optional, Tuple
  18. from ...tokenization_utils_base import BatchEncoding
  19. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
  23. class BloomTokenizerFast(PreTrainedTokenizerFast):
  24. """
  25. Construct a "fast" Bloom tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
  26. Byte-Pair-Encoding.
  27. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  28. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  29. ```python
  30. >>> from transformers import BloomTokenizerFast
  31. >>> tokenizer = BloomTokenizerFast.from_pretrained("bigscience/bloom")
  32. >>> tokenizer("Hello world")["input_ids"]
  33. [59414, 8876]
  34. >>> tokenizer(" Hello world")["input_ids"]
  35. [86153, 8876]
  36. ```
  37. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
  38. the model was not pretrained this way, it might yield a decrease in performance.
  39. <Tip>
  40. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  41. </Tip>
  42. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  43. refer to this superclass for more information regarding those methods.
  44. Args:
  45. vocab_file (`str`):
  46. Path to the vocabulary file.
  47. merges_file (`str`):
  48. Path to the merges 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. unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
  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. bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
  56. The beginning of sequence token.
  57. eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
  58. The end of sequence token.
  59. add_prefix_space (`bool`, *optional*, defaults to `False`):
  60. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  61. other word. (Bloom tokenizer detect beginning of words by the preceding space).
  62. trim_offsets (`bool`, *optional*, defaults to `True`):
  63. Whether or not the post-processing step should trim offsets to avoid including whitespaces.
  64. """
  65. vocab_files_names = VOCAB_FILES_NAMES
  66. model_input_names = ["input_ids", "attention_mask"]
  67. slow_tokenizer_class = None
  68. # No `max_model_input_sizes` as BLOOM uses ALiBi positional embeddings
  69. def __init__(
  70. self,
  71. vocab_file=None,
  72. merges_file=None,
  73. tokenizer_file=None,
  74. unk_token="<unk>",
  75. bos_token="<s>",
  76. eos_token="</s>",
  77. pad_token="<pad>",
  78. add_prefix_space=False,
  79. clean_up_tokenization_spaces=False,
  80. **kwargs,
  81. ):
  82. super().__init__(
  83. vocab_file=vocab_file,
  84. merges_file=merges_file,
  85. tokenizer_file=tokenizer_file,
  86. unk_token=unk_token,
  87. bos_token=bos_token,
  88. eos_token=eos_token,
  89. pad_token=pad_token,
  90. add_prefix_space=add_prefix_space,
  91. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  92. **kwargs,
  93. )
  94. # TODO @ArthurZucker this can only work one way for now, to update later-on. Tests should also properly
  95. # check this as they were green before.
  96. pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer)
  97. decoder_state = pickle.dumps(self.backend_tokenizer.decoder)
  98. if add_prefix_space:
  99. pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
  100. decoder_state = decoder_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
  101. self.backend_tokenizer.pre_tokenizer = pickle.loads(pre_tok_state)
  102. self.backend_tokenizer.decoder = pickle.loads(decoder_state)
  103. self.add_prefix_space = add_prefix_space
  104. def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
  105. is_split_into_words = kwargs.get("is_split_into_words", False)
  106. if not (self.add_prefix_space or not is_split_into_words):
  107. raise Exception(
  108. f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
  109. " pretokenized inputs."
  110. )
  111. return super()._batch_encode_plus(*args, **kwargs)
  112. def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
  113. is_split_into_words = kwargs.get("is_split_into_words", False)
  114. if not (self.add_prefix_space or not is_split_into_words):
  115. raise Exception(
  116. f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
  117. " pretokenized inputs."
  118. )
  119. return super()._encode_plus(*args, **kwargs)
  120. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  121. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  122. return tuple(files)