utils.py 6.1 KB

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