1
0

tokenizer.py 5.3 KB

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