tokenizer.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import os
  2. from pathlib import Path
  3. from typing import Optional, Union
  4. import huggingface_hub
  5. from loguru import logger
  6. from transformers import (AutoTokenizer, PreTrainedTokenizer,
  7. PreTrainedTokenizerFast)
  8. from aphrodite.common.config import APHRODITE_USE_MODELSCOPE
  9. from aphrodite.common.utils import make_async
  10. from aphrodite.lora.request import LoRARequest
  11. from aphrodite.transformers_utils.tokenizers import BaichuanTokenizer
  12. from aphrodite.transformers_utils.utils import check_gguf_file
  13. def get_cached_tokenizer(
  14. tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
  15. ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  16. """Get tokenizer with cached properties.
  17. This will patch the tokenizer object in place.
  18. By default, transformers will recompute multiple tokenizer properties
  19. each time they are called, leading to a significant slowdown. This
  20. function caches these properties for faster access."""
  21. tokenizer_all_special_ids = set(tokenizer.all_special_ids)
  22. tokenizer_all_special_tokens_extended = (
  23. tokenizer.all_special_tokens_extended)
  24. tokenizer_all_special_tokens = set(tokenizer.all_special_tokens)
  25. tokenizer_len = len(tokenizer)
  26. class CachedTokenizer(tokenizer.__class__): # type: ignore
  27. @property
  28. def all_special_ids(self):
  29. return tokenizer_all_special_ids
  30. @property
  31. def all_special_tokens(self):
  32. return tokenizer_all_special_tokens
  33. @property
  34. def all_special_tokens_extended(self):
  35. return tokenizer_all_special_tokens_extended
  36. def __len__(self):
  37. return tokenizer_len
  38. CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"
  39. tokenizer.__class__ = CachedTokenizer
  40. return tokenizer
  41. def get_tokenizer(
  42. tokenizer_name: Union[str, Path],
  43. *args,
  44. tokenizer_mode: str = "auto",
  45. trust_remote_code: bool = False,
  46. revision: Optional[str] = None,
  47. download_dir: Optional[str] = None,
  48. **kwargs,
  49. ) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  50. """Gets a tokenizer for the given model name via Huggingface/modelscope."""
  51. if APHRODITE_USE_MODELSCOPE:
  52. # download model from ModelScope hub,
  53. # lazy import so that modelscope is not required for normal use.
  54. # pylint: disable=C.
  55. from modelscope.hub.snapshot_download import snapshot_download
  56. # Only set the tokenizer here, model will be downloaded on the workers.
  57. if not os.path.exists(tokenizer_name):
  58. tokenizer_path = snapshot_download(
  59. model_id=tokenizer_name,
  60. cache_dir=download_dir,
  61. revision=revision,
  62. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  63. # Ignore weights - we only need the tokenizer.
  64. ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"])
  65. tokenizer_name = tokenizer_path
  66. if tokenizer_mode == "slow":
  67. if kwargs.get("use_fast", False):
  68. raise ValueError(
  69. "Cannot use the fast tokenizer in slow tokenizer mode.")
  70. kwargs["use_fast"] = False
  71. if "truncation_side" not in kwargs:
  72. kwargs["truncation_side"] = "left"
  73. # Separate model folder from file path for GGUF models
  74. is_gguf = check_gguf_file(tokenizer_name)
  75. if is_gguf:
  76. kwargs["gguf_file"] = Path(tokenizer_name).name
  77. tokenizer_name = Path(tokenizer_name).parent
  78. try:
  79. tokenizer = AutoTokenizer.from_pretrained(
  80. tokenizer_name,
  81. *args,
  82. trust_remote_code=trust_remote_code,
  83. revision=revision,
  84. **kwargs)
  85. except ValueError as e:
  86. # If the error pertains to the tokenizer class not existing or not
  87. # currently being imported, suggest using the --trust-remote-code flag.
  88. if (not trust_remote_code and
  89. ("does not exist or is not currently imported." in str(e)
  90. or "requires you to execute the tokenizer file" in str(e))):
  91. err_msg = (
  92. "Failed to load the tokenizer. If the tokenizer is a custom "
  93. "tokenizer not yet available in the HuggingFace transformers "
  94. "library, consider setting `trust_remote_code=True` in LLM "
  95. "or using the `--trust-remote-code` flag in the CLI.")
  96. raise RuntimeError(err_msg) from e
  97. else:
  98. raise e
  99. except AttributeError as e:
  100. if "BaichuanTokenizer" in str(e):
  101. # This is for the error "'BaichuanTokenizer' object has no
  102. # attribute 'sp_model'".
  103. tokenizer = BaichuanTokenizer.from_pretrained(
  104. tokenizer_name,
  105. *args,
  106. trust_remote_code=trust_remote_code,
  107. revision=revision,
  108. **kwargs)
  109. else:
  110. raise e
  111. if not isinstance(tokenizer, PreTrainedTokenizerFast):
  112. logger.warning(
  113. "Using a slow tokenizer. This might cause a significant "
  114. "slowdown. Consider using a fast tokenizer instead.")
  115. return get_cached_tokenizer(tokenizer)
  116. def get_lora_tokenizer(lora_request: LoRARequest, *args,
  117. **kwargs) -> Optional[PreTrainedTokenizer]:
  118. if lora_request is None:
  119. return None
  120. try:
  121. tokenizer = get_tokenizer(lora_request.lora_path, *args, **kwargs)
  122. except OSError as e:
  123. # No tokenizer was found in the LoRA folder,
  124. # use base model tokenizer
  125. logger.warning(f"No tokenizer found in {lora_request.lora_path}, "
  126. "using base model tokenizer instead. "
  127. f"(Exception: {str(e)})")
  128. tokenizer = None
  129. return tokenizer
  130. get_lora_tokenizer_async = make_async(get_lora_tokenizer)