1
0

models.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. import copy
  2. import json
  3. import math
  4. import os
  5. import re
  6. from typing import Callable, Dict, Hashable, List, Optional, Tuple, Type
  7. import safetensors.torch
  8. import torch
  9. from loguru import logger
  10. from torch import nn
  11. from aphrodite.common.config import LoRAConfig
  12. from aphrodite.common.utils import LRUCache, is_pin_memory_available
  13. from aphrodite.lora.layers import (BaseLayerWithLoRA, LoRAMapping, from_layer,
  14. from_layer_logits_processor)
  15. from aphrodite.lora.lora import LoRALayerWeights, PackedLoRALayerWeights
  16. from aphrodite.lora.utils import parse_fine_tuned_lora_name, replace_submodule
  17. _GLOBAL_LORA_ID = 0
  18. def convert_mapping(
  19. mapping: LoRAMapping, lora_index_to_id: List[Optional[int]],
  20. max_loras: int, vocab_size: int, extra_vocab_size: int
  21. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, List[int]]:
  22. """Converts LoRAMapping to index tensors.
  23. Args:
  24. mapping: LoRAMapping mapping rows in a batch to LoRA ids.
  25. lora_index_to_id: List mapping LoRA ids to LoRA indices.
  26. max_loras: Maximum number of LoRAs.
  27. vocab_size: Model vocab size.
  28. extra_vocab_size: Extra vocab size each LoRA can have.
  29. Returns:
  30. A tuple of tensors:
  31. base_indices: Tensor of shape [batch_size] mapping batch rows to
  32. LoRA indices.
  33. sampler_indices: Tensor of shape [batch_size] mapping requests to
  34. LoRA indices for sampler. For generation, this will be the
  35. same as base_indicies. For prefill, this will map requests
  36. to LoRA indices.
  37. sampler_indices_padded: Tensor of shape [batch_size] mapping
  38. requests to LoRA indices for sampler with padding.
  39. Same as sampler_indicies, but -1 is replaced with
  40. max_loras.
  41. embeddings_indices: Tensor of shape [2, batch_size] mapping
  42. requests to embedding indices. First row is for embeddings
  43. added by the LoRAs, second row is for the LoRA.lora_a
  44. embeddings.
  45. indices_len: List of lengths of the above tensors.
  46. """
  47. indices = list(mapping.index_mapping).copy()
  48. embedding_indices = indices.copy()
  49. lora_indices = indices.copy()
  50. prompt_mapping = [
  51. lora_index_to_id.index(x) if x > 0 else -1
  52. for x in mapping.prompt_mapping
  53. ]
  54. lora_idx = None
  55. for i in range(len(indices)):
  56. # TODO index can be slow. optimize
  57. lora_idx = (lora_index_to_id.index(indices[i])
  58. if indices[i] > 0 else -1)
  59. embedding_indices[i] = lora_idx if indices[i] > 0 else 0
  60. indices[i] = i
  61. lora_indices[i] = lora_idx
  62. indices = torch.tensor([indices, lora_indices, embedding_indices],
  63. dtype=torch.long,
  64. device="cuda")
  65. prompt_mapping = torch.tensor(prompt_mapping,
  66. device="cuda",
  67. dtype=torch.long)
  68. embeddings_indices = torch.stack([
  69. indices[2] * extra_vocab_size,
  70. indices[2] * (vocab_size + extra_vocab_size)
  71. ])
  72. embeddings_indices[embeddings_indices == -1] = max_loras - 1
  73. base_indices = indices[1]
  74. sampler_indices = prompt_mapping
  75. sampler_indices_padded = sampler_indices.clone()
  76. sampler_indices_padded[sampler_indices_padded == -1] = max_loras - 1
  77. sampler_indices_padded = (
  78. torch.arange(
  79. 0, len(sampler_indices_padded), device="cuda", dtype=torch.long) +
  80. (sampler_indices_padded * len(sampler_indices_padded)))
  81. indices_len = (base_indices.shape[-1], sampler_indices.shape[-1],
  82. sampler_indices_padded.shape[-1],
  83. embeddings_indices.shape[-1])
  84. return (base_indices, sampler_indices, sampler_indices_padded,
  85. embeddings_indices, indices_len)
  86. def get_lora_id():
  87. global _GLOBAL_LORA_ID
  88. _GLOBAL_LORA_ID += 1
  89. return _GLOBAL_LORA_ID
  90. class LoRAModel:
  91. """A LoRA fine-tuned model."""
  92. def __init__(
  93. self,
  94. lora_model_id: int,
  95. rank: int,
  96. loras: Dict[str, LoRALayerWeights],
  97. ) -> None:
  98. self.id = lora_model_id
  99. assert (lora_model_id >
  100. 0), f"a valid lora id should be greater than 0, got {self.id}"
  101. self.rank = rank
  102. self.loras: Dict[str, LoRALayerWeights] = loras
  103. @property
  104. def extra_vocab_size(self) -> int:
  105. return max(lora.extra_vocab_size
  106. for lora in self.loras.values()) if self.loras else 0
  107. def get_lora(self, module_name: str) -> Optional[LoRALayerWeights]:
  108. """Get LoRA for a given module by name"""
  109. return self.loras.get(module_name, None)
  110. # (yard1): TODO see if we can derive target_embedding_padding automatically
  111. @classmethod
  112. def from_lora_tensors(
  113. cls,
  114. lora_model_id: int,
  115. rank: int,
  116. lora_alpha: int,
  117. tensors: Dict[str, torch.Tensor],
  118. device: str = "cuda",
  119. dtype: Optional[torch.dtype] = None,
  120. embeddings: Optional[Dict[str, torch.Tensor]] = None,
  121. target_embedding_padding: Optional[int] = None,
  122. embedding_modules: Optional[Dict[str, str]] = None,
  123. embedding_padding_modules: Optional[List[str]] = None,
  124. ) -> "LoRAModel":
  125. """Create a LoRAModel from a dictionary of tensors."""
  126. pin_memory = str(device) == "cpu" and is_pin_memory_available()
  127. loras: Dict[str, LoRALayerWeights] = {}
  128. for tensor_name, tensor in tensors.items():
  129. module_name, is_lora_a = parse_fine_tuned_lora_name(tensor_name)
  130. if module_name not in loras:
  131. lora_embeddings_tensor = None
  132. if embeddings:
  133. embeddings_module = next(
  134. (k for k in embedding_modules if k in module_name),
  135. None)
  136. if embeddings_module:
  137. lora_embeddings_tensor = embeddings[
  138. embedding_modules[embeddings_module]].to(
  139. device=device, dtype=dtype)
  140. if pin_memory:
  141. lora_embeddings_tensor = (
  142. lora_embeddings_tensor.pin_memory())
  143. loras[module_name] = LoRALayerWeights(module_name, rank,
  144. lora_alpha, None, None,
  145. lora_embeddings_tensor)
  146. if is_lora_a:
  147. loras[module_name].lora_a = tensor.to(device=device,
  148. dtype=dtype).t()
  149. if pin_memory:
  150. loras[module_name].lora_a = loras[
  151. module_name].lora_a.pin_memory()
  152. else:
  153. loras[module_name].lora_b = tensor.to(device=device,
  154. dtype=dtype).t()
  155. if any(name in module_name
  156. for name in embedding_padding_modules
  157. ) and target_embedding_padding is not None:
  158. lora_b = loras[module_name].lora_b
  159. assert target_embedding_padding >= lora_b.shape[1]
  160. addition = target_embedding_padding - lora_b.shape[1]
  161. loras[module_name].lora_b = torch.nn.functional.pad(
  162. lora_b, (0, addition))
  163. if pin_memory:
  164. loras[module_name].lora_b = loras[
  165. module_name].lora_b.pin_memory()
  166. # Filter out LoRALayerWeights instances where lora_a or lora_b is None
  167. loras = {
  168. k: v
  169. for k, v in loras.items()
  170. if v.lora_a is not None and v.lora_b is not None
  171. }
  172. for lora in loras.values():
  173. lora.optimize()
  174. return cls(lora_model_id, rank, loras)
  175. @classmethod
  176. def from_local_checkpoint(
  177. cls,
  178. lora_dir: str,
  179. expected_lora_modules: List[str],
  180. lora_model_id: Optional[int] = None,
  181. device: str = "cuda",
  182. dtype: Optional[torch.dtype] = None,
  183. target_embedding_padding: Optional[int] = None,
  184. embedding_modules: Optional[Dict[str, str]] = None,
  185. embedding_padding_modules: Optional[List[str]] = None,
  186. ) -> "LoRAModel":
  187. """Create a LoRAModel from a local checkpoint."""
  188. lora_config_path = os.path.join(lora_dir, "adapter_config.json")
  189. lora_tensor_path = os.path.join(lora_dir, "adapter_model.safetensors")
  190. lora_bin_file_path = os.path.join(lora_dir, "adapter_model.bin")
  191. new_embeddings_tensor_path = os.path.join(
  192. lora_dir, "new_embeddings.safetensors")
  193. new_embeddings_bin_file_path = os.path.join(lora_dir,
  194. "new_embeddings.bin")
  195. with open(lora_config_path) as f:
  196. config = json.load(f)
  197. target_modules = config["target_modules"]
  198. unexpected_modules = []
  199. for module in target_modules:
  200. if module not in expected_lora_modules:
  201. unexpected_modules.append(module)
  202. # loaded lora's target modules must be a subset of expected_lora_modules
  203. if unexpected_modules:
  204. raise ValueError(
  205. f"While loading {lora_dir}, expected"
  206. f" target modules in {expected_lora_modules}"
  207. f" but received {unexpected_modules}."
  208. f" Please verify that the loaded LoRA module is correct")
  209. if os.path.isfile(lora_tensor_path):
  210. tensors = safetensors.torch.load_file(lora_tensor_path)
  211. elif os.path.isfile(lora_bin_file_path):
  212. tensors = torch.load(lora_bin_file_path)
  213. else:
  214. raise ValueError(f"{lora_dir} doesn't contain tensors")
  215. embeddings = None
  216. if os.path.isfile(new_embeddings_tensor_path):
  217. embeddings = safetensors.torch.load_file(
  218. new_embeddings_tensor_path)
  219. elif os.path.isfile(new_embeddings_bin_file_path):
  220. embeddings = torch.load(new_embeddings_bin_file_path)
  221. rank = config["r"]
  222. lora_alpha = config["lora_alpha"]
  223. return cls.from_lora_tensors(
  224. lora_model_id=get_lora_id()
  225. if lora_model_id is None else lora_model_id,
  226. rank=rank,
  227. lora_alpha=lora_alpha,
  228. tensors=tensors,
  229. device=device,
  230. dtype=dtype,
  231. embeddings=embeddings,
  232. target_embedding_padding=target_embedding_padding,
  233. embedding_modules=embedding_modules,
  234. embedding_padding_modules=embedding_padding_modules,
  235. )
  236. class LoRAModelManager:
  237. """A manager that manages multiple LoRA-fine-tuned models."""
  238. def __init__(
  239. self,
  240. model: nn.Module,
  241. max_num_seqs: int,
  242. max_num_batched_tokens: int,
  243. vocab_size: int,
  244. lora_config: LoRAConfig,
  245. ):
  246. """Create a LoRAModelManager and adapter for a given model.
  247. Args:
  248. model: the model to be adapted.
  249. max_num_seqs: the maximum number of sequences model can run in a
  250. single batch.
  251. max_num_batched_tokens: the maximum number of tokens model can run
  252. in a single batch.
  253. vocab_size: the vocab size of the model.
  254. lora_config: the LoRA configuration.
  255. """
  256. self.lora_config = lora_config
  257. self.max_num_seqs = max_num_seqs
  258. assert self.capacity >= self.lora_slots
  259. self.max_num_batched_tokens = math.ceil(max_num_batched_tokens / 8) * 8
  260. self.lora_index_to_id: List[Optional[int]] = [None] * self.lora_slots
  261. self.vocab_size = vocab_size
  262. self.base_indices = torch.empty(self.max_num_batched_tokens,
  263. dtype=torch.long,
  264. device="cuda")
  265. self.sampler_indices = torch.empty(self.max_num_batched_tokens,
  266. dtype=torch.long,
  267. device="cuda")
  268. self.sampler_indices_padded = torch.empty(self.max_num_batched_tokens,
  269. dtype=torch.long,
  270. device="cuda")
  271. self.embeddings_indices = torch.empty(2,
  272. self.max_num_batched_tokens,
  273. dtype=torch.long,
  274. device="cuda")
  275. self.offsets = []
  276. # 4 is the number of indicies tensors defined above
  277. # base_indices, sampler_indices, sampler_indices_padded,
  278. # embeddings_indices
  279. self.indices_len = [None] * 4
  280. self.model: nn.Module = model
  281. if hasattr(self.model, "supported_lora_modules"):
  282. self.supported_lora_modules = copy.deepcopy(
  283. self.model.supported_lora_modules)
  284. self.packed_modules_mapping = copy.deepcopy(
  285. self.model.packed_modules_mapping)
  286. self.packed_modules: Dict[str, List[str]] = {}
  287. self.modules: Dict[str, "BaseLayerWithLoRA"] = {}
  288. self._registered_loras: Dict[int, LoRAModel] = {}
  289. # Dict instead of a Set for compatibility with LRUCache.
  290. self._active_loras: Dict[int, None] = {}
  291. self._last_mapping = None
  292. self._create_lora_modules()
  293. self.model.lora_manager = self
  294. @property
  295. def capacity(self) -> int:
  296. return self.lora_config.max_cpu_loras
  297. @property
  298. def lora_slots(self) -> int:
  299. return self.lora_config.max_loras
  300. def __len__(self) -> int:
  301. return len(self._registered_loras)
  302. def activate_lora(
  303. self,
  304. lora_id: int,
  305. ) -> bool:
  306. """Move LoRA into a GPU buffer to be used in the forward pass."""
  307. if lora_id in self._active_loras:
  308. return False
  309. first_free_slot = next(
  310. ((i, lora_id) for i, lora_id in enumerate(self.lora_index_to_id)
  311. if lora_id is None), None)
  312. if first_free_slot is None:
  313. raise ValueError("No free lora slots")
  314. index, _ = first_free_slot
  315. self._active_loras[lora_id] = None
  316. lora_model = self._registered_loras[lora_id]
  317. logger.debug(
  318. f"Activating LoRA. int id: {lora_model.id}, slot index: {index}")
  319. self.lora_index_to_id[index] = lora_model.id
  320. for module_name, module in self.modules.items():
  321. module_lora = lora_model.get_lora(module_name)
  322. if module_lora:
  323. module_lora.optimize()
  324. module.set_lora(index, module_lora.lora_a, module_lora.lora_b,
  325. module_lora.embeddings_tensor)
  326. else:
  327. module.reset_lora(index)
  328. return True
  329. def _deactivate_lora(self, lora_id: int):
  330. try:
  331. index = self.lora_index_to_id.index(lora_id)
  332. self.lora_index_to_id[index] = None
  333. except ValueError:
  334. pass
  335. def deactivate_lora(self, lora_id: int) -> bool:
  336. """Remove a LoRA from a GPU buffer."""
  337. if lora_id in self._active_loras:
  338. self._deactivate_lora(lora_id)
  339. self._active_loras.pop(lora_id)
  340. return True
  341. return False
  342. def _add_lora(self, lora: LoRAModel) -> bool:
  343. self._create_merged_loras_inplace(lora)
  344. self._registered_loras[lora.id] = lora
  345. def add_lora(self, lora: LoRAModel) -> bool:
  346. """Add a LoRAModel to the manager CPU cache."""
  347. if lora.id not in self._registered_loras:
  348. if len(self._registered_loras) >= self.capacity:
  349. raise RuntimeError("No free LoRA slots.")
  350. self._add_lora(lora)
  351. return True
  352. return False
  353. def remove_lora(self, lora_id: int) -> bool:
  354. """Remove a LoRAModel from the manager CPU cache."""
  355. # TODO: should we check active lora?
  356. self.deactivate_lora(lora_id)
  357. return bool(self._registered_loras.pop(lora_id, None))
  358. # TODO see if this can be vectorized
  359. def _set_lora_mapping(self, mapping: LoRAMapping) -> None:
  360. (base_indices, sampler_indices, sampler_indices_padded,
  361. embeddings_indices,
  362. indices_len) = convert_mapping(mapping, self.lora_index_to_id,
  363. self.lora_slots + 1, self.vocab_size,
  364. self.lora_config.lora_extra_vocab_size)
  365. self.base_indices[:base_indices.shape[0]].copy_(base_indices)
  366. self.sampler_indices[:sampler_indices.shape[0]].copy_(sampler_indices)
  367. self.sampler_indices_padded[:sampler_indices_padded.shape[0]].copy_(
  368. sampler_indices_padded)
  369. self.embeddings_indices[:embeddings_indices.
  370. shape[0], :embeddings_indices.shape[1]].copy_(
  371. embeddings_indices)
  372. # Maintain the reference
  373. self.indices_len[:] = indices_len
  374. def set_lora_mapping(self, lora_mapping: LoRAMapping) -> None:
  375. if self._last_mapping != lora_mapping:
  376. self._set_lora_mapping(lora_mapping)
  377. self._last_mapping = lora_mapping
  378. def list_loras(self) -> Dict[int, LoRAModel]:
  379. """List all registered LoRAModels."""
  380. return dict(self._registered_loras)
  381. def get_lora(self, lora_id: int) -> Optional[LoRAModel]:
  382. return self._registered_loras.get(lora_id, None)
  383. def remove_all_loras(self) -> bool:
  384. """Remove all LoRAModels from the manager."""
  385. self._registered_loras.clear()
  386. self.lora_index_to_id = [None] * self.lora_slots
  387. self._active_loras.clear()
  388. def _create_lora_modules(self):
  389. for module_name, module in self.model.named_modules():
  390. if not self._match_target_modules(module_name):
  391. continue
  392. parts = module_name.split(".")[-1]
  393. packed_moduled_lst = self.packed_modules_mapping.get(parts, [])
  394. new_module = replace_submodule(
  395. self.model, module_name,
  396. from_layer(module, self.lora_slots, self.lora_config,
  397. packed_moduled_lst, self.model.config))
  398. # (yard1): TODO make this more robust
  399. if "lm_head" in module_name:
  400. logits_processor_module = self.model.get_submodule(
  401. "logits_processor")
  402. new_module = replace_submodule(
  403. self.model, "logits_processor",
  404. from_layer_logits_processor(logits_processor_module,
  405. module, self.lora_slots,
  406. self.lora_config,
  407. self.model.config))
  408. self.register_module(module_name, new_module)
  409. self._register_packed_modules(module_name)
  410. new_module.set_mapping(self.base_indices, self.sampler_indices,
  411. self.sampler_indices_padded,
  412. self.embeddings_indices, self.indices_len)
  413. def register_module(self, module_name: str, module: "BaseLayerWithLoRA"):
  414. assert isinstance(module, BaseLayerWithLoRA)
  415. self.modules[module_name] = module
  416. def create_dummy_lora(
  417. self,
  418. lora_id: int,
  419. rank: int,
  420. embedding_modules: Optional[Dict[str, str]] = None) -> LoRAModel:
  421. """Create zero-initialized LoRAModel for warmup."""
  422. model = LoRAModel(lora_id, rank, {})
  423. for module_name, module in self.model.named_modules():
  424. if not self._match_target_modules(module_name) or not isinstance(
  425. module, BaseLayerWithLoRA):
  426. continue
  427. parts = module_name.split(".")
  428. if module_name not in self.packed_modules:
  429. if parts[-1] in embedding_modules:
  430. input_dim = (module.base_layer.org_vocab_size +
  431. self.lora_config.lora_extra_vocab_size if
  432. hasattr(module.base_layer, "org_vocab_size")
  433. else module.base_layer.weight.shape[1])
  434. output_dim = module.base_layer.embedding_dim if hasattr(
  435. module.base_layer,
  436. "embedding_dim") else module.base_layer.weight.shape[0]
  437. embeddings_tensor_dim = (module.base_layer.embedding_dim if
  438. hasattr(module.base_layer,
  439. "embedding_dim") else
  440. module.base_layer.weight.shape[1])
  441. lora = LoRALayerWeights.create_dummy_lora_weights(
  442. module_name,
  443. input_dim,
  444. output_dim,
  445. rank,
  446. module.lora_a_stacked.dtype,
  447. "cpu",
  448. embeddings_tensor_dim=embeddings_tensor_dim)
  449. else:
  450. lora = LoRALayerWeights.create_dummy_lora_weights(
  451. module_name,
  452. module.lora_a_stacked.shape[-1],
  453. module.lora_b_stacked.shape[-2],
  454. rank,
  455. module.lora_a_stacked.dtype,
  456. "cpu",
  457. )
  458. lora.optimize()
  459. else:
  460. parts = module_name.split(".")
  461. replacements = self.packed_modules_mapping[parts[-1]]
  462. subloras = []
  463. for i, r in enumerate(replacements):
  464. lora = LoRALayerWeights.create_dummy_lora_weights(
  465. module_name + "." + r,
  466. module.lora_a_stacked[i].shape[-1],
  467. module.lora_b_stacked[i].shape[-2],
  468. rank,
  469. module.lora_a_stacked[i].dtype,
  470. "cpu",
  471. )
  472. lora.optimize()
  473. subloras.append(lora)
  474. lora = PackedLoRALayerWeights.pack(subloras)
  475. model.loras[module_name] = lora
  476. return model
  477. def _match_target_modules(self, module_name: str):
  478. return any(
  479. re.match(
  480. r".*\.{target_module}$".format(target_module=target_module),
  481. module_name) or target_module == module_name
  482. for target_module in self.supported_lora_modules)
  483. def _register_packed_modules(self, module_full_name: str) -> None:
  484. parts = module_full_name.split(".")
  485. module_name = parts[-1]
  486. replacements = self.packed_modules_mapping.get(module_name, [])
  487. # When replacements is less than or equal to 1, it indicates that this
  488. # module is not a packed module.
  489. if len(replacements) <= 1:
  490. return
  491. prefix = ".".join(parts[:-1])
  492. self.packed_modules[module_full_name] = [
  493. prefix + "." + r if prefix else r for r in replacements
  494. ]
  495. def _create_merged_loras_inplace(self, lora_model: LoRAModel) -> None:
  496. for module_name, new_module_names in self.packed_modules.items():
  497. replacement_loras = []
  498. has_replacement = False
  499. for r in new_module_names:
  500. lora = lora_model.get_lora(r)
  501. replacement_loras.append(lora)
  502. if lora:
  503. has_replacement = True
  504. if not has_replacement:
  505. continue
  506. for i in range(len(replacement_loras)):
  507. if replacement_loras[i]:
  508. continue
  509. replacement_loras[i] = None
  510. lora_model.loras[module_name] = PackedLoRALayerWeights.pack(
  511. replacement_loras)
  512. class LoRALRUCache(LRUCache[LoRAModel]):
  513. def __init__(self, capacity: int, deactivate_lora_fn: Callable[[Hashable],
  514. None]):
  515. super().__init__(capacity)
  516. self.deactivate_lora_fn = deactivate_lora_fn
  517. def _on_remove(self, key: Hashable, value: LoRAModel):
  518. logger.debug(f"Removing LoRA. int id: {key}")
  519. self.deactivate_lora_fn(key)
  520. return super()._on_remove(key, value)
  521. class LRUCacheLoRAModelManager(LoRAModelManager):
  522. """A model manager that manages multiple LoRAs with LRU cache."""
  523. def __init__(
  524. self,
  525. model: nn.Module,
  526. max_num_seqs: int,
  527. max_num_batched_tokens: int,
  528. vocab_size: int,
  529. lora_config: LoRAConfig,
  530. ):
  531. super().__init__(model, max_num_seqs, max_num_batched_tokens,
  532. vocab_size, lora_config)
  533. self._registered_loras: LoRALRUCache = LoRALRUCache(
  534. self.capacity, self.deactivate_lora)
  535. self._active_loras: LoRALRUCache = LoRALRUCache(
  536. self.lora_slots, self._deactivate_lora)
  537. def list_loras(self) -> Dict[int, LoRAModel]:
  538. """List all registered LoRAModels."""
  539. return dict(self._registered_loras.cache)
  540. def add_lora(self, lora: LoRAModel) -> bool:
  541. """Add a LoRAModel to the manager."""
  542. if lora.id not in self._registered_loras:
  543. self._add_lora(lora)
  544. was_added = True
  545. else:
  546. # We always touch to update the LRU cache order
  547. self._registered_loras.touch(lora.id)
  548. was_added = False
  549. return was_added
  550. def activate_lora(
  551. self,
  552. lora_id: int,
  553. ) -> bool:
  554. if lora_id not in self._active_loras and len(
  555. self._active_loras) >= self.lora_slots:
  556. self._active_loras.remove_oldest()
  557. result = super().activate_lora(lora_id)
  558. # We always touch to update the LRU cache order
  559. self._active_loras.touch(lora_id)
  560. return result
  561. def remove_oldest_lora(self) -> bool:
  562. if len(self._registered_loras) > 0:
  563. self._registered_loras.remove_oldest()
  564. return True
  565. return False
  566. def create_lora_manager(
  567. model: nn.Module,
  568. max_num_seqs: int,
  569. max_num_batched_tokens: int,
  570. vocab_size: int,
  571. lora_config: LoRAConfig,
  572. lora_manager_cls: Type[LoRAModelManager] = LoRAModelManager,
  573. **kwargs) -> LoRAModelManager:
  574. """Create a LoRA adapter for a given model."""
  575. if not hasattr(model, "supported_lora_modules"):
  576. raise ValueError(f"Model {type(model)} is not supported for LoRA.")
  577. lora_manager = lora_manager_cls(
  578. model=model,
  579. max_num_seqs=max_num_seqs,
  580. max_num_batched_tokens=max_num_batched_tokens,
  581. vocab_size=vocab_size,
  582. lora_config=lora_config,
  583. **kwargs)
  584. return lora_manager