loader.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. # ruff: noqa: SIM117
  2. import collections
  3. import copy
  4. import fnmatch
  5. import glob
  6. import json
  7. import math
  8. import os
  9. from abc import ABC, abstractmethod
  10. from contextlib import contextmanager
  11. from typing import Any, Dict, Generator, List, Optional, Tuple, Type
  12. import gguf
  13. import huggingface_hub
  14. import numpy as np
  15. import torch
  16. from huggingface_hub import HfApi, hf_hub_download
  17. from loguru import logger
  18. from torch import nn
  19. from transformers import AutoModelForCausalLM, PretrainedConfig
  20. from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
  21. from aphrodite.common.config import (APHRODITE_USE_MODELSCOPE, CacheConfig,
  22. DeviceConfig, LoadConfig, LoadFormat,
  23. LoRAConfig, ModelConfig, MultiModalConfig,
  24. ParallelConfig, SchedulerConfig)
  25. from aphrodite.common.utils import is_pin_memory_available
  26. from aphrodite.modeling.model_loader.tensorizer import (
  27. TensorizerConfig, is_aphrodite_tensorized, load_with_tensorizer,
  28. serialize_aphrodite_model, tensorizer_weights_iterator)
  29. from aphrodite.modeling.model_loader.utils import (get_model_architecture,
  30. set_default_torch_dtype)
  31. from aphrodite.modeling.model_loader.weight_utils import (
  32. download_safetensors_index_file_from_hf, download_weights_from_hf,
  33. filter_duplicate_safetensors_files, filter_files_not_needed_for_inference,
  34. get_gguf_extra_tensor_names, get_quant_config, gguf_quant_weights_iterator,
  35. initialize_dummy_weights, np_cache_weights_iterator, pt_weights_iterator,
  36. safetensors_weights_iterator)
  37. from aphrodite.modeling.models.interfaces import (has_inner_state,
  38. supports_lora,
  39. supports_multimodal)
  40. from aphrodite.modeling.utils import set_weight_attrs
  41. from aphrodite.platforms import current_platform
  42. from aphrodite.quantization.base_config import QuantizationConfig
  43. @contextmanager
  44. def device_loading_context(module: torch.nn.Module,
  45. target_device: torch.device):
  46. if target_device.type == "cpu":
  47. # If target is CPU, no need to move anything
  48. yield module
  49. return
  50. original_device_states: Dict[str, torch.device] = {}
  51. # Store original device states and move parameters to GPU if they're on CPU
  52. for name, p in module.named_parameters():
  53. if p.device.type == "cpu":
  54. original_device_states[name] = p.device
  55. p.data = p.data.to(target_device)
  56. # Parameters already on target device are not touched
  57. try:
  58. yield module
  59. finally:
  60. # Restore parameters to their original devices, ignoring new parameters
  61. pin_memory = is_pin_memory_available()
  62. for name, p in module.named_parameters():
  63. if name in original_device_states:
  64. original_device: torch.device = original_device_states[name]
  65. if original_device.type == "cpu":
  66. # `torch.empty_like` does not support `pin_memory` argument
  67. cpu_data = torch.empty_strided(size=p.data.size(),
  68. stride=p.data.stride(),
  69. dtype=p.data.dtype,
  70. layout=p.data.layout,
  71. device="cpu",
  72. pin_memory=pin_memory)
  73. cpu_data.copy_(p.data)
  74. p.data = cpu_data
  75. else:
  76. p.data = p.data.to(original_device)
  77. # New parameters or parameters already on target device are untouched
  78. def _get_quantization_config(
  79. model_config: ModelConfig,
  80. load_config: LoadConfig) -> Optional[QuantizationConfig]:
  81. """Get the quantization config."""
  82. if model_config.quantization is not None:
  83. quant_config = get_quant_config(model_config, load_config)
  84. if not current_platform.is_tpu():
  85. capability = current_platform.get_device_capability()
  86. capability = capability[0] * 10 + capability[1]
  87. if capability < quant_config.get_min_capability():
  88. raise ValueError(
  89. f"The quantization method {model_config.quantization} "
  90. "is not supported for the current GPU. "
  91. f"Minimum capability: {quant_config.get_min_capability()}. "
  92. f"Current capability: {capability}.")
  93. supported_dtypes = quant_config.get_supported_act_dtypes()
  94. if model_config.dtype not in supported_dtypes:
  95. raise ValueError(
  96. f"{model_config.dtype} is not supported for quantization "
  97. f"method {model_config.quantization}. Supported dtypes: "
  98. f"{supported_dtypes}")
  99. return quant_config
  100. return None
  101. def _get_model_initialization_kwargs(
  102. model_class: Type[nn.Module],
  103. lora_config: Optional[LoRAConfig],
  104. multimodal_config: Optional[MultiModalConfig],
  105. scheduler_config: Optional[SchedulerConfig] = None) -> Dict[str, Any]:
  106. """Get extra kwargs for model initialization."""
  107. extra_kwargs: Dict[str, Any] = {}
  108. if supports_lora(model_class):
  109. # lora_config=None is used to disable LoRA
  110. extra_kwargs["lora_config"] = lora_config
  111. elif lora_config:
  112. raise ValueError(
  113. f"Model {model_class.__name__} does not support LoRA, "
  114. "but LoRA is enabled. Support for this model may "
  115. "be added in the future. If this is important to you, "
  116. "please open an issue on github.")
  117. if supports_multimodal(model_class):
  118. assert multimodal_config is not None
  119. extra_kwargs["multimodal_config"] = multimodal_config
  120. if has_inner_state(model_class) and scheduler_config:
  121. extra_kwargs["scheduler_config"] = scheduler_config
  122. return extra_kwargs
  123. def build_model(model_class: Type[nn.Module], hf_config: PretrainedConfig,
  124. cache_config: Optional[CacheConfig],
  125. quant_config: Optional[QuantizationConfig], *,
  126. lora_config: Optional[LoRAConfig],
  127. multimodal_config: Optional[MultiModalConfig],
  128. scheduler_config: Optional[SchedulerConfig]) -> nn.Module:
  129. extra_kwargs = _get_model_initialization_kwargs(model_class, lora_config,
  130. multimodal_config,
  131. scheduler_config)
  132. return model_class(config=hf_config,
  133. cache_config=cache_config,
  134. quant_config=quant_config,
  135. **extra_kwargs)
  136. def _initialize_model(
  137. model_config: ModelConfig,
  138. load_config: LoadConfig,
  139. lora_config: Optional[LoRAConfig],
  140. cache_config: CacheConfig,
  141. scheduler_config: Optional[SchedulerConfig] = None) -> nn.Module:
  142. """Initialize a model with the given configurations."""
  143. model_class, _ = get_model_architecture(model_config)
  144. return build_model(
  145. model_class,
  146. model_config.hf_config,
  147. cache_config=cache_config,
  148. quant_config=_get_quantization_config(model_config, load_config),
  149. lora_config=lora_config,
  150. multimodal_config=model_config.multimodal_config,
  151. scheduler_config=scheduler_config,
  152. )
  153. class BaseModelLoader(ABC):
  154. """Base class for model loaders."""
  155. def __init__(self, load_config: LoadConfig):
  156. self.load_config = load_config
  157. @abstractmethod
  158. def load_model(self, *, model_config: ModelConfig,
  159. device_config: DeviceConfig,
  160. lora_config: Optional[LoRAConfig],
  161. parallel_config: ParallelConfig,
  162. scheduler_config: SchedulerConfig,
  163. cache_config: CacheConfig) -> nn.Module:
  164. """Load a model with the given configurations."""
  165. ...
  166. class DefaultModelLoader(BaseModelLoader):
  167. """Model loader that can load different file types from disk."""
  168. def __init__(self, load_config: LoadConfig):
  169. super().__init__(load_config)
  170. if load_config.model_loader_extra_config:
  171. raise ValueError(f"Model loader extra config is not supported for "
  172. f"load format {load_config.load_format}")
  173. def _maybe_download_from_modelscope(
  174. self, model: str, revision: Optional[str]) -> Optional[str]:
  175. """Download model from ModelScope hub if APHRODITE_USE_MODELSCOPE is
  176. True.
  177. Returns the path to the downloaded model, or None if the model is not
  178. downloaded from ModelScope."""
  179. if APHRODITE_USE_MODELSCOPE:
  180. # download model from ModelScope hub,
  181. # lazy import so that modelscope is not required for normal use.
  182. # pylint: disable=C.
  183. from modelscope.hub.snapshot_download import snapshot_download
  184. if not os.path.exists(model):
  185. model_path = snapshot_download(
  186. model_id=model,
  187. cache_dir=self.load_config.download_dir,
  188. local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
  189. revision=revision,
  190. ignore_file_pattern=self.load_config.ignore_patterns,
  191. )
  192. else:
  193. model_path = model
  194. return model_path
  195. return None
  196. def _prepare_weights(self, model_name_or_path: str,
  197. revision: Optional[str],
  198. fall_back_to_pt: bool) -> Tuple[str, List[str], bool]:
  199. """Prepare weights for the model.
  200. If the model is not local, it will be downloaded."""
  201. model_name_or_path = self._maybe_download_from_modelscope(
  202. model_name_or_path, revision) or model_name_or_path
  203. is_local = os.path.isdir(model_name_or_path)
  204. load_format = self.load_config.load_format
  205. use_safetensors = False
  206. index_file = SAFE_WEIGHTS_INDEX_NAME
  207. # Some quantized models use .pt files for storing the weights.
  208. if load_format == LoadFormat.AUTO:
  209. allow_patterns = ["*.safetensors", "*.bin"]
  210. elif load_format == LoadFormat.SAFETENSORS:
  211. use_safetensors = True
  212. allow_patterns = ["*.safetensors"]
  213. elif load_format == LoadFormat.MISTRAL:
  214. use_safetensors = True
  215. allow_patterns = ["consolidated*.safetensors"]
  216. index_file = "consolidated.safetensors.index.json"
  217. elif load_format == LoadFormat.PT:
  218. allow_patterns = ["*.pt"]
  219. elif load_format == LoadFormat.NPCACHE:
  220. allow_patterns = ["*.bin"]
  221. else:
  222. raise ValueError(f"Unknown load_format: {load_format}")
  223. if fall_back_to_pt:
  224. allow_patterns += ["*.pt"]
  225. if not is_local:
  226. hf_folder = download_weights_from_hf(
  227. model_name_or_path,
  228. self.load_config.download_dir,
  229. allow_patterns,
  230. revision,
  231. ignore_patterns=self.load_config.ignore_patterns,
  232. )
  233. else:
  234. hf_folder = model_name_or_path
  235. hf_weights_files: List[str] = []
  236. for pattern in allow_patterns:
  237. hf_weights_files += glob.glob(os.path.join(hf_folder, pattern))
  238. if len(hf_weights_files) > 0:
  239. if pattern == "*.safetensors":
  240. use_safetensors = True
  241. break
  242. if use_safetensors:
  243. # For models like Mistral-7B-Instruct-v0.3
  244. # there are both sharded safetensors files and a consolidated
  245. # safetensors file. Using both breaks.
  246. # Here, we download the `model.safetensors.index.json` and filter
  247. # any files not found in the index.
  248. if not is_local:
  249. download_safetensors_index_file_from_hf(
  250. model_name_or_path, index_file,
  251. self.load_config.download_dir, revision)
  252. hf_weights_files = filter_duplicate_safetensors_files(
  253. hf_weights_files, hf_folder, index_file)
  254. else:
  255. hf_weights_files = filter_files_not_needed_for_inference(
  256. hf_weights_files)
  257. if len(hf_weights_files) == 0:
  258. raise RuntimeError(
  259. f"Cannot find any model weights with `{model_name_or_path}`")
  260. return hf_folder, hf_weights_files, use_safetensors
  261. def _get_weights_iterator(
  262. self, model_name_or_path: str, revision: Optional[str],
  263. fall_back_to_pt: bool
  264. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  265. """Get an iterator for the model weights based on the load format."""
  266. hf_folder, hf_weights_files, use_safetensors = self._prepare_weights(
  267. model_name_or_path, revision, fall_back_to_pt)
  268. if self.load_config.load_format == LoadFormat.NPCACHE:
  269. # Currently np_cache only support *.bin checkpoints
  270. assert use_safetensors is False
  271. weights_iterator = np_cache_weights_iterator(
  272. model_name_or_path, self.load_config.download_dir, hf_folder,
  273. hf_weights_files)
  274. elif use_safetensors:
  275. weights_iterator = safetensors_weights_iterator(hf_weights_files)
  276. else:
  277. weights_iterator = pt_weights_iterator(hf_weights_files)
  278. if current_platform.is_tpu():
  279. # In PyTorch XLA, we should call `xm.mark_step` frequently so that
  280. # not too many ops are accumulated in the XLA program.
  281. import torch_xla.core.xla_model as xm
  282. def _xla_weights_iterator(iterator: Generator):
  283. for weights in iterator:
  284. yield weights
  285. xm.mark_step()
  286. weights_iterator = _xla_weights_iterator(weights_iterator)
  287. return weights_iterator
  288. def load_model(self, *, model_config: ModelConfig,
  289. device_config: DeviceConfig,
  290. lora_config: Optional[LoRAConfig],
  291. parallel_config: ParallelConfig,
  292. scheduler_config: SchedulerConfig,
  293. cache_config: CacheConfig) -> nn.Module:
  294. target_device = torch.device(device_config.device)
  295. with set_default_torch_dtype(model_config.dtype):
  296. with target_device:
  297. model = _initialize_model(model_config, self.load_config,
  298. lora_config, cache_config,
  299. scheduler_config)
  300. model.load_weights(
  301. self._get_weights_iterator(model_config.model,
  302. model_config.revision,
  303. fall_back_to_pt=getattr(
  304. model,
  305. "fall_back_to_pt_during_load",
  306. True)), )
  307. for _, module in model.named_modules():
  308. quant_method = getattr(module, "quant_method", None)
  309. if quant_method is not None:
  310. # When quant methods need to process weights after loading
  311. # (for repacking, quantizing, etc), they expect parameters
  312. # to be on the global target device. This scope is for the
  313. # case where cpu offloading is used, where we will move the
  314. # parameters onto device for processing and back off after.
  315. with device_loading_context(module, target_device):
  316. quant_method.process_weights_after_loading(module)
  317. return model.eval()
  318. class DummyModelLoader(BaseModelLoader):
  319. """Model loader that will set model weights to random values."""
  320. def __init__(self, load_config: LoadConfig):
  321. super().__init__(load_config)
  322. if load_config.model_loader_extra_config:
  323. raise ValueError(f"Model loader extra config is not supported for "
  324. f"load format {load_config.load_format}")
  325. def load_model(self, *, model_config: ModelConfig,
  326. device_config: DeviceConfig,
  327. lora_config: Optional[LoRAConfig],
  328. parallel_config: ParallelConfig,
  329. scheduler_config: SchedulerConfig,
  330. cache_config: CacheConfig) -> nn.Module:
  331. with set_default_torch_dtype(model_config.dtype):
  332. with torch.device(device_config.device):
  333. model = _initialize_model(model_config, self.load_config,
  334. lora_config, cache_config,
  335. scheduler_config)
  336. # NOTE: For accurate performance evaluation, we assign
  337. # random values to the weights.
  338. initialize_dummy_weights(model)
  339. return model.eval()
  340. class TensorizerLoader(BaseModelLoader):
  341. """Model loader using CoreWeave's tensorizer library."""
  342. def __init__(self, load_config: LoadConfig):
  343. super().__init__(load_config)
  344. if isinstance(load_config.model_loader_extra_config, TensorizerConfig):
  345. self.tensorizer_config = load_config.model_loader_extra_config
  346. else:
  347. self.tensorizer_config = TensorizerConfig(
  348. **load_config.model_loader_extra_config)
  349. def _verify_config(self, model_config: ModelConfig,
  350. parallel_config: ParallelConfig):
  351. self.tensorizer_config.verify_with_model_config(model_config)
  352. self.tensorizer_config.verify_with_parallel_config(parallel_config)
  353. def _get_weights_iterator(
  354. self) -> Generator[Tuple[str, torch.Tensor], None, None]:
  355. tensorizer_args = self.tensorizer_config._construct_tensorizer_args()
  356. return tensorizer_weights_iterator(tensorizer_args)
  357. def _load_model_serialized_cpu(
  358. self,
  359. model_config: ModelConfig,
  360. device_config: DeviceConfig,
  361. lora_config: Optional[LoRAConfig],
  362. cache_config: CacheConfig,
  363. ) -> nn.Module:
  364. """Load a serialized model with tensorizer to the CPU.
  365. This is only necessary when the model isn't Aphrodite-tensorized (see
  366. examples/tensorize_aphrodite_model.py) This should still be faster than
  367. default HuggingFace loading, but will be slower than loading a
  368. Aphrodite-tensorized model.
  369. """
  370. with set_default_torch_dtype(model_config.dtype):
  371. with torch.device(device_config.device):
  372. model = _initialize_model(model_config, self.load_config,
  373. lora_config, cache_config)
  374. model.load_weights(self._get_weights_iterator())
  375. return model.eval()
  376. def _load_model_serialized(
  377. self,
  378. model_config: ModelConfig,
  379. device_config: DeviceConfig,
  380. lora_config: Optional[LoRAConfig],
  381. cache_config: CacheConfig,
  382. ) -> nn.Module:
  383. """Load a serialized model with tensorizer.
  384. Expects a Aphrodite-tensorized model. See the
  385. examples/tensorize_aphrodite_model.py example script
  386. for serializing Aphrodite models."""
  387. with set_default_torch_dtype(model_config.dtype):
  388. with torch.device(device_config.device):
  389. model_class = get_model_architecture(model_config)[0]
  390. quant_config = _get_quantization_config(
  391. model_config, self.load_config)
  392. extra_kwargs = _get_model_initialization_kwargs(
  393. model_class, lora_config, model_config.multimodal_config)
  394. extra_kwargs["quant_config"] = quant_config
  395. extra_kwargs["cache_config"] = cache_config
  396. tensorizer_config = copy.copy(self.tensorizer_config)
  397. tensorizer_config.model_class = model_class
  398. tensorizer_config.hf_config = model_config.hf_config
  399. tensorizer_config.dtype = model_config.dtype
  400. model = load_with_tensorizer(tensorizer_config, **extra_kwargs)
  401. return model.eval()
  402. def load_model(self, *, model_config: ModelConfig,
  403. device_config: DeviceConfig,
  404. lora_config: Optional[LoRAConfig],
  405. parallel_config: ParallelConfig,
  406. scheduler_config: SchedulerConfig,
  407. cache_config: CacheConfig) -> nn.Module:
  408. self._verify_config(model_config, parallel_config)
  409. if parallel_config.tensor_parallel_size > 1:
  410. from aphrodite.distributed import get_tensor_model_parallel_rank
  411. self.tensorizer_config.tensorizer_uri = \
  412. self.tensorizer_config.tensorizer_uri \
  413. % get_tensor_model_parallel_rank()
  414. if is_aphrodite_tensorized(self.tensorizer_config):
  415. return self._load_model_serialized(model_config, device_config,
  416. lora_config, cache_config)
  417. return self._load_model_serialized_cpu(model_config, device_config,
  418. lora_config, cache_config)
  419. @staticmethod
  420. def save_model(
  421. model: torch.nn.Module,
  422. tensorizer_config: TensorizerConfig,
  423. ) -> None:
  424. serialize_aphrodite_model(
  425. model=model,
  426. tensorizer_config=tensorizer_config,
  427. )
  428. class ShardedStateLoader(BaseModelLoader):
  429. """
  430. Model loader that directly loads each worker's model state dict, which
  431. enables a fast load path for large tensor-parallel models where each worker
  432. only needs to read its own shard rather than the entire checkpoint. See
  433. `examples/save_sharded_state.py` for creating a sharded checkpoint.
  434. """
  435. DEFAULT_PATTERN = "model-rank-{rank}-part-{part}.safetensors"
  436. def __init__(self, load_config: LoadConfig):
  437. super().__init__(load_config)
  438. extra_config = ({} if load_config.model_loader_extra_config is None
  439. else load_config.model_loader_extra_config.copy())
  440. self.pattern = extra_config.pop("pattern", self.DEFAULT_PATTERN)
  441. if extra_config:
  442. raise ValueError(f"Unexpected extra config keys for load format "
  443. f"{load_config.load_format}: "
  444. f"{load_config.model_loader_extra_config.keys()}")
  445. @staticmethod
  446. def _filter_subtensors(
  447. tensors: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
  448. """
  449. Filter out all tensors that share the same memory or a subset of the
  450. memory of another tensor.
  451. """
  452. same_storage_groups: Dict[Any, List[Tuple[
  453. str, torch.Tensor]]] = collections.defaultdict(list)
  454. for key, tensor in tensors.items():
  455. if tensor.numel():
  456. ptr = tensor.untyped_storage().data_ptr()
  457. same_storage_groups[tensor.device, ptr].append((key, tensor))
  458. def get_end_ptr(tensor: torch.Tensor) -> int:
  459. return tensor.view(-1)[-1].data_ptr() + tensor.element_size()
  460. result: Dict[str, torch.Tensor] = {}
  461. for group in same_storage_groups.values():
  462. for k, t in group:
  463. a, b = t.data_ptr(), get_end_ptr(t)
  464. for k2, t2 in group:
  465. if not t2.is_contiguous():
  466. continue
  467. a2, b2 = t2.data_ptr(), get_end_ptr(t2)
  468. if a < a2 or b2 < b:
  469. continue
  470. if a2 < a or b < b2 or not t.is_contiguous():
  471. break # t2 covers strictly more memory than t.
  472. if k2 < k:
  473. # Same tensors, keep the one with the smaller key.
  474. break
  475. else:
  476. result[k] = t
  477. return result
  478. def _prepare_weights(self, model_name_or_path: str,
  479. revision: Optional[str]):
  480. if os.path.isdir(model_name_or_path):
  481. return model_name_or_path
  482. else:
  483. allow_patterns = ["*.safetensors"]
  484. return download_weights_from_hf(
  485. model_name_or_path,
  486. self.load_config.download_dir,
  487. allow_patterns,
  488. revision,
  489. ignore_patterns=self.load_config.ignore_patterns,
  490. )
  491. def load_model(self, *, model_config: ModelConfig,
  492. device_config: DeviceConfig,
  493. lora_config: Optional[LoRAConfig],
  494. parallel_config: ParallelConfig,
  495. scheduler_config: SchedulerConfig,
  496. cache_config: CacheConfig) -> nn.Module:
  497. from safetensors.torch import safe_open
  498. from aphrodite.distributed import get_tensor_model_parallel_rank
  499. local_model_path = self._prepare_weights(model_config.model,
  500. model_config.revision)
  501. with set_default_torch_dtype(model_config.dtype):
  502. with torch.device(device_config.device):
  503. model = _initialize_model(model_config, self.load_config,
  504. lora_config, cache_config)
  505. rank = get_tensor_model_parallel_rank()
  506. pattern = os.path.join(
  507. local_model_path,
  508. self.pattern.format(rank=rank, part="*"),
  509. )
  510. filepaths = glob.glob(pattern)
  511. if not filepaths:
  512. # TODO: support un-sharded checkpoints too
  513. raise ValueError(
  514. f"Could not find checkpoint files '{pattern}', only "
  515. f"pre-sharded checkpoints are currently supported!")
  516. state_dict = self._filter_subtensors(model.state_dict())
  517. for path in filepaths:
  518. with safe_open(path, framework="pt") as f:
  519. for key in f.keys(): # noqa: SIM118
  520. tensor = f.get_tensor(key)
  521. # If loading with LoRA enabled, additional padding may
  522. # be added to certain parameters. We only load into a
  523. # narrowed view of the parameter data.
  524. param_data = state_dict[key].data
  525. param_shape = state_dict[key].shape
  526. for dim, size in enumerate(tensor.shape):
  527. if size < param_shape[dim]:
  528. param_data = param_data.narrow(dim, 0, size)
  529. if tensor.shape != param_shape:
  530. logger.warning("loading tensor of shape "
  531. f"{tensor.shape} into parameter "
  532. f"'{key}' of shape {param_shape}")
  533. param_data.copy_(tensor)
  534. state_dict.pop(key)
  535. if state_dict:
  536. raise ValueError(
  537. f"Missing keys {tuple(state_dict)} in loaded state!")
  538. return model.eval()
  539. @staticmethod
  540. def save_model(
  541. model: torch.nn.Module,
  542. path: str,
  543. pattern: Optional[str] = None,
  544. max_size: Optional[int] = None,
  545. ) -> None:
  546. from safetensors.torch import save_file
  547. from aphrodite.distributed import get_tensor_model_parallel_rank
  548. if pattern is None:
  549. pattern = ShardedStateLoader.DEFAULT_PATTERN
  550. rank = get_tensor_model_parallel_rank()
  551. part_idx = 0
  552. total_size = 0
  553. state_dict = ShardedStateLoader._filter_subtensors(model.state_dict())
  554. state_dict_part: Dict[str, torch.Tensor] = {}
  555. for key, tensor in state_dict.items():
  556. param_size = tensor.nelement() * tensor.element_size()
  557. if max_size is not None and total_size + param_size > max_size:
  558. filename = pattern.format(rank=rank, part=part_idx)
  559. save_file(
  560. state_dict_part,
  561. os.path.join(path, filename),
  562. )
  563. part_idx += 1
  564. total_size = 0
  565. state_dict_part = {}
  566. state_dict_part[key] = tensor
  567. total_size += param_size
  568. if len(state_dict_part) > 0:
  569. filename = pattern.format(rank=rank, part=part_idx)
  570. save_file(
  571. state_dict_part,
  572. os.path.join(path, filename),
  573. )
  574. class BitsAndBytesModelLoader(BaseModelLoader):
  575. """Model loader to load model weights with BitAndBytes quantization."""
  576. default_target_modules = [
  577. "gate_proj", "down_proj", "up_proj", "q_proj", "k_proj", "v_proj",
  578. "o_proj"
  579. ]
  580. possible_config_file_names = ["adapter_config.json"]
  581. def __init__(self, load_config: LoadConfig):
  582. super().__init__(load_config)
  583. # we don't need to quantize the whole model, only the target modules
  584. # that are specified in the adapter config file. If the adapter config
  585. # file is not provided, we will quantize the default modules.
  586. if (not load_config.model_loader_extra_config
  587. or "qlora_adapter_name_or_path"
  588. not in load_config.model_loader_extra_config):
  589. self.target_modules = self.default_target_modules
  590. return
  591. qlora_adapter = load_config.model_loader_extra_config[
  592. "qlora_adapter_name_or_path"]
  593. config_file_path = self._get_config_file(qlora_adapter)
  594. with open(config_file_path, "r") as f:
  595. config = json.load(f)
  596. self.target_modules = config["target_modules"]
  597. def _get_config_file(self, qlora_adapter: str) -> str:
  598. is_local = os.path.isdir(qlora_adapter)
  599. config_file_path = None
  600. if is_local:
  601. for file in self.possible_config_file_names:
  602. config_file_path = os.path.join(qlora_adapter, file)
  603. if os.path.exists(config_file_path):
  604. break
  605. else:
  606. hf_api = HfApi()
  607. repo_files = hf_api.list_repo_files(repo_id=qlora_adapter)
  608. for file in self.possible_config_file_names:
  609. if file in repo_files:
  610. config_file_path = hf_hub_download(repo_id=qlora_adapter,
  611. filename=file)
  612. break
  613. if not config_file_path:
  614. raise ValueError(
  615. f"Cannot find adapter config file in {qlora_adapter}")
  616. return config_file_path
  617. def _get_weight_files(
  618. self,
  619. model_name_or_path: str,
  620. allowed_patterns: List[str],
  621. revision: Optional[str] = None) -> Tuple[List[str], str]:
  622. """Retrieve weight files. Download the files if necessary.
  623. Return the weight files and the file pattern."""
  624. is_local = os.path.isdir(model_name_or_path)
  625. if is_local:
  626. for pattern in allowed_patterns:
  627. weight_files = glob.glob(
  628. os.path.join(model_name_or_path, pattern))
  629. if weight_files:
  630. return weight_files, pattern
  631. else:
  632. hf_api = HfApi()
  633. repo_files = hf_api.list_repo_files(repo_id=model_name_or_path)
  634. for pattern in allowed_patterns:
  635. matching_files = fnmatch.filter(repo_files, pattern)
  636. if matching_files:
  637. hf_folder = download_weights_from_hf(
  638. model_name_or_path,
  639. self.load_config.download_dir,
  640. [pattern],
  641. revision,
  642. ignore_patterns=self.load_config.ignore_patterns,
  643. )
  644. return glob.glob(os.path.join(hf_folder, pattern)), pattern
  645. raise RuntimeError(
  646. f"No model weights found in: `{model_name_or_path}`")
  647. def _prepare_weights(self, model_name_or_path: str,
  648. revision: Optional[str]) -> Tuple[List[str], bool]:
  649. """Prepare weight files for the model."""
  650. allowed_patterns = ["*.safetensors", "*.bin", "*.pt"]
  651. hf_weights_files, matched_pattern = self._get_weight_files(
  652. model_name_or_path, allowed_patterns, revision)
  653. if matched_pattern != "*.safetensors":
  654. hf_weights_files = filter_files_not_needed_for_inference(
  655. hf_weights_files)
  656. if len(hf_weights_files) == 0:
  657. raise RuntimeError(
  658. f"Cannot find any model weights with `{model_name_or_path}`")
  659. return hf_weights_files, matched_pattern == "*.safetensors"
  660. def _hf_weight_iter(self, hf_weights_files, use_safetensors: bool):
  661. if use_safetensors:
  662. return safetensors_weights_iterator(hf_weights_files)
  663. else:
  664. return pt_weights_iterator(hf_weights_files)
  665. def _get_quantized_weights_iterator(
  666. self, model_name_or_path: str, revision: Optional[str], pre_quant: bool
  667. ) -> Tuple[Generator[Tuple[str, torch.Tensor], None, None], Dict[str,
  668. Any]]:
  669. """Get an iterator to the model weights with bitsandbytes quantization,
  670. as well as the quantization state dictionary."""
  671. # only load the bitsandbytes module when needed
  672. try:
  673. import bitsandbytes
  674. from bitsandbytes.functional import QuantState
  675. if bitsandbytes.__version__ < "0.42.0":
  676. raise ImportError("bitsandbytes version is wrong. Please "
  677. "install bitsandbytes>=0.42.0.")
  678. from bitsandbytes.functional import quantize_4bit
  679. except ImportError as err:
  680. raise ImportError("Please install bitsandbytes>=0.42.0 via "
  681. "`pip install bitsandbytes>=0.42.0` to use "
  682. "bitsandbytes quantizer.") from err
  683. hf_weights_files, use_safetensors = self._prepare_weights(
  684. model_name_or_path, revision)
  685. quant_state_dict = {}
  686. def quantized_checkpoint() -> Generator:
  687. # First iterate over all quant state weights
  688. weight_iterator = self._hf_weight_iter(hf_weights_files,
  689. use_safetensors)
  690. temp_state_dict = {}
  691. for weight_name, weight_tensor in weight_iterator:
  692. if weight_name.endswith(".weight"):
  693. continue
  694. # TODO: only nf4 quantization is supported for now
  695. if weight_name.endswith(".quant_state.bitsandbytes__fp4"):
  696. raise NotImplementedError(
  697. "Only bitsandbytes_nf4 quantization"
  698. f"is supported for now. {weight_name} is fp4 quantized"
  699. )
  700. temp_state_dict[weight_name] = weight_tensor
  701. # Closure to parse quant_state for each prequant weight
  702. def _parse_quant_state(param_name: str,
  703. temp_state_dict: Dict) -> QuantState:
  704. quant_state = {}
  705. for k in temp_state_dict:
  706. if param_name + "." in k:
  707. quant_state[k] = temp_state_dict[k]
  708. # bitsandbytes library requires
  709. # weight.quant_state.bitsandbytes__nf4 in CPU
  710. quant_state[param_name +
  711. ".quant_state.bitsandbytes__nf4"] = quant_state[
  712. param_name +
  713. ".quant_state.bitsandbytes__nf4"].cpu().data
  714. return QuantState.from_dict(quant_state, device="cuda")
  715. # Second iterate over all prequant and normal weights
  716. # pre quantized weights would have a quant_state
  717. for weight_name, weight_tensor in self._hf_weight_iter(
  718. hf_weights_files, use_safetensors):
  719. # Filter out all weights whose suffix is not ".weight"
  720. if not weight_name.endswith(".weight"):
  721. continue
  722. if weight_name + ".quant_state.bitsandbytes__nf4" \
  723. in temp_state_dict:
  724. quant_state = _parse_quant_state(weight_name,
  725. temp_state_dict)
  726. weight_name = weight_name.replace(".weight", ".qweight")
  727. quant_state_dict[weight_name] = quant_state
  728. yield weight_name.replace(".weight",
  729. ".qweight"), weight_tensor
  730. else:
  731. yield weight_name, weight_tensor
  732. def generator() -> Generator:
  733. for weight_name, weight_tensor in self._hf_weight_iter(
  734. hf_weights_files, use_safetensors):
  735. if any(target_module in weight_name
  736. for target_module in self.target_modules):
  737. weight_name = weight_name.replace(".weight", ".qweight")
  738. # bitsandbytes requires data in GPU
  739. loaded_weight = weight_tensor.cuda().data
  740. with set_default_torch_dtype(torch.float32):
  741. processed_weight, quant_state = quantize_4bit(
  742. loaded_weight,
  743. compress_statistics=True,
  744. quant_type="nf4")
  745. quant_state_dict[weight_name] = quant_state
  746. else:
  747. processed_weight = weight_tensor
  748. yield weight_name, processed_weight
  749. if pre_quant:
  750. return quantized_checkpoint(), quant_state_dict
  751. return generator(), quant_state_dict
  752. def _load_weights(self, model_config: ModelConfig,
  753. model: nn.Module) -> None:
  754. if not hasattr(model, 'load_weights'):
  755. raise AttributeError(
  756. "The required method 'load_weights' is not defined in class"
  757. f" {type(self).__name__}.")
  758. if not hasattr(model, 'bitsandbytes_stacked_params_mapping'):
  759. raise AttributeError(
  760. f"Model {type(self).__name__} does not support BitsAndBytes "
  761. "quantization yet.")
  762. logger.info("Loading weights with BitsAndBytes quantization. "
  763. "This May take a while ...")
  764. is_quantized_checkpoint = False
  765. quant_config = getattr(model_config.hf_config, "quantization_config",
  766. None)
  767. if quant_config is not None and quant_config.get(
  768. 'quant_method') == "bitsandbytes":
  769. is_quantized_checkpoint = True
  770. qweight_iterator, quant_state_dict = \
  771. self._get_quantized_weights_iterator(
  772. model_config.model, model_config.revision, is_quantized_checkpoint)
  773. model.load_weights(qweight_iterator)
  774. torch.cuda.empty_cache()
  775. param_dict = dict(model.named_parameters())
  776. stacked_quant_state_dict: Dict[str, Dict[int, Any]] = {}
  777. for quant_param_name in quant_state_dict:
  778. non_stacked_param_name = quant_param_name
  779. shard_index = 0
  780. for shard_name, (
  781. weight_name, index
  782. ) in model.bitsandbytes_stacked_params_mapping.items():
  783. if shard_name in quant_param_name:
  784. shard_index = index
  785. quant_param_name = quant_param_name.replace(
  786. shard_name, weight_name)
  787. break
  788. if quant_param_name not in param_dict:
  789. raise ValueError(
  790. f"Parameter {quant_param_name} not found in the model.")
  791. if quant_param_name not in stacked_quant_state_dict:
  792. stacked_quant_state_dict[quant_param_name] = {}
  793. stacked_quant_state_dict[quant_param_name][shard_index] = (
  794. quant_state_dict[non_stacked_param_name])
  795. # save quant_states and offsets as the attributes of the parameters
  796. for param_name, param in param_dict.items():
  797. if param_name in stacked_quant_state_dict:
  798. quant_states = stacked_quant_state_dict[param_name]
  799. set_weight_attrs(param, {"bnb_quant_state": quant_states})
  800. pack_ratio = getattr(param, "pack_factor", -1)
  801. if pack_ratio == -1:
  802. raise ValueError(
  803. f"pack_factor not set for parameter {param_name}.")
  804. num_elements = [0] * len(quant_states)
  805. for seq, quant_state in quant_states.items():
  806. num_elements[seq] = math.prod(
  807. quant_state.shape) // pack_ratio
  808. offsets = np.concatenate(([0], np.cumsum(num_elements)))
  809. set_weight_attrs(param, {"bnb_shard_offsets": offsets})
  810. def load_model(self, *, model_config: ModelConfig,
  811. device_config: DeviceConfig,
  812. lora_config: Optional[LoRAConfig],
  813. parallel_config: ParallelConfig,
  814. scheduler_config: SchedulerConfig,
  815. cache_config: CacheConfig) -> nn.Module:
  816. with set_default_torch_dtype(model_config.dtype):
  817. with torch.device(device_config.device):
  818. model = _initialize_model(model_config, self.load_config,
  819. lora_config, cache_config)
  820. self._load_weights(model_config, model)
  821. return model.eval()
  822. class GGUFModelLoader(BaseModelLoader):
  823. """
  824. Model loader that can load GGUF files. This is useful for loading models
  825. that are quantized with GGUF and saved in the GGUF format. This loader
  826. supports loading both full models and sharded models.
  827. """
  828. def __init__(self, load_config: LoadConfig):
  829. super().__init__(load_config)
  830. if load_config.model_loader_extra_config:
  831. raise ValueError(f"Model loader extra config is not supported for "
  832. f"load format {load_config.load_format}")
  833. def _prepare_weights(self, model_name_or_path: str):
  834. if os.path.isfile(model_name_or_path):
  835. return model_name_or_path
  836. else:
  837. raise ValueError(f"{model_name_or_path} is not a file.")
  838. def _get_gguf_weights_map(self, model_config: ModelConfig):
  839. """
  840. GGUF uses this naming convention for their tensors from HF checkpoint:
  841. `blk.N.BB.weight` and `blk.N.BB.bias`
  842. where N signifies the block number of a layer, and BB signifies the
  843. attention/mlp layer components.
  844. See "Standardized tensor names" in
  845. https://github.com/ggerganov/ggml/blob/master/docs/gguf.md for details.
  846. """
  847. config = model_config.hf_config
  848. model_type = config.model_type
  849. # hack: ggufs have a different name than transformers
  850. if model_type == "cohere":
  851. model_type = "command-r"
  852. arch = None
  853. for key, value in gguf.MODEL_ARCH_NAMES.items():
  854. if value == model_type:
  855. arch = key
  856. break
  857. if arch is None:
  858. raise RuntimeError(f"Unknown gguf model_type: {model_type}")
  859. num_layers = config.num_hidden_layers
  860. name_map = gguf.get_tensor_name_map(arch, num_layers)
  861. with torch.device("meta"):
  862. dummy_model = AutoModelForCausalLM.from_config(config)
  863. state_dict = dummy_model.state_dict()
  864. gguf_to_hf_name_map = {}
  865. for hf_name in state_dict:
  866. name, suffix = hf_name.rsplit(".", 1)
  867. gguf_name = name_map.get_name(name)
  868. gguf_to_hf_name_map[f"{gguf_name}.{suffix}"] = hf_name
  869. return gguf_to_hf_name_map
  870. def _get_weights_iterator(
  871. self, model_name_or_path: str, gguf_to_hf_name_map: Dict[str, str]
  872. ) -> Generator[Tuple[str, torch.Tensor], None, None]:
  873. return gguf_quant_weights_iterator(model_name_or_path,
  874. gguf_to_hf_name_map)
  875. def load_model(self, *, model_config: ModelConfig,
  876. device_config: DeviceConfig,
  877. lora_config: Optional[LoRAConfig],
  878. parallel_config: ParallelConfig,
  879. scheduler_config: SchedulerConfig,
  880. cache_config: CacheConfig) -> nn.Module:
  881. local_model_path = self._prepare_weights(model_config.model)
  882. gguf_weights_map = self._get_gguf_weights_map(model_config)
  883. # we can only know if tie word embeddings after mapping weights
  884. if "lm_head.weight" in get_gguf_extra_tensor_names(
  885. local_model_path, gguf_weights_map):
  886. model_config.hf_config.update({"tie_word_embeddings": True})
  887. with set_default_torch_dtype(model_config.dtype):
  888. with torch.device(device_config.device):
  889. model = _initialize_model(model_config, self.load_config,
  890. lora_config, cache_config)
  891. model.load_weights(
  892. self._get_weights_iterator(local_model_path, gguf_weights_map))
  893. return model
  894. def get_model_loader(load_config: LoadConfig) -> BaseModelLoader:
  895. """Get a model loader based on the load format."""
  896. if isinstance(load_config.load_format, type):
  897. return load_config.load_format(load_config)
  898. if load_config.load_format == LoadFormat.DUMMY:
  899. return DummyModelLoader(load_config)
  900. if load_config.load_format == LoadFormat.TENSORIZER:
  901. return TensorizerLoader(load_config)
  902. if load_config.load_format == LoadFormat.SHARDED_STATE:
  903. return ShardedStateLoader(load_config)
  904. if load_config.load_format == LoadFormat.BITSANDBYTES:
  905. return BitsAndBytesModelLoader(load_config)
  906. if load_config.load_format == LoadFormat.GGUF:
  907. return GGUFModelLoader(load_config)
  908. return DefaultModelLoader(load_config)