tokenizer.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import os
  2. import tempfile
  3. from typing import Optional, Union
  4. from transformers import (AutoTokenizer, PreTrainedTokenizer,
  5. PreTrainedTokenizerFast, LlamaTokenizer)
  6. from transformers.convert_slow_tokenizer import import_protobuf
  7. from loguru import logger
  8. from aphrodite.lora.request import LoRARequest
  9. from aphrodite.common.utils import make_async
  10. from aphrodite.common.gguf import GGUFReader
  11. from aphrodite.transformers_utils.tokenizers import BaichuanTokenizer
  12. def convert_gguf_to_tokenizer(checkpoint):
  13. result = GGUFReader(checkpoint)
  14. # write vocab
  15. sentencepiece_model_pb2 = import_protobuf()
  16. vocab = sentencepiece_model_pb2.ModelProto()
  17. vocab_size = len(result.fields['tokenizer.ggml.token_type'].data)
  18. vocab.trainer_spec.model_type = 2 # BPE
  19. vocab.trainer_spec.vocab_size = vocab_size
  20. vocab.trainer_spec.byte_fallback = True
  21. vocab.normalizer_spec.remove_extra_whitespaces = False
  22. tokens = result.fields['tokenizer.ggml.tokens']
  23. scores = result.fields['tokenizer.ggml.scores']
  24. types = result.fields['tokenizer.ggml.token_type']
  25. for i in range(vocab_size):
  26. new_token = vocab.SentencePiece()
  27. new_token.piece = str(bytes(tokens.parts[tokens.data[i]]),
  28. encoding='utf-8')
  29. new_token.score = scores.parts[scores.data[i]]
  30. # llama.cpp tokentype is the same with sentencepiece token type
  31. new_token.type = int(types.parts[types.data[i]])
  32. vocab.pieces.append(new_token)
  33. with tempfile.NamedTemporaryFile(mode='wb', delete=False) as temp_file:
  34. temp_file.write(vocab.SerializeToString())
  35. temp_file_filename = temp_file.name
  36. tokenizer_args = {"vocab_file": temp_file_filename}
  37. if 'tokenizer.ggml.bos_token_id' in result.fields:
  38. tokenizer_args["bos_token"] = vocab.pieces[int(
  39. result.fields['tokenizer.ggml.bos_token_id'].parts[-1])].piece
  40. if 'tokenizer.ggml.eos_token_id' in result.fields:
  41. tokenizer_args["eos_token"] = vocab.pieces[int(
  42. result.fields['tokenizer.ggml.eos_token_id'].parts[-1])].piece
  43. if 'tokenizer.ggml.padding_token_id' in result.fields:
  44. tokenizer_args["pad_token"] = vocab.pieces[int(
  45. result.fields['tokenizer.ggml.padding_token_id'].parts[-1])].piece
  46. if 'tokenizer.ggml.unknown_token_id' in result.fields:
  47. tokenizer_args["unk_token"] = vocab.pieces[int(
  48. result.fields['tokenizer.ggml.unknown_token_id'].parts[-1])].piece
  49. if 'tokenizer.ggml.add_bos_token' in result.fields:
  50. tokenizer_args["add_bos_token"] = bool(
  51. result.fields['tokenizer.ggml.add_bos_token'].parts[-1])
  52. if 'tokenizer.ggml.add_eos_token' in result.fields:
  53. tokenizer_args["add_eos_token"] = bool(
  54. result.fields['tokenizer.ggml.add_eos_token'].parts[-1])
  55. if 'tokenizer.chat_template' in result.fields:
  56. tokenizer_args["chat_template"] = str(
  57. bytes(result.fields['tokenizer.chat_template'].parts[-1]))
  58. tokenizer = LlamaTokenizer(**tokenizer_args)
  59. os.unlink(temp_file_filename)
  60. return tokenizer
  61. def get_cached_tokenizer(
  62. tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
  63. ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  64. """Get tokenizer with cached properties.
  65. This will patch the tokenizer object in place.
  66. By default, transformers will recompute multiple tokenizer
  67. properties each time they are called, leading to a significant
  68. slowdown. This function caches these properties for faster
  69. access."""
  70. tokenizer_all_special_ids = set(tokenizer.all_special_ids)
  71. tokenizer_all_special_tokens_extended = (
  72. tokenizer.all_special_tokens_extended)
  73. tokenizer_all_special_tokens = set(tokenizer.all_special_tokens)
  74. tokenizer_len = len(tokenizer)
  75. class CachedTokenizer(tokenizer.__class__):
  76. @property
  77. def all_special_ids(self):
  78. return tokenizer_all_special_ids
  79. @property
  80. def all_special_tokens(self):
  81. return tokenizer_all_special_tokens
  82. @property
  83. def all_special_tokens_extended(self):
  84. return tokenizer_all_special_tokens_extended
  85. def __len__(self):
  86. return tokenizer_len
  87. CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"
  88. tokenizer.__class__ = CachedTokenizer
  89. return tokenizer
  90. def get_tokenizer(
  91. tokenizer_name: str,
  92. *args,
  93. tokenizer_mode: str = "auto",
  94. trust_remote_code: bool = False,
  95. tokenizer_revision: Optional[str] = None,
  96. **kwargs,
  97. ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  98. """Gets a tokenizer for the given model name via Huggingface."""
  99. if tokenizer_name.endswith("gguf"):
  100. return convert_gguf_to_tokenizer(tokenizer_name)
  101. if tokenizer_mode == "slow":
  102. if kwargs.get("use_fast", False):
  103. raise ValueError(
  104. "Cannot use the fast tokenizer in slow tokenizer mode.")
  105. kwargs["use_fast"] = False
  106. try:
  107. tokenizer = AutoTokenizer.from_pretrained(
  108. tokenizer_name,
  109. *args,
  110. trust_remote_code=trust_remote_code,
  111. tokenizer_revision=tokenizer_revision,
  112. **kwargs)
  113. except ValueError as e:
  114. # If the error pertains to the tokenizer class not existing or not
  115. # currently being imported, suggest using the --trust-remote-code flag.
  116. if (not trust_remote_code and
  117. ("does not exist or is not currently imported." in str(e)
  118. or "requires you to execute the tokenizer file" in str(e))):
  119. err_msg = (
  120. "Failed to load the tokenizer. If the tokenizer is a custom "
  121. "tokenizer not yet available in the HuggingFace transformers "
  122. "library, consider setting `trust_remote_code=True` in LLM "
  123. "or using the `--trust-remote-code` flag in the CLI.")
  124. raise RuntimeError(err_msg) from e
  125. else:
  126. raise e
  127. except AttributeError as e:
  128. if "BaichuanTokenizer" in str(e):
  129. # This is for the error "'BaichuanTokenizer' object has no
  130. # attribute 'sp_model'".
  131. tokenizer = BaichuanTokenizer.from_pretrained(
  132. tokenizer_name,
  133. *args,
  134. trust_remote_code=trust_remote_code,
  135. tokenizer_revision=tokenizer_revision,
  136. **kwargs)
  137. else:
  138. raise e
  139. if not isinstance(tokenizer, PreTrainedTokenizerFast):
  140. logger.warning(
  141. "Using a slow tokenizer. This might cause a significant "
  142. "slowdown. Consider using a fast tokenizer instead.")
  143. return get_cached_tokenizer(tokenizer)
  144. def get_lora_tokenizer(lora_request: LoRARequest, *args,
  145. **kwargs) -> Optional[PreTrainedTokenizer]:
  146. if lora_request is None:
  147. return None
  148. try:
  149. tokenizer = get_tokenizer(lora_request.lora_local_path, *args,
  150. **kwargs)
  151. except OSError as e:
  152. # No tokenizer was found in the LoRA folder,
  153. # use base model tokenizer
  154. logger.warning(
  155. f"No tokenizer found in {lora_request.lora_local_path}, "
  156. "using base model tokenizer instead. "
  157. f"(Exception: {str(e)})")
  158. tokenizer = None
  159. return tokenizer
  160. get_lora_tokenizer_async = make_async(get_lora_tokenizer)