tokenization_speecht5.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # Copyright 2023 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 SpeechT5."""
  15. from typing import Any
  16. from ...tokenization_utils_sentencepiece import SentencePieceBackend
  17. from ...utils import logging
  18. from ...utils.import_utils import requires
  19. from .number_normalizer import EnglishNumberNormalizer
  20. logger = logging.get_logger(__name__)
  21. VOCAB_FILES_NAMES = {"vocab_file": "spm_char.model"}
  22. @requires(backends=("sentencepiece",))
  23. class SpeechT5Tokenizer(SentencePieceBackend):
  24. """
  25. Construct a SpeechT5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
  26. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  27. this superclass for more information regarding those methods.
  28. Args:
  29. vocab_file (`str`):
  30. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  31. contains the vocabulary necessary to instantiate a tokenizer.
  32. bos_token (`str`, *optional*, defaults to `"<s>"`):
  33. The begin of sequence token.
  34. eos_token (`str`, *optional*, defaults to `"</s>"`):
  35. The end of sequence token.
  36. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  37. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  38. token instead.
  39. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  40. The token used for padding, for example when batching sequences of different lengths.
  41. normalize (`bool`, *optional*, defaults to `False`):
  42. Whether to convert numeric quantities in the text to their spelt-out english counterparts.
  43. sp_model_kwargs (`dict`, *optional*):
  44. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  45. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  46. to set:
  47. - `enable_sampling`: Enable subword regularization.
  48. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  49. - `nbest_size = {0,1}`: No sampling is performed.
  50. - `nbest_size > 1`: samples from the nbest_size results.
  51. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  52. using forward-filtering-and-backward-sampling algorithm.
  53. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  54. BPE-dropout.
  55. Attributes:
  56. sp_model (`SentencePieceProcessor`):
  57. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  58. """
  59. vocab_files_names = VOCAB_FILES_NAMES
  60. model_input_names = ["input_ids", "attention_mask"]
  61. is_fast = False
  62. def __init__(
  63. self,
  64. vocab_file,
  65. bos_token="<s>",
  66. eos_token="</s>",
  67. unk_token="<unk>",
  68. pad_token="<pad>",
  69. normalize=False,
  70. sp_model_kwargs: dict[str, Any] | None = None,
  71. **kwargs,
  72. ) -> None:
  73. self.normalize = normalize
  74. self._normalizer = None
  75. # Prepare sp_model_kwargs for parent class
  76. if sp_model_kwargs is not None:
  77. kwargs["sp_model_kwargs"] = sp_model_kwargs
  78. # Call parent init (which will load sp_model)
  79. super().__init__(
  80. vocab_file=vocab_file,
  81. bos_token=bos_token,
  82. eos_token=eos_token,
  83. unk_token=unk_token,
  84. pad_token=pad_token,
  85. normalize=normalize,
  86. **kwargs,
  87. )
  88. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  89. normalize = kwargs.pop("normalize", self.normalize)
  90. if is_split_into_words:
  91. text = " " + text
  92. if normalize:
  93. text = self.normalizer(text)
  94. return (text, kwargs)
  95. @property
  96. def normalizer(self):
  97. if self._normalizer is None:
  98. self._normalizer = EnglishNumberNormalizer()
  99. return self._normalizer
  100. @normalizer.setter
  101. def normalizer(self, value):
  102. self._normalizer = value
  103. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:
  104. """Build model inputs from a sequence by appending eos_token_id."""
  105. if token_ids_1 is None:
  106. return token_ids_0 + [self.eos_token_id]
  107. # We don't expect to process pairs, but leave the pair logic for API consistency
  108. return token_ids_0 + token_ids_1 + [self.eos_token_id]
  109. def get_special_tokens_mask(
  110. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  111. ) -> list[int]:
  112. if already_has_special_tokens:
  113. return super().get_special_tokens_mask(
  114. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  115. )
  116. suffix_ones = [1]
  117. if token_ids_1 is None:
  118. return ([0] * len(token_ids_0)) + suffix_ones
  119. return ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
  120. def create_token_type_ids_from_sequences(
  121. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  122. ) -> list[int]:
  123. """
  124. Create a mask from the two sequences passed to be used in a sequence-pair classification task. SpeechT5 does not
  125. make use of token type ids, therefore a list of zeros is returned.
  126. Args:
  127. token_ids_0 (`list[int]`):
  128. List of IDs.
  129. token_ids_1 (`list[int]`, *optional*):
  130. Optional second list of IDs for sequence pairs.
  131. Returns:
  132. `list[int]`: List of zeros.
  133. """
  134. eos = [self.eos_token_id]
  135. if token_ids_1 is None:
  136. return len(token_ids_0 + eos) * [0]
  137. return len(token_ids_0 + token_ids_1 + eos) * [0]
  138. __all__ = ["SpeechT5Tokenizer"]