tokenization_perceiver.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # Copyright 2021 The 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 Perceiver."""
  15. from ...tokenization_python import AddedToken, PreTrainedTokenizer
  16. from ...utils import logging
  17. logger = logging.get_logger(__name__)
  18. class PerceiverTokenizer(PreTrainedTokenizer):
  19. """
  20. Construct a Perceiver tokenizer. The Perceiver simply uses raw bytes utf-8 encoding.
  21. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  22. this superclass for more information regarding those methods.
  23. Args:
  24. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  25. The token used for padding, for example when batching sequences of different lengths.
  26. bos_token (`str`, *optional*, defaults to `"[BOS]"`):
  27. The BOS token (reserved in the vocab, but not actually used).
  28. eos_token (`str`, *optional*, defaults to `"[EOS]"`):
  29. The end of sequence token (reserved in the vocab, but not actually used).
  30. <Tip>
  31. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  32. The token used is the `sep_token`.
  33. </Tip>
  34. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  35. The MASK token, useful for masked language modeling.
  36. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  37. The CLS token (reserved in the vocab, but not actually used).
  38. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  39. The separator token, which is used when building a sequence from two sequences.
  40. """
  41. model_input_names = ["input_ids", "attention_mask"]
  42. def __init__(
  43. self,
  44. pad_token="[PAD]",
  45. bos_token="[BOS]",
  46. eos_token="[EOS]",
  47. mask_token="[MASK]",
  48. cls_token="[CLS]",
  49. sep_token="[SEP]",
  50. model_max_length=2048,
  51. **kwargs,
  52. ) -> None:
  53. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  54. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  55. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  56. mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
  57. cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
  58. sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
  59. self._utf_vocab_size = 2**8 # utf is 8 bits
  60. # Since these tokens are not part of the vocabulary, we manually add them
  61. self._added_tokens_decoder: dict[str, int] = {
  62. 0: pad_token,
  63. 1: bos_token,
  64. 2: eos_token,
  65. 3: mask_token,
  66. 4: cls_token,
  67. 5: sep_token,
  68. }
  69. self._num_special_tokens = len(self._added_tokens_decoder)
  70. super().__init__(
  71. pad_token=pad_token,
  72. bos_token=bos_token,
  73. eos_token=eos_token,
  74. mask_token=mask_token,
  75. cls_token=cls_token,
  76. sep_token=sep_token,
  77. model_max_length=model_max_length,
  78. **kwargs,
  79. )
  80. def get_vocab(self) -> dict[str, int]:
  81. vocab = {}
  82. for i in range(self._utf_vocab_size):
  83. token = chr(i)
  84. vocab[token] = i + self._num_special_tokens
  85. vocab.update(self.added_tokens_encoder)
  86. return vocab
  87. @property
  88. def vocab_size(self):
  89. return self._utf_vocab_size
  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 [1] + [0] * len(token_ids_0) + [1]
  113. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  114. def build_inputs_with_special_tokens(
  115. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  116. ) -> list[int]:
  117. """
  118. Build model inputs from a sequence or a pair of sequence for sequence classification tasks. A sequence has the
  119. following format:
  120. - single sequence: `[CLS] X [SEP]`
  121. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  122. Args:
  123. token_ids_0 (`list[int]`):
  124. List of IDs to which the special tokens will be added.
  125. token_ids_1 (`list[int]`, *optional*):
  126. Optional second list of IDs for sequence pairs.
  127. Returns:
  128. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  129. """
  130. if token_ids_1 is None:
  131. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  132. else:
  133. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1 + [self.sep_token_id]
  134. def _tokenize(self, text: str) -> list[str]:
  135. """Take as input a string and return a list of strings (tokens) for words/sub-words"""
  136. tokens = [chr(i) for i in text.encode("utf-8")]
  137. return tokens
  138. def _convert_token_to_id(self, token):
  139. """Converts a token (str) in an id using the vocab."""
  140. if len(token) != 1:
  141. token_id = self.unk_token_id
  142. else:
  143. token_id = ord(token) + self._num_special_tokens
  144. return token_id
  145. def _convert_id_to_token(self, index):
  146. """Converts an index (integer) in a token (str) using the vocab."""
  147. token = chr(index - self._num_special_tokens)
  148. return token
  149. # TODO @ArthurZ refactor this as well....
  150. def convert_tokens_to_string(self, tokens):
  151. """Converts a sequence of tokens (string) in a single string."""
  152. bstring = b""
  153. for token in tokens:
  154. if token in self.added_tokens_encoder:
  155. tok_string = str(token).encode("utf-8")
  156. else:
  157. tok_string = bytes([ord(token)])
  158. bstring += tok_string
  159. string = bstring.decode("utf-8", errors="replace")
  160. return string
  161. # PerceiverTokenizer has no vocab file
  162. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  163. return ()
  164. __all__ = ["PerceiverTokenizer"]