models.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. import copy
  2. import json
  3. import math
  4. import os
  5. import re
  6. from dataclasses import dataclass, field
  7. from typing import Any, Callable, Dict, List, Optional, Type
  8. import safetensors.torch
  9. import torch
  10. from loguru import logger
  11. from torch import nn
  12. from aphrodite.adapter_commons.models import (AdapterLRUCache, AdapterModel,
  13. AdapterModelManager)
  14. from aphrodite.adapter_commons.utils import (add_adapter, deactivate_adapter,
  15. get_adapter, list_adapters,
  16. remove_adapter,
  17. set_adapter_mapping)
  18. from aphrodite.common.config import LoRAConfig
  19. from aphrodite.common.utils import is_pin_memory_available
  20. from aphrodite.lora.layers import (BaseLayerWithLoRA,
  21. LinearScalingRotaryEmbeddingWithLora,
  22. LoRAMapping)
  23. from aphrodite.lora.lora import LoRALayerWeights, PackedLoRALayerWeights
  24. from aphrodite.lora.punica import PunicaWrapper
  25. from aphrodite.lora.utils import (from_layer, from_layer_logits_processor,
  26. parse_fine_tuned_lora_name,
  27. replace_submodule)
  28. from aphrodite.modeling.models.interfaces import SupportsLoRA
  29. from aphrodite.modeling.models.utils import PPMissingLayer
  30. _GLOBAL_LORA_ID = 0
  31. @dataclass
  32. class LongContextLoRAContext:
  33. """Context for lora adapters that support long context."""
  34. # The scaling factors to support long context lora fine tuned models.
  35. scaling_factors: List[float]
  36. # dimension to apply rotary embedding.
  37. rot_dim: int
  38. # offsets to the sin_cos_cache for each lora_id loaded.
  39. # This value is dynamically modified.
  40. offsets_by_lora_id: Dict[int, int] = field(default_factory=dict)
  41. def get_lora_id():
  42. global _GLOBAL_LORA_ID
  43. _GLOBAL_LORA_ID += 1
  44. return _GLOBAL_LORA_ID
  45. class LoRAModel(AdapterModel):
  46. """A LoRA fine-tuned model."""
  47. def __init__(
  48. self,
  49. lora_model_id: int,
  50. rank: int,
  51. loras: Dict[str, LoRALayerWeights],
  52. scaling_factor: Optional[float] = None,
  53. ) -> None:
  54. """
  55. Args:
  56. lora_model_id: The integer id for the lora model.
  57. rank: lora rank.
  58. loras: module name -> weights for lora-replaced layers.
  59. scaling_factor: Scaling factor to support long context lora model.
  60. None if the lora is not tuned for long context support.
  61. """
  62. self.id = lora_model_id
  63. # Scaling factor for long context lora model. None if it is not
  64. # fine tuned for the long context.
  65. self.scaling_factor = scaling_factor
  66. assert (lora_model_id >
  67. 0), f"a valid lora id should be greater than 0, got {self.id}"
  68. self.rank = rank
  69. self.loras: Dict[str, LoRALayerWeights] = loras
  70. def clone(self, lora_model_id: int) -> "LoRAModel":
  71. """Return a copy of the object with different ids.
  72. Will share the underlying tensors."""
  73. return self.__class__(
  74. lora_model_id,
  75. rank=self.rank,
  76. loras=self.loras.copy(),
  77. )
  78. @property
  79. def extra_vocab_size(self) -> int:
  80. return max(lora.extra_vocab_size
  81. for lora in self.loras.values()) if self.loras else 0
  82. def get_lora(self, module_name: str) -> Optional[LoRALayerWeights]:
  83. """Get LoRA for a given module by name"""
  84. return self.loras.get(module_name, None)
  85. # (yard1): TODO see if we can derive target_embedding_padding automatically
  86. @classmethod
  87. def from_lora_tensors(
  88. cls,
  89. lora_model_id: int,
  90. rank: int,
  91. lora_alpha: int,
  92. tensors: Dict[str, torch.Tensor],
  93. device: str = "cuda",
  94. dtype: Optional[torch.dtype] = None,
  95. embeddings: Optional[Dict[str, torch.Tensor]] = None,
  96. target_embedding_padding: Optional[int] = None,
  97. scaling_factor: Optional[float] = None,
  98. embedding_modules: Optional[Dict[str, str]] = None,
  99. embedding_padding_modules: Optional[List[str]] = None,
  100. ) -> "LoRAModel":
  101. """Create a LoRAModel from a dictionary of tensors."""
  102. pin_memory = str(device) == "cpu" and is_pin_memory_available()
  103. loras: Dict[str, LoRALayerWeights] = {}
  104. for tensor_name, tensor in tensors.items():
  105. module_name, is_lora_a = parse_fine_tuned_lora_name(tensor_name)
  106. if module_name not in loras:
  107. lora_embeddings_tensor = None
  108. if embeddings:
  109. assert embedding_modules is not None
  110. embeddings_module = next(
  111. (k for k in embedding_modules if k in module_name),
  112. None)
  113. if embeddings_module:
  114. lora_embeddings_tensor = embeddings[
  115. embedding_modules[embeddings_module]].to(
  116. device=device, dtype=dtype)
  117. if pin_memory:
  118. lora_embeddings_tensor = (
  119. lora_embeddings_tensor.pin_memory())
  120. loras[module_name] = LoRALayerWeights(module_name, rank,
  121. lora_alpha, None, None,
  122. lora_embeddings_tensor)
  123. if is_lora_a:
  124. loras[module_name].lora_a = tensor.to(device=device,
  125. dtype=dtype).t()
  126. if pin_memory:
  127. loras[module_name].lora_a = loras[
  128. module_name].lora_a.pin_memory()
  129. else:
  130. loras[module_name].lora_b = tensor.to(device=device,
  131. dtype=dtype).t()
  132. assert embedding_padding_modules is not None
  133. if any(name in module_name
  134. for name in embedding_padding_modules
  135. ) and target_embedding_padding is not None:
  136. lora_b = loras[module_name].lora_b
  137. assert target_embedding_padding >= lora_b.shape[1]
  138. addition = target_embedding_padding - lora_b.shape[1]
  139. loras[module_name].lora_b = torch.nn.functional.pad(
  140. lora_b, (0, addition))
  141. if pin_memory:
  142. loras[module_name].lora_b = loras[
  143. module_name].lora_b.pin_memory()
  144. for lora in loras.values():
  145. lora.optimize()
  146. return cls(lora_model_id, rank, loras, scaling_factor=scaling_factor)
  147. @classmethod
  148. def from_local_checkpoint(
  149. cls,
  150. lora_dir: str,
  151. expected_lora_modules: List[str],
  152. *,
  153. max_position_embeddings: Optional[int] = None,
  154. lora_model_id: Optional[int] = None,
  155. device: str = "cuda",
  156. dtype: Optional[torch.dtype] = None,
  157. target_embedding_padding: Optional[int] = None,
  158. embedding_modules: Optional[Dict[str, str]] = None,
  159. embedding_padding_modules: Optional[List[str]] = None,
  160. ) -> "LoRAModel":
  161. """Create a LoRAModel from a local checkpoint.
  162. Args:
  163. lora_dir: The local path that has lora data.
  164. expected_lora_modules: Name of modules that are expected to be
  165. replaced by lora.
  166. max_position_embeddings: Max position embedding length. Used to
  167. scaling the largest context length. If None, the lora model's
  168. context length is not scaled.
  169. lora_model_id: Lora model id. If not given, automatically set by
  170. a global counter.
  171. device: Device where the lora model is loaded.
  172. dtype: dtype of the lora model weights.
  173. Returns:
  174. Loaded LoRA Model.
  175. """
  176. lora_config_path = os.path.join(lora_dir, "adapter_config.json")
  177. lora_tensor_path = os.path.join(lora_dir, "adapter_model.safetensors")
  178. lora_bin_file_path = os.path.join(lora_dir, "adapter_model.bin")
  179. new_embeddings_tensor_path = os.path.join(
  180. lora_dir, "new_embeddings.safetensors")
  181. new_embeddings_bin_file_path = os.path.join(lora_dir,
  182. "new_embeddings.bin")
  183. with open(lora_config_path) as f:
  184. config = json.load(f)
  185. if os.path.isfile(lora_tensor_path):
  186. tensors: Dict[str, torch.Tensor] = {}
  187. # Find unexpected modules.
  188. # Use safetensor key as a source of truth to find expected modules.
  189. # in peft if you have target_modules A, B, C and C does not exist
  190. # in the model it won’t error and model will be trained with A, B
  191. # loraified. C won’t exist in the safetensor but it will exist in
  192. # the target_modules of the adapter_config.json.
  193. unexpected_modules = []
  194. with safetensors.safe_open(lora_tensor_path,
  195. framework="pt") as f: # type: ignore
  196. for lora_module in f.keys(): # noqa
  197. module_name, _ = parse_fine_tuned_lora_name(lora_module)
  198. part_name = module_name.split(".")[-1]
  199. if part_name not in expected_lora_modules:
  200. unexpected_modules.append(module_name)
  201. if unexpected_modules:
  202. raise ValueError(
  203. f"While loading {lora_dir}, expected"
  204. f" target modules in {expected_lora_modules}"
  205. f" but received {unexpected_modules}."
  206. f" Please verify that the loaded LoRA module is correct"
  207. )
  208. # Load tensors if there are only expected modules.
  209. for module in f.keys(): # noqa
  210. tensors[module] = f.get_tensor(module)
  211. elif os.path.isfile(lora_bin_file_path):
  212. # When a bin file is provided, we rely on config to find unexpected
  213. # modules.
  214. unexpected_modules = []
  215. target_modules = config["target_modules"]
  216. for module in target_modules:
  217. # Compatible with more modules,
  218. # such as:layers.11.self_attn.k_proj
  219. part_name = module.split(".")[-1]
  220. if part_name not in expected_lora_modules:
  221. unexpected_modules.append(module)
  222. # loaded lora's target modules must be a subset of
  223. # expected_lora_modules. It is not reliable. See
  224. # https://github.com/vllm-project/vllm/pull/5909. But there's no
  225. # other better mechanism.
  226. if unexpected_modules:
  227. print(unexpected_modules, "modules")
  228. raise ValueError(
  229. f"While loading {lora_dir}, expected"
  230. f" target modules in {expected_lora_modules}"
  231. f" but received {unexpected_modules}."
  232. f" Please verify that the loaded LoRA module is correct")
  233. tensors = torch.load(lora_bin_file_path, map_location=device)
  234. else:
  235. raise ValueError(f"{lora_dir} doesn't contain tensors")
  236. embeddings = None
  237. if os.path.isfile(new_embeddings_tensor_path):
  238. embeddings = safetensors.torch.load_file(
  239. new_embeddings_tensor_path)
  240. elif os.path.isfile(new_embeddings_bin_file_path):
  241. embeddings = torch.load(new_embeddings_bin_file_path,
  242. map_location=device)
  243. rank = config["r"]
  244. lora_alpha = config["lora_alpha"] * math.sqrt(rank) if config.get(
  245. "use_rslora", False) else config["lora_alpha"]
  246. context_length = config.get("context_length", None)
  247. scaling_factor = None
  248. if context_length:
  249. if max_position_embeddings is None:
  250. max_position_embeddings = context_length
  251. scaling_factor = float(
  252. math.ceil(context_length / max_position_embeddings))
  253. return cls.from_lora_tensors(
  254. lora_model_id=get_lora_id()
  255. if lora_model_id is None else lora_model_id,
  256. rank=rank,
  257. lora_alpha=lora_alpha,
  258. tensors=tensors,
  259. device=device,
  260. dtype=dtype,
  261. embeddings=embeddings,
  262. target_embedding_padding=target_embedding_padding,
  263. scaling_factor=scaling_factor,
  264. embedding_modules=embedding_modules,
  265. embedding_padding_modules=embedding_padding_modules,
  266. )
  267. class LoRAModelManager(AdapterModelManager):
  268. """A manager that manages multiple LoRA-fine-tuned models."""
  269. def __init__(
  270. self,
  271. model: SupportsLoRA,
  272. max_num_seqs: int,
  273. max_num_batched_tokens: int,
  274. vocab_size: int,
  275. lora_config: LoRAConfig,
  276. ):
  277. """Create a LoRAModelManager and adapter for a given model.
  278. Args:
  279. model: the model to be adapted.
  280. max_num_seqs: the maximum number of sequences model can run in a
  281. single batch.
  282. max_num_batched_tokens: the maximum number of tokens model can run
  283. in a single batch.
  284. vocab_size: the vocab size of the model.
  285. lora_config: the LoRA configuration.
  286. """
  287. self.lora_config = lora_config
  288. self.max_num_seqs = max_num_seqs
  289. assert self.capacity >= self.lora_slots
  290. self.max_num_batched_tokens = math.ceil(max_num_batched_tokens / 8) * 8
  291. self.lora_index_to_id: List[Optional[int]] = [None] * self.lora_slots
  292. self.vocab_size = vocab_size
  293. self.long_lora_context: Optional[LongContextLoRAContext] = None
  294. self.punica_wrapper = PunicaWrapper(max_num_batched_tokens,
  295. max_batches=self.max_num_seqs,
  296. device="cuda")
  297. # Scaling factor -> offset to the sin_cos_cache to it.
  298. # Used for long context lora.
  299. self.scaling_factor_to_offset: Dict[float, int] = {}
  300. super().__init__(model)
  301. if hasattr(self.model, "supported_lora_modules"):
  302. self.supported_lora_modules = copy.deepcopy(
  303. self.model.supported_lora_modules)
  304. if lora_config.long_lora_scaling_factors:
  305. # We need to replace rotary emb layer to do batch computation
  306. # for long lora.
  307. self.supported_lora_modules.append("rotary_emb")
  308. self.packed_modules_mapping = copy.deepcopy(
  309. self.model.packed_modules_mapping)
  310. self.packed_modules: Dict[str, List[str]] = {}
  311. self.modules: Dict[str, "BaseLayerWithLoRA"] = {}
  312. # Dict instead of a Set for compatibility with LRUCache.
  313. self._last_mapping: Optional[LoRAMapping] = None
  314. self._create_lora_modules()
  315. self.model.lora_manager = self
  316. self.adapter_type = 'LoRa'
  317. @property
  318. def capacity(self) -> int:
  319. return self.lora_config.max_cpu_loras
  320. @property
  321. def lora_slots(self) -> int:
  322. return self.lora_config.max_loras
  323. @property
  324. def adapter_slots(self) -> int:
  325. return self.lora_slots
  326. def activate_adapter(
  327. self,
  328. lora_id: int,
  329. ) -> bool:
  330. """Move LoRA into a GPU buffer to be used in the forward pass."""
  331. if lora_id in self._active_adapters:
  332. return False
  333. first_free_slot = next(
  334. ((i, lora_id) for i, lora_id in enumerate(self.lora_index_to_id)
  335. if lora_id is None), None)
  336. if first_free_slot is None:
  337. raise ValueError("No free lora slots")
  338. index, _ = first_free_slot
  339. self._active_adapters[lora_id] = None
  340. lora_model = self._registered_adapters[lora_id]
  341. logger.debug(f"Activating LoRA. int id: {lora_model.id}, "
  342. f"slot index: {index}")
  343. self.lora_index_to_id[index] = lora_model.id
  344. for module_name, module in self.modules.items():
  345. module_lora = lora_model.get_lora(module_name)
  346. if module_lora:
  347. module_lora.optimize()
  348. module.set_lora(index, module_lora.lora_a, module_lora.lora_b,
  349. module_lora.embeddings_tensor)
  350. else:
  351. module.reset_lora(index)
  352. return True
  353. def _deactivate_adapter(self, lora_id: int):
  354. try:
  355. index = self.lora_index_to_id.index(lora_id)
  356. self.lora_index_to_id[index] = None
  357. except ValueError:
  358. pass
  359. def _set_long_lora_context(self, lora: LoRAModel):
  360. if self.long_lora_context is None:
  361. return
  362. if lora.scaling_factor is None:
  363. return
  364. if (lora.scaling_factor not in self.scaling_factor_to_offset):
  365. raise ValueError(f"Long LoRA scaling factor {lora.scaling_factor}"
  366. " has not been initialized.")
  367. offsets = self.scaling_factor_to_offset.get(lora.scaling_factor)
  368. if offsets:
  369. self.long_lora_context.offsets_by_lora_id[lora.id] = offsets
  370. def _add_adapter(self, lora: LoRAModel):
  371. self._create_merged_loras_inplace(lora)
  372. self._registered_adapters[lora.id] = lora
  373. self._set_long_lora_context(lora)
  374. def pin_adapter(self, lora_id: int) -> bool:
  375. """Pin a LoRAModel in the manager cache."""
  376. raise NotImplementedError(
  377. "Pinning is not supported in LoRAModelManager."
  378. "Use LRUCacheLoRAModelManager for pinning") # type: ignore
  379. def _set_adapter_mapping(self, mapping: LoRAMapping) -> None:
  380. # update lora states
  381. self.punica_wrapper.update_metadata(
  382. mapping,
  383. self.lora_index_to_id,
  384. self.lora_slots + 1,
  385. self.vocab_size,
  386. self.lora_config.lora_extra_vocab_size,
  387. self.long_lora_context,
  388. )
  389. def remove_all_adapters(self):
  390. """Remove all LoRAModels from the manager."""
  391. self._registered_adapters.clear()
  392. self.lora_index_to_id = [None] * self.lora_slots
  393. self._active_adapters.clear()
  394. def _create_lora_modules(self):
  395. for module_name, module in self.model.named_modules(
  396. remove_duplicate=False):
  397. if isinstance(module, PPMissingLayer):
  398. continue
  399. if not self._match_target_modules(module_name):
  400. continue
  401. parts = module_name.split(".")[-1]
  402. packed_moduled_lst = self.packed_modules_mapping.get(parts, [])
  403. new_module = replace_submodule(
  404. self.model, module_name,
  405. from_layer(module, self.lora_slots, self.lora_config,
  406. packed_moduled_lst, self.model.config))
  407. # LinearScalingRotaryEmbeddingWithLora is used to handle
  408. # long context lora. Register relevant metadata.
  409. if isinstance(new_module, LinearScalingRotaryEmbeddingWithLora):
  410. self.long_lora_context = LongContextLoRAContext(
  411. new_module.scaling_factors, new_module.rotary_dim)
  412. self.scaling_factor_to_offset = \
  413. new_module.scaling_factor_to_offset
  414. # (yard1): TODO make this more robust
  415. if "lm_head" in module_name:
  416. logits_processor_module = self.model.get_submodule(
  417. "logits_processor")
  418. new_module = replace_submodule(
  419. self.model, "logits_processor",
  420. from_layer_logits_processor(logits_processor_module,
  421. module, self.lora_slots,
  422. self.lora_config,
  423. self.model.config))
  424. self.register_module(module_name, new_module)
  425. self._register_packed_modules(module_name)
  426. # All lora layers share the same punica_wrapper based on reference.
  427. new_module.set_mapping(self.punica_wrapper)
  428. def register_module(self, module_name: str, module: "BaseLayerWithLoRA"):
  429. assert isinstance(module, BaseLayerWithLoRA)
  430. self.modules[module_name] = module
  431. def create_dummy_lora(
  432. self,
  433. lora_id: int,
  434. rank: int,
  435. scaling_factor: Optional[float],
  436. embedding_modules: Optional[Dict[str, str]] = None) -> LoRAModel:
  437. """Create zero-initialized LoRAModel for warmup."""
  438. model = LoRAModel(lora_id, rank, {}, scaling_factor)
  439. for module_name, module in self.model.named_modules():
  440. if not self._match_target_modules(module_name) or not isinstance(
  441. module, BaseLayerWithLoRA) or isinstance(
  442. module, LinearScalingRotaryEmbeddingWithLora):
  443. continue
  444. parts = module_name.split(".")
  445. if module_name not in self.packed_modules:
  446. assert embedding_modules is not None
  447. if parts[-1] in embedding_modules:
  448. input_dim = (module.base_layer.org_vocab_size +
  449. self.lora_config.lora_extra_vocab_size if
  450. hasattr(module.base_layer, "org_vocab_size")
  451. else module.base_layer.weight.shape[1])
  452. output_dim = module.base_layer.embedding_dim if hasattr(
  453. module.base_layer,
  454. "embedding_dim") else module.base_layer.weight.shape[0]
  455. embeddings_tensor_dim = (module.base_layer.embedding_dim if
  456. hasattr(module.base_layer,
  457. "embedding_dim") else
  458. module.base_layer.weight.shape[1])
  459. lora = LoRALayerWeights.create_dummy_lora_weights(
  460. module_name,
  461. input_dim,
  462. output_dim,
  463. rank,
  464. module.lora_a_stacked.dtype,
  465. "cpu",
  466. embeddings_tensor_dim=embeddings_tensor_dim)
  467. else:
  468. lora = LoRALayerWeights.create_dummy_lora_weights(
  469. module_name,
  470. module.lora_a_stacked.shape[-1],
  471. module.lora_b_stacked.shape[-2],
  472. rank,
  473. module.lora_a_stacked.dtype,
  474. "cpu",
  475. )
  476. lora.optimize()
  477. else:
  478. parts = module_name.split(".")
  479. replacements = self.packed_modules_mapping[parts[-1]]
  480. subloras: List[Optional["LoRALayerWeights"]] = []
  481. for i, r in enumerate(replacements):
  482. lora = LoRALayerWeights.create_dummy_lora_weights(
  483. module_name + "." + r,
  484. module.lora_a_stacked[i].shape[-1],
  485. module.lora_b_stacked[i].shape[-2],
  486. rank,
  487. module.lora_a_stacked[i].dtype,
  488. "cpu",
  489. )
  490. lora.optimize()
  491. subloras.append(lora)
  492. lora = PackedLoRALayerWeights.pack(subloras)
  493. model.loras[module_name] = lora
  494. return model
  495. def _match_target_modules(self, module_name: str):
  496. return any(
  497. re.match(
  498. r".*\.{target_module}$".format(target_module=target_module),
  499. module_name) or target_module == module_name
  500. for target_module in self.supported_lora_modules)
  501. def _register_packed_modules(self, module_full_name: str) -> None:
  502. parts = module_full_name.split(".")
  503. module_name = parts[-1]
  504. replacements = self.packed_modules_mapping.get(module_name, [])
  505. # When replacements is less than or equal to 1, it indicates that this
  506. # module is not a packed module.
  507. if len(replacements) <= 1:
  508. return
  509. prefix = ".".join(parts[:-1])
  510. self.packed_modules[module_full_name] = [
  511. prefix + "." + r if prefix else r for r in replacements
  512. ]
  513. def _create_merged_loras_inplace(self, lora_model: LoRAModel) -> None:
  514. for module_name, new_module_names in self.packed_modules.items():
  515. replacement_loras: List[Optional[LoRALayerWeights]] = []
  516. has_replacement = False
  517. for r in new_module_names:
  518. lora = lora_model.get_lora(r)
  519. replacement_loras.append(lora)
  520. if lora:
  521. has_replacement = True
  522. if not has_replacement:
  523. continue
  524. for i in range(len(replacement_loras)):
  525. if replacement_loras[i]:
  526. continue
  527. replacement_loras[i] = None
  528. lora_model.loras[module_name] = PackedLoRALayerWeights.pack(
  529. replacement_loras)
  530. def deactivate_adapter(self, adapter_id: int) -> bool:
  531. return deactivate_adapter(adapter_id, self._active_adapters,
  532. self._deactivate_adapter)
  533. def add_adapter(self, adapter: LoRAModel) -> bool:
  534. logger.debug(
  535. f"Adding lora. Model id: {adapter.id}, "
  536. f"int id: {adapter.id}, "
  537. f"scaling factor: {adapter.scaling_factor}")
  538. return add_adapter(adapter, self._registered_adapters, self.capacity,
  539. self._add_adapter)
  540. def set_adapter_mapping(self, mapping: LoRAMapping) -> None:
  541. self._last_mapping = set_adapter_mapping(mapping, self._last_mapping,
  542. self._set_adapter_mapping)
  543. def remove_adapter(self, adapter_id: int) -> bool:
  544. return remove_adapter(adapter_id, self._registered_adapters,
  545. self.deactivate_adapter)
  546. def list_adapters(self) -> Dict[int, Any]:
  547. return list_adapters(self._registered_adapters)
  548. def get_adapter(self, adapter_id: int) -> Optional[Any]:
  549. return get_adapter(adapter_id, self._registered_adapters)
  550. class LoRALRUCache(AdapterLRUCache[LoRAModel]):
  551. def __init__(self, capacity: int, deactivate_lora_fn: Callable[[int],
  552. bool]):
  553. super().__init__(capacity, deactivate_lora_fn)
  554. class LRUCacheLoRAModelManager(LoRAModelManager):
  555. """A model manager that manages multiple LoRAs with LRU cache."""
  556. def __init__(
  557. self,
  558. model: nn.Module,
  559. max_num_seqs: int,
  560. max_num_batched_tokens: int,
  561. vocab_size: int,
  562. lora_config: LoRAConfig,
  563. ):
  564. super().__init__(model, max_num_seqs, max_num_batched_tokens,
  565. vocab_size, lora_config)
  566. self._registered_adapters: LoRALRUCache = LoRALRUCache(
  567. self.capacity, self.deactivate_adapter)
  568. self._active_adapters: LoRALRUCache = LoRALRUCache(
  569. self.lora_slots, self._deactivate_adapter)
  570. def list_adapters(self) -> Dict[int, LoRAModel]:
  571. """List all registered LoRAModels."""
  572. return dict(self._registered_adapters.cache)
  573. def add_adapter(self, lora: LoRAModel) -> bool:
  574. """Add a LoRAModel to the manager."""
  575. logger.debug(
  576. f"Adding lora. Model id: {lora.id}, "
  577. f"int id: {lora.id}, "
  578. f"scaling factor: {lora.scaling_factor}")
  579. if lora.id not in self._registered_adapters:
  580. self._add_adapter(lora)
  581. was_added = True
  582. else:
  583. # We always touch to update the LRU cache order
  584. self._registered_adapters.touch(lora.id)
  585. was_added = False
  586. return was_added
  587. def activate_adapter(
  588. self,
  589. lora_id: int,
  590. ) -> bool:
  591. if lora_id not in self._active_adapters and len(
  592. self._active_adapters) >= self.lora_slots:
  593. self._active_adapters.remove_oldest()
  594. result = super().activate_adapter(lora_id)
  595. # We always touch to update the LRU cache order
  596. self._active_adapters.touch(lora_id)
  597. return result
  598. def remove_oldest_adapter(self) -> bool:
  599. if len(self._registered_adapters) > 0:
  600. self._registered_adapters.remove_oldest()
  601. return True
  602. return False
  603. def pin_adapter(self, lora_id: int) -> bool:
  604. """Pin a LoRAModel in the manager cache."""
  605. self._pin_lora_in_cpu_cache(lora_id)
  606. self._pin_lora_in_gpu_cache(lora_id)
  607. return True
  608. def _pin_lora_in_cpu_cache(self, lora_id: int):
  609. try:
  610. self._registered_adapters.pin(lora_id)
  611. except ValueError as err:
  612. raise ValueError("Pinning failed. "
  613. f"LoRA {lora_id} is not registered.") from err
  614. def _pin_lora_in_gpu_cache(self, lora_id: int):
  615. if lora_id not in self._active_adapters:
  616. # move lora to gpu if not already active
  617. self.activate_adapter(lora_id)
  618. self._active_adapters.pin(lora_id)
  619. def create_lora_manager(
  620. model: nn.Module,
  621. max_num_seqs: int,
  622. max_num_batched_tokens: int,
  623. vocab_size: int,
  624. lora_config: LoRAConfig,
  625. lora_manager_cls: Type[LoRAModelManager] = LoRAModelManager,
  626. **kwargs) -> LoRAModelManager:
  627. """Create a LoRA adapter for a given model."""
  628. if not hasattr(model, "supported_lora_modules"):
  629. raise ValueError(f"Model {type(model)} is not supported for LoRA.")
  630. lora_manager = lora_manager_cls(
  631. model=model,
  632. max_num_seqs=max_num_seqs,
  633. max_num_batched_tokens=max_num_batched_tokens,
  634. vocab_size=vocab_size,
  635. lora_config=lora_config,
  636. **kwargs)
  637. return lora_manager