utils.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import os
  2. from typing import List, Optional, Set, Tuple, Type
  3. import huggingface_hub
  4. from huggingface_hub.utils import (EntryNotFoundError, HfHubHTTPError,
  5. HFValidationError, RepositoryNotFoundError)
  6. from loguru import logger
  7. from torch import nn
  8. from transformers import PretrainedConfig
  9. from aphrodite.common.config import LoRAConfig
  10. from aphrodite.lora.fully_sharded_layers import (
  11. ColumnParallelLinearWithShardedLoRA,
  12. MergedColumnParallelLinearWithShardedLoRA,
  13. MergedQKVParallelLinearWithShardedLora, QKVParallelLinearWithShardedLora,
  14. RowParallelLinearWithShardedLoRA)
  15. # being imported for _all_lora_classes below
  16. # yapf conflicts with isort for this block
  17. # yapf: disable
  18. from aphrodite.lora.layers import (BaseLayerWithLoRA,
  19. ColumnParallelLinearWithLoRA,
  20. LinearScalingRotaryEmbeddingWithLora,
  21. LogitsProcessorWithLoRA,
  22. MergedColumnParallelLinearWithLoRA,
  23. MergedQKVParallelLinearWithLora,
  24. QKVParallelLinearWithLora,
  25. RowParallelLinearWithLoRA,
  26. VocabParallelEmbeddingWithLoRA)
  27. # yapf: enable
  28. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  29. from aphrodite.modeling.layers.vocab_parallel_embedding import ParallelLMHead
  30. _all_lora_classes: Set[Type[BaseLayerWithLoRA]] = {
  31. VocabParallelEmbeddingWithLoRA,
  32. ColumnParallelLinearWithLoRA,
  33. MergedColumnParallelLinearWithLoRA,
  34. QKVParallelLinearWithLora,
  35. MergedQKVParallelLinearWithLora,
  36. RowParallelLinearWithLoRA,
  37. LogitsProcessorWithLoRA,
  38. ColumnParallelLinearWithShardedLoRA,
  39. QKVParallelLinearWithShardedLora,
  40. MergedColumnParallelLinearWithShardedLoRA,
  41. MergedQKVParallelLinearWithShardedLora,
  42. RowParallelLinearWithShardedLoRA,
  43. LinearScalingRotaryEmbeddingWithLora,
  44. }
  45. def from_layer(layer: nn.Module,
  46. max_loras: int,
  47. lora_config: LoRAConfig,
  48. packed_modules_list: List,
  49. model_config: Optional[PretrainedConfig] = None) -> nn.Module:
  50. for lora_cls in _all_lora_classes:
  51. # specifying kwargs so they can be easily accessed in decorator
  52. if lora_cls.can_replace_layer(source_layer=layer,
  53. lora_config=lora_config,
  54. packed_modules_list=packed_modules_list,
  55. model_config=model_config):
  56. ret = lora_cls(layer)
  57. ret.create_lora_weights(max_loras, lora_config, model_config)
  58. return ret
  59. return layer
  60. def from_layer_logits_processor(
  61. layer: LogitsProcessor,
  62. lm_head: ParallelLMHead,
  63. max_loras: int,
  64. lora_config: LoRAConfig,
  65. model_config: Optional[PretrainedConfig] = None,
  66. ) -> LogitsProcessorWithLoRA:
  67. ret = LogitsProcessorWithLoRA(layer, lm_head.embedding_dim,
  68. lm_head.weight.dtype, lm_head.weight.device,
  69. lm_head.get_sharded_to_full_mapping())
  70. ret.create_lora_weights(max_loras, lora_config, model_config)
  71. return ret
  72. def replace_submodule(model: nn.Module, module_name: str,
  73. new_module: nn.Module) -> nn.Module:
  74. """Replace a submodule in a model with a new module."""
  75. parent = model.get_submodule(".".join(module_name.split(".")[:-1]))
  76. target_name = module_name.split(".")[-1]
  77. setattr(parent, target_name, new_module)
  78. return new_module
  79. def parse_fine_tuned_lora_name(name: str) -> Tuple[str, bool]:
  80. """Parse the name of lora weights.
  81. args:
  82. name: the name of the fine-tuned LoRA, e.g.
  83. base_model.model.dense1.weight
  84. return:
  85. Tuple(module_name, is_lora_a):
  86. module_name: the name of the module, e.g. model.dense1,
  87. is_lora_a whether the tensor is lora_a or lora_b.
  88. """
  89. parts = name.split(".")
  90. if len(parts) >= 2 and parts[0] == "base_model" and parts[1] == "model":
  91. if parts[-1] == "weight":
  92. if parts[-2] == "lora_A" or parts[-2] == "lora_B":
  93. return ".".join(parts[2:-2]), parts[-2] == "lora_A"
  94. elif parts[-1] == "lora_embedding_A" or parts[-1] == "lora_embedding_B":
  95. return ".".join(parts[2:-1]), parts[-1] == "lora_embedding_A"
  96. raise ValueError(f"{name} is unsupported LoRA weight")
  97. def get_adapter_absolute_path(lora_path: str) -> str:
  98. """
  99. Resolves the given lora_path to an absolute local path.
  100. If the lora_path is identified as a Hugging Face model identifier,
  101. it will download the model and return the local snapshot path.
  102. Otherwise, it treats the lora_path as a local file path and
  103. converts it to an absolute path.
  104. Parameters:
  105. lora_path (str): The path to the lora model, which can be an absolute path,
  106. a relative path, or a Hugging Face model identifier.
  107. Returns:
  108. str: The resolved absolute local path to the lora model.
  109. """
  110. # Check if the path is an absolute path. Return it no matter exists or not.
  111. if os.path.isabs(lora_path):
  112. return lora_path
  113. # If the path starts with ~, expand the user home directory.
  114. if lora_path.startswith('~'):
  115. return os.path.expanduser(lora_path)
  116. # Check if the expanded relative path exists locally.
  117. if os.path.exists(lora_path):
  118. return os.path.abspath(lora_path)
  119. # If the path does not exist locally, assume it's a Hugging Face repo.
  120. try:
  121. local_snapshot_path = huggingface_hub.snapshot_download(
  122. repo_id=lora_path)
  123. except (HfHubHTTPError, RepositoryNotFoundError, EntryNotFoundError,
  124. HFValidationError):
  125. # Handle errors that may occur during the download
  126. # Return original path instead instead of throwing error here
  127. logger.exception("Error downloading the HuggingFace model")
  128. return lora_path
  129. return local_snapshot_path