tokenization_dia.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # coding=utf-8
  2. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization class for Dia."""
  16. from typing import Optional
  17. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class DiaTokenizer(PreTrainedTokenizer):
  21. """
  22. Construct a Dia tokenizer. Dia simply uses raw bytes utf-8 encoding except for special tokens `[S1]` and `[S2]`.
  23. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  24. refer to this superclass for more information regarding those methods.
  25. Args:
  26. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  27. The token used for padding, for example when batching sequences of different lengths.
  28. unk_token (`str`, *optional*, defaults to `"<pad>"`):
  29. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  30. token instead.
  31. max_length (`int`, *optional*, defaults to 1024):
  32. The maximum length of the sequences when encoding. Sequences longer than this will be truncated.
  33. offset (`int`, *optional*, defaults to 0):
  34. The offset of the tokenizer.
  35. """
  36. model_input_names = ["input_ids", "attention_mask"]
  37. def __init__(
  38. self,
  39. pad_token: Optional[str] = "<pad>",
  40. unk_token: Optional[str] = "<pad>",
  41. max_length: Optional[int] = 1024,
  42. offset: int = 0,
  43. **kwargs,
  44. ):
  45. # We have no eos/bos tokens but allow padding -- no l/r strip as we treat them as tokens as well
  46. pad_token = AddedToken(pad_token) if isinstance(pad_token, str) else pad_token
  47. unk_token = AddedToken(unk_token) if isinstance(unk_token, str) else unk_token
  48. self._utf_vocab_size = 2**8 # utf is 8 bits
  49. self._added_tokens_decoder = {0: pad_token, 1: AddedToken("[S1]"), 2: AddedToken("[S2]")}
  50. self.offset = offset
  51. super().__init__(
  52. unk_token=unk_token,
  53. pad_token=pad_token,
  54. max_length=max_length,
  55. **kwargs,
  56. )
  57. @property
  58. def vocab_size(self):
  59. return self._utf_vocab_size
  60. def get_vocab(self):
  61. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
  62. vocab.update(self.added_tokens_encoder)
  63. return vocab
  64. def _tokenize(self, text: str) -> list[str]:
  65. """Take as input a string and return a list of strings (tokens) for words/sub-words"""
  66. tokens = [chr(i) for i in text.encode("utf-8")]
  67. return tokens
  68. def _convert_token_to_id(self, token):
  69. """Converts a token (str) in an id using the vocab."""
  70. if len(token) != 1:
  71. token_id = None
  72. else:
  73. token_id = ord(token) + self.offset
  74. return token_id
  75. def _convert_id_to_token(self, index):
  76. """Converts an index (integer) in a token (str) using the vocab."""
  77. token = chr(index - self.offset)
  78. return token
  79. def convert_tokens_to_string(self, tokens: list[str]) -> str:
  80. """Converts a sequence of tokens (string) in a single string."""
  81. bstring = b""
  82. for token in tokens:
  83. if token in self.added_tokens_decoder:
  84. added_token_obj = self.added_tokens_decoder[token]
  85. tok_string = str(added_token_obj).encode("utf-8")
  86. elif token in self.added_tokens_encoder:
  87. tok_string = token.encode("utf-8")
  88. else:
  89. tok_string = token.encode("utf-8") # Assume general string token
  90. bstring += tok_string
  91. string = bstring.decode("utf-8", errors="ignore")
  92. return string
  93. # No vocab file
  94. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  95. return ()
  96. __all__ = ["DiaTokenizer"]