tokenization_dia.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. # Copyright 2025 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 Dia."""
  15. from ...tokenization_python import AddedToken, PreTrainedTokenizer
  16. from ...utils import logging
  17. logger = logging.get_logger(__name__)
  18. class DiaTokenizer(PreTrainedTokenizer):
  19. """
  20. Construct a Dia tokenizer. Dia simply uses raw bytes utf-8 encoding except for special tokens `[S1]` and `[S2]`.
  21. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  22. refer to 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. unk_token (`str`, *optional*, defaults to `"<pad>"`):
  27. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  28. token instead.
  29. max_length (`int`, *optional*, defaults to 1024):
  30. The maximum length of the sequences when encoding. Sequences longer than this will be truncated.
  31. offset (`int`, *optional*, defaults to 0):
  32. The offset of the tokenizer.
  33. """
  34. model_input_names = ["input_ids", "attention_mask"]
  35. def __init__(
  36. self,
  37. pad_token: str | None = "<pad>",
  38. unk_token: str | None = "<pad>",
  39. max_length: int | None = 1024,
  40. offset: int = 0,
  41. **kwargs,
  42. ):
  43. # We have no eos/bos tokens but allow padding -- no l/r strip as we treat them as tokens as well
  44. pad_token = AddedToken(pad_token) if isinstance(pad_token, str) else pad_token
  45. unk_token = AddedToken(unk_token) if isinstance(unk_token, str) else unk_token
  46. self._utf_vocab_size = 2**8 # utf is 8 bits
  47. self._added_tokens_decoder = {0: pad_token, 1: AddedToken("[S1]"), 2: AddedToken("[S2]")}
  48. self.offset = offset
  49. super().__init__(
  50. unk_token=unk_token,
  51. pad_token=pad_token,
  52. max_length=max_length,
  53. offset=offset,
  54. token_type_ids_pattern="all_zeros",
  55. token_type_ids_include_special_tokens=True,
  56. special_tokens_pattern="none",
  57. **kwargs,
  58. )
  59. @property
  60. def vocab_size(self):
  61. return self._utf_vocab_size
  62. def get_vocab(self):
  63. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
  64. vocab.update(self.added_tokens_encoder)
  65. return vocab
  66. def _tokenize(self, text: str) -> list[str]:
  67. """Take as input a string and return a list of strings (tokens) for words/sub-words"""
  68. tokens = [chr(i) for i in text.encode("utf-8")]
  69. return tokens
  70. def _convert_token_to_id(self, token):
  71. """Converts a token (str) in an id using the vocab."""
  72. if len(token) != 1:
  73. token_id = None
  74. else:
  75. token_id = ord(token) + self.offset
  76. return token_id
  77. def _convert_id_to_token(self, index):
  78. """Converts an index (integer) in a token (str) using the vocab."""
  79. token = chr(index - self.offset)
  80. return token
  81. def convert_tokens_to_string(self, tokens: list[str]) -> str:
  82. """Converts a sequence of tokens (string) in a single string."""
  83. bstring = b""
  84. for token in tokens:
  85. if token in self.added_tokens_decoder:
  86. added_token_obj = self.added_tokens_decoder[token]
  87. tok_string = str(added_token_obj).encode("utf-8")
  88. elif token in self.added_tokens_encoder:
  89. tok_string = token.encode("utf-8")
  90. else:
  91. tok_string = token.encode("utf-8") # Assume general string token
  92. bstring += tok_string
  93. string = bstring.decode("utf-8", errors="ignore")
  94. return string
  95. __all__ = ["DiaTokenizer"]