tokenization_t5.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright 2018 T5 Authors and HuggingFace Inc. team.
  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 model T5."""
  15. import re
  16. from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
  17. from tokenizers.models import Unigram
  18. from ...tokenization_utils_tokenizers import TokenizersBackend
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
  22. class T5Tokenizer(TokenizersBackend):
  23. """
  24. Construct a T5 tokenizer (backed by HuggingFace's *tokenizers* library). Based on
  25. [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
  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_file (`str`, *optional*):
  30. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  31. contains the vocabulary necessary to instantiate a tokenizer.
  32. eos_token (`str`, *optional*, defaults to `"</s>"`):
  33. The end of sequence token.
  34. <Tip>
  35. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  36. The token used is the `sep_token`.
  37. </Tip>
  38. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  39. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  40. token instead.
  41. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  42. The token used for padding, for example when batching sequences of different lengths.
  43. extra_ids (`int`, *optional*, defaults to 100):
  44. Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are accessible as
  45. "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be retrieved by
  46. calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids method
  47. additional_special_tokens (`list[str]`, *optional*):
  48. Additional special tokens used by the tokenizer.
  49. vocab (`str`, `dict` or `list`, *optional*):
  50. Custom vocabulary dict. If not provided, a minimal vocabulary is created using the special tokens.
  51. """
  52. vocab_files_names = VOCAB_FILES_NAMES
  53. model_input_names = ["input_ids", "attention_mask"]
  54. model = Unigram
  55. def __init__(
  56. self,
  57. vocab: str | list[tuple[str, float]] | None = None,
  58. eos_token="</s>",
  59. unk_token="<unk>",
  60. pad_token="<pad>",
  61. _spm_precompiled_charsmap=None,
  62. extra_ids=100,
  63. additional_special_tokens=None,
  64. **kwargs,
  65. ):
  66. self._extra_ids = extra_ids
  67. # Handle extra_ids and additional_special_tokens
  68. if additional_special_tokens is not None:
  69. extra_tokens = [x for x in additional_special_tokens if "<extra_id_" in str(x)]
  70. if len(extra_tokens) < 1:
  71. additional_special_tokens += [f"<extra_id_{i}>" for i in range(extra_ids)]
  72. elif extra_ids > 0 and extra_ids != len(extra_tokens):
  73. raise ValueError(
  74. f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
  75. " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
  76. " tokens"
  77. )
  78. else:
  79. extra_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
  80. additional_special_tokens = extra_tokens
  81. # T5 vocab structure: <pad>=0, </s>=1, <unk>=2, then regular vocab, then extra_ids in reverse
  82. if vocab is not None:
  83. self._vocab_scores = vocab
  84. else:
  85. self._vocab_scores = [
  86. (str(pad_token), 0.0),
  87. (str(eos_token), 0.0),
  88. (str(unk_token), 0.0),
  89. ("▁", -2.0), # Space token
  90. ]
  91. for i in range(extra_ids - 1, -1, -1):
  92. self._vocab_scores.append((f"<extra_id_{i}>", 0.0))
  93. self._tokenizer = Tokenizer(
  94. Unigram(
  95. self._vocab_scores,
  96. unk_id=2,
  97. byte_fallback=False,
  98. )
  99. )
  100. if _spm_precompiled_charsmap is not None:
  101. self._tokenizer.normalizer = normalizers.Precompiled(_spm_precompiled_charsmap)
  102. self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
  103. [
  104. pre_tokenizers.WhitespaceSplit(),
  105. pre_tokenizers.Metaspace(replacement="▁", prepend_scheme="always", split=True),
  106. ]
  107. )
  108. self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme="always", split=True)
  109. super().__init__(
  110. eos_token=eos_token,
  111. unk_token=unk_token,
  112. pad_token=pad_token,
  113. extra_ids=extra_ids,
  114. additional_special_tokens=additional_special_tokens,
  115. **kwargs,
  116. )
  117. self._tokenizer.post_processor = processors.TemplateProcessing(
  118. single=["$A", "</s>"],
  119. pair=["$A", "</s>", "$B", "</s>"],
  120. special_tokens=[
  121. ("</s>", self.eos_token_id),
  122. ],
  123. )
  124. def get_sentinel_tokens(self):
  125. """Get the list of sentinel tokens (extra_id tokens) from additional_special_tokens."""
  126. return list(
  127. set(filter(lambda x: bool(re.search(r"<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
  128. )
  129. def get_sentinel_token_ids(self):
  130. """Get the token IDs for sentinel tokens."""
  131. return [self.convert_tokens_to_ids(token) for token in self.get_sentinel_tokens()]
  132. __all__ = ["T5Tokenizer"]