tokenization_myt5.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # Copyright 2024
  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 MyT5."""
  15. import json
  16. import os
  17. import warnings
  18. from collections import defaultdict
  19. from ...tokenization_python import AddedToken, PreTrainedTokenizer
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. VOCAB_FILES_NAMES = {"vocab_file": "byte_maps.json"}
  23. class ByteRewriter:
  24. """
  25. Byte rewriter class for MyT5 tokenizer.
  26. This class is used to rewrite bytes using a hash tree. The hash tree is constructed from a set of rewriting rules.
  27. Args:
  28. rewriting_rules (`str` or `dict[str, str]`):
  29. A path to a json file containing the rewriting rules or a dictionary containing the rewriting rules.
  30. """
  31. LEAF = "[LEAF]"
  32. def __init__(self, rewriting_rules: str | dict[str, str]):
  33. if isinstance(rewriting_rules, str):
  34. with open(rewriting_rules, "r") as f:
  35. rewriting_rules = json.load(f)
  36. elif not isinstance(rewriting_rules, dict):
  37. raise TypeError(
  38. f"rewriting_rules should be either a path to json file or a dict, got {type(rewriting_rules)}"
  39. )
  40. self.hash_tree = self.construct_hash_tree(rewriting_rules)
  41. reverse_rewriting_rules = {v: k for k, v in rewriting_rules.items()}
  42. self.reverse_hash_tree = self.construct_hash_tree(reverse_rewriting_rules)
  43. def add_leaf(self, hash_tree: dict[str, dict | list[str]], byte_in_sequence: str, byte_out_sequence: str):
  44. """
  45. Add a leaf with the output byte sequence to the hash tree.
  46. """
  47. byte_in_list = byte_in_sequence.split(" ")
  48. byte_out_list = byte_out_sequence.split(" ")
  49. tree_pointer = hash_tree
  50. for b in byte_in_list:
  51. if b not in tree_pointer:
  52. tree_pointer[b] = {}
  53. tree_pointer = tree_pointer[b]
  54. tree_pointer[self.LEAF] = byte_out_list
  55. def construct_hash_tree(self, rewriting_rules: dict[str, str]) -> dict[str, dict | list[str]]:
  56. """
  57. Construct a hash tree for rewritten byte sequences.
  58. """
  59. hash_tree = defaultdict(dict)
  60. for b in (f"{x:02x}" for x in range(256)):
  61. hash_tree[b][self.LEAF] = [b]
  62. for in_sequence, out_sequence in rewriting_rules.items():
  63. self.add_leaf(hash_tree, in_sequence, out_sequence)
  64. return hash_tree
  65. def search_hash_tree(self, byte_sequence: list[str]) -> None | list[str]:
  66. """
  67. Search the hash tree and return the rewritten byte sequence if found.
  68. """
  69. tree_pointer = self.hash_tree
  70. for b in byte_sequence:
  71. if b in tree_pointer:
  72. tree_pointer = tree_pointer[b]
  73. else:
  74. return None
  75. return tree_pointer[self.LEAF]
  76. def rewrite_bytes(self, in_bytes: list[str], reverse=False) -> list[str]:
  77. """
  78. Rewrite a sequence of bytes using the hash tree.
  79. Args:
  80. in_bytes (`list[str]`): A list of bytes to be rewritten.
  81. reverse (`bool`): If True, decoding is performed with the reverse hash tree.
  82. Returns:
  83. `list[str]`: The rewritten byte sequence.
  84. """
  85. out_bytes = []
  86. b_start = 0
  87. b_end = 0
  88. while b_start < len(in_bytes):
  89. tree_pointer = self.hash_tree if not reverse else self.reverse_hash_tree
  90. for j in range(b_start, len(in_bytes)):
  91. b = in_bytes[j]
  92. if b in tree_pointer:
  93. tree_pointer = tree_pointer[b]
  94. elif j == b_start:
  95. cur_leaf = [b]
  96. b_end = j
  97. break
  98. else:
  99. break
  100. if self.LEAF in tree_pointer:
  101. cur_leaf = tree_pointer[self.LEAF]
  102. b_end = j
  103. out_bytes.extend(cur_leaf)
  104. b_start = b_end + 1
  105. return out_bytes
  106. class MyT5Tokenizer(PreTrainedTokenizer):
  107. """
  108. Construct a MyT5 tokenizer.
  109. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  110. this superclass for more information regarding those methods.
  111. Args:
  112. vocab_file (`str`): The file containing the byte rewriting rules.
  113. eos_token (`str`, *optional*, defaults to `"</s>"`):
  114. The end of sequence token.
  115. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  116. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  117. token instead.
  118. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  119. The token used for padding, for example when batching sequences of different lengths.
  120. extra_ids (`int`, *optional*, defaults to 125):
  121. Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
  122. accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
  123. indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
  124. like in ByT5 preprocessing see
  125. [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
  126. additional_special_tokens (`list[str]`, *optional*):
  127. Additional special tokens used by the tokenizer.
  128. """
  129. model_input_names = ["input_ids", "attention_mask"]
  130. vocab_files_names = VOCAB_FILES_NAMES
  131. def __init__(
  132. self,
  133. vocab_file,
  134. eos_token="</s>",
  135. unk_token="<unk>",
  136. pad_token="<pad>",
  137. extra_ids=125,
  138. additional_special_tokens=None,
  139. **kwargs,
  140. ) -> None:
  141. # Add extra_ids to the special token list
  142. if extra_ids > 0 and additional_special_tokens is None:
  143. additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
  144. elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
  145. # Check that we have the right number of extra_id special tokens
  146. extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
  147. if extra_tokens != extra_ids:
  148. raise ValueError(
  149. f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
  150. " provided to MyT5Tokenizer. In this case the additional_special_tokens must include the"
  151. " extra_ids tokens"
  152. )
  153. pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token
  154. eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token
  155. unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token
  156. # unk token needs to be in the vocab with correct index
  157. self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token}
  158. self.offset = len(self._added_tokens_decoder)
  159. self._utf_vocab_size = 2**8 # utf is 8 bits
  160. # Load byte maps
  161. self.byte_maps = json.load(open(vocab_file, "r"))
  162. self.decompose_rewriter = ByteRewriter(self.byte_maps["decompose_map"])
  163. self.merge_rewriter = ByteRewriter(self.byte_maps["merge_map"])
  164. super().__init__(
  165. eos_token=eos_token,
  166. unk_token=unk_token,
  167. pad_token=pad_token,
  168. extra_ids=0,
  169. additional_special_tokens=additional_special_tokens,
  170. **kwargs,
  171. )
  172. @property
  173. def vocab_size(self):
  174. return self._utf_vocab_size
  175. # Copied from transformers.models.byt5.tokenization_byt5.ByT5Tokenizer.get_vocab
  176. def get_vocab(self):
  177. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
  178. vocab.update(self.added_tokens_encoder)
  179. return vocab
  180. # Copied from transformers.models.byt5.tokenization_byt5.ByT5Tokenizer.get_special_tokens_mask
  181. def get_special_tokens_mask(
  182. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  183. ) -> list[int]:
  184. """
  185. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  186. special tokens using the tokenizer `prepare_for_model` method.
  187. Args:
  188. token_ids_0 (`list[int]`):
  189. List of IDs.
  190. token_ids_1 (`list[int]`, *optional*):
  191. Optional second list of IDs for sequence pairs.
  192. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  193. Whether or not the token list is already formatted with special tokens for the model.
  194. Returns:
  195. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  196. """
  197. if already_has_special_tokens:
  198. return super().get_special_tokens_mask(
  199. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  200. )
  201. # normal case: some special tokens
  202. if token_ids_1 is None:
  203. return ([0] * len(token_ids_0)) + [1]
  204. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  205. def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]:
  206. """Do not add eos again if user already added it."""
  207. if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
  208. warnings.warn(
  209. f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
  210. " eos tokens being added."
  211. )
  212. return token_ids
  213. else:
  214. return token_ids + [self.eos_token_id]
  215. def create_token_type_ids_from_sequences(
  216. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  217. ) -> list[int]:
  218. """
  219. Create a mask from the two sequences passed to be used in a sequence-pair classification task. MyT5 does not
  220. make use of token type ids, therefore a list of zeros is returned.
  221. Args:
  222. token_ids_0 (`list[int]`):
  223. List of IDs.
  224. token_ids_1 (`list[int]`, *optional*):
  225. Optional second list of IDs for sequence pairs.
  226. Returns:
  227. `list[int]`: List of zeros.
  228. """
  229. eos = [self.eos_token_id]
  230. if token_ids_1 is None:
  231. return len(token_ids_0 + eos) * [0]
  232. return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
  233. # Copied from transformers.models.byt5.tokenization_byt5.ByT5Tokenizer.build_inputs_with_special_tokens
  234. def build_inputs_with_special_tokens(
  235. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  236. ) -> list[int]:
  237. """
  238. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  239. adding special tokens. A sequence has the following format:
  240. - single sequence: `X </s>`
  241. - pair of sequences: `A </s> B </s>`
  242. Args:
  243. token_ids_0 (`list[int]`):
  244. List of IDs to which the special tokens will be added.
  245. token_ids_1 (`list[int]`, *optional*):
  246. Optional second list of IDs for sequence pairs.
  247. Returns:
  248. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  249. """
  250. token_ids_0 = self._add_eos_if_not_present(token_ids_0)
  251. if token_ids_1 is None:
  252. return token_ids_0
  253. else:
  254. token_ids_1 = self._add_eos_if_not_present(token_ids_1)
  255. return token_ids_0 + token_ids_1
  256. def _tokenize(self, text: str, **kwargs) -> list[str]:
  257. """Take as input a string and return a list of strings (tokens) for words/sub-words.
  258. Represents tokens in two character hex format"""
  259. tokens = [f"{i:02x}" for i in text.encode("utf-8")]
  260. tokens = self.morphological_encode(tokens)
  261. return tokens
  262. def _convert_token_to_id(self, token):
  263. """Converts a token (str) in an id using the vocab."""
  264. if len(token) != 2:
  265. token_id = None
  266. else:
  267. token_id = int(token, 16) + self.offset
  268. return token_id
  269. def _convert_id_to_token(self, index):
  270. """Converts an index (integer) in a token (str) using the vocab."""
  271. token = f"{index - self.offset:02x}"
  272. return token
  273. def morphological_encode(self, indices: list[str]) -> list[str]:
  274. # Decompose and merge morphological sequences
  275. indices = self.decompose_rewriter.rewrite_bytes(indices, reverse=False)
  276. indices = self.merge_rewriter.rewrite_bytes(indices, reverse=False)
  277. return indices
  278. def morphological_decode(self, indices: list[str]) -> list[str]:
  279. # Demerge and compose morphological sequences
  280. indices = self.merge_rewriter.rewrite_bytes(indices, reverse=True)
  281. indices = self.decompose_rewriter.rewrite_bytes(indices, reverse=True)
  282. return indices
  283. def convert_tokens_to_string(self, tokens):
  284. """Converts a sequence of tokens (string) in a single string."""
  285. bstring = b""
  286. out_tokens = []
  287. for token in tokens:
  288. if token in self.added_tokens_decoder:
  289. out_tokens.append(self.added_tokens_decoder[token])
  290. elif token in self.added_tokens_encoder:
  291. out_tokens.append(token)
  292. else:
  293. out_tokens.append(token)
  294. out_tokens = self.morphological_decode(out_tokens)
  295. _added_tokens = set(self.added_tokens_decoder.values()) | set(self.added_tokens_encoder)
  296. for token in out_tokens:
  297. if token in _added_tokens:
  298. bstring += bytes(token, "utf-8")
  299. else:
  300. bstring += bytes.fromhex(token)
  301. string = bstring.decode("utf-8", errors="ignore")
  302. return string
  303. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  304. if os.path.isdir(save_directory):
  305. vocab_file = os.path.join(
  306. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  307. )
  308. else:
  309. vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
  310. with open(vocab_file, "w", encoding="utf-8") as writer:
  311. writer.write(json.dumps(self.byte_maps, indent=2, ensure_ascii=False))
  312. return (vocab_file,)
  313. __all__ = ["MyT5Tokenizer"]