tokenization_byt5.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. # Copyright 2021 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 ByT5."""
  15. import warnings
  16. from ...tokenization_python import AddedToken, PreTrainedTokenizer
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class ByT5Tokenizer(PreTrainedTokenizer):
  20. """
  21. Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
  22. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  23. this superclass for more information regarding those methods.
  24. Args:
  25. eos_token (`str`, *optional*, defaults to `"</s>"`):
  26. The end of sequence token.
  27. <Tip>
  28. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  29. The token used is the `sep_token`.
  30. </Tip>
  31. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  32. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  33. token instead.
  34. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  35. The token used for padding, for example when batching sequences of different lengths.
  36. extra_ids (`int`, *optional*, defaults to 125):
  37. Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
  38. accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
  39. indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
  40. like in ByT5 preprocessing see
  41. [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
  42. additional_special_tokens (`list[str]`, *optional*):
  43. Additional special tokens used by the tokenizer.
  44. """
  45. model_input_names = ["input_ids", "attention_mask"]
  46. def __init__(
  47. self,
  48. eos_token="</s>",
  49. unk_token="<unk>",
  50. pad_token="<pad>",
  51. extra_ids=125,
  52. additional_special_tokens=None,
  53. **kwargs,
  54. ) -> None:
  55. # Add extra_ids to the special token list
  56. if extra_ids > 0 and additional_special_tokens is None:
  57. additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
  58. elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
  59. # Check that we have the right number of extra_id special tokens
  60. extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
  61. if extra_tokens != extra_ids:
  62. raise ValueError(
  63. f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
  64. " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the"
  65. " extra_ids tokens"
  66. )
  67. pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token
  68. # we force left and right stripping for backward compatibility. The byt5tests depend on this.
  69. eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token
  70. unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token
  71. # unk token needs to be in the vocab with correct index
  72. self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token}
  73. self.offset = len(self._added_tokens_decoder)
  74. self._utf_vocab_size = 2**8 # utf is 8 bits
  75. super().__init__(
  76. eos_token=eos_token,
  77. unk_token=unk_token,
  78. pad_token=pad_token,
  79. extra_ids=0,
  80. additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
  81. **kwargs,
  82. )
  83. @property
  84. def vocab_size(self):
  85. return self._utf_vocab_size
  86. def get_vocab(self):
  87. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
  88. vocab.update(self.added_tokens_encoder)
  89. return vocab
  90. def get_special_tokens_mask(
  91. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  92. ) -> list[int]:
  93. """
  94. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  95. special tokens using the tokenizer `prepare_for_model` method.
  96. Args:
  97. token_ids_0 (`list[int]`):
  98. List of IDs.
  99. token_ids_1 (`list[int]`, *optional*):
  100. Optional second list of IDs for sequence pairs.
  101. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  102. Whether or not the token list is already formatted with special tokens for the model.
  103. Returns:
  104. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  105. """
  106. if already_has_special_tokens:
  107. return super().get_special_tokens_mask(
  108. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  109. )
  110. # normal case: some special tokens
  111. if token_ids_1 is None:
  112. return ([0] * len(token_ids_0)) + [1]
  113. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  114. def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]:
  115. """Do not add eos again if user already added it."""
  116. if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
  117. warnings.warn(
  118. f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
  119. " eos tokens being added."
  120. )
  121. return token_ids
  122. else:
  123. return token_ids + [self.eos_token_id]
  124. def create_token_type_ids_from_sequences(
  125. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  126. ) -> list[int]:
  127. """
  128. Create a mask from the two sequences passed to be used in a sequence-pair classification task. ByT5 does not
  129. make use of token type ids, therefore a list of zeros is returned.
  130. Args:
  131. token_ids_0 (`list[int]`):
  132. List of IDs.
  133. token_ids_1 (`list[int]`, *optional*):
  134. Optional second list of IDs for sequence pairs.
  135. Returns:
  136. `list[int]`: List of zeros.
  137. """
  138. eos = [self.eos_token_id]
  139. if token_ids_1 is None:
  140. return len(token_ids_0 + eos) * [0]
  141. return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
  142. def build_inputs_with_special_tokens(
  143. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  144. ) -> list[int]:
  145. """
  146. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  147. adding special tokens. A sequence has the following format:
  148. - single sequence: `X </s>`
  149. - pair of sequences: `A </s> B </s>`
  150. Args:
  151. token_ids_0 (`list[int]`):
  152. List of IDs to which the special tokens will be added.
  153. token_ids_1 (`list[int]`, *optional*):
  154. Optional second list of IDs for sequence pairs.
  155. Returns:
  156. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  157. """
  158. token_ids_0 = self._add_eos_if_not_present(token_ids_0)
  159. if token_ids_1 is None:
  160. return token_ids_0
  161. else:
  162. token_ids_1 = self._add_eos_if_not_present(token_ids_1)
  163. return token_ids_0 + token_ids_1
  164. def _tokenize(self, text: str) -> list[str]:
  165. """Take as input a string and return a list of strings (tokens) for words/sub-words"""
  166. tokens = [chr(i) for i in text.encode("utf-8")]
  167. return tokens
  168. def _convert_token_to_id(self, token):
  169. """Converts a token (str) in an id using the vocab."""
  170. if len(token) != 1:
  171. token_id = None
  172. else:
  173. token_id = ord(token) + self.offset
  174. return token_id
  175. def _convert_id_to_token(self, index):
  176. """Converts an index (integer) in a token (str) using the vocab."""
  177. token = chr(index - self.offset)
  178. return token
  179. def convert_tokens_to_string(self, tokens):
  180. """Converts a sequence of tokens (string) in a single string."""
  181. bstring = b""
  182. for token in tokens:
  183. if token in self.added_tokens_decoder:
  184. tok_string = self.added_tokens_decoder[token].encode("utf-8")
  185. elif token in self.added_tokens_encoder:
  186. tok_string = token.encode("utf-8")
  187. else:
  188. tok_string = bytes([ord(token)])
  189. bstring += tok_string
  190. string = bstring.decode("utf-8", errors="ignore")
  191. return string
  192. # ByT5Tokenizer has no vocab file
  193. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  194. return ()
  195. __all__ = ["ByT5Tokenizer"]