loader.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """Utilities for selecting and loading models."""
  2. import contextlib
  3. import gc
  4. from contextlib import nullcontext
  5. from typing import Optional, Type
  6. from loguru import logger
  7. import torch
  8. import torch.nn as nn
  9. from aphrodite.common.config import DeviceConfig, ModelConfig, LoRAConfig
  10. from aphrodite.modeling.models import ModelRegistry
  11. from aphrodite.modeling.hf_downloader import (get_quant_config,
  12. initialize_dummy_weights)
  13. from aphrodite.modeling.layers.quantization.bitsandbytes import (
  14. BNBLinearMethod, replace_quant_params)
  15. @contextlib.contextmanager
  16. def _set_default_torch_dtype(dtype: torch.dtype):
  17. """Sets the default torch dtype to the given dtype."""
  18. old_dtype = torch.get_default_dtype()
  19. torch.set_default_dtype(dtype)
  20. yield
  21. torch.set_default_dtype(old_dtype)
  22. def _get_model_architecture(model_config: ModelConfig) -> Type[nn.Module]:
  23. architectures = getattr(model_config.hf_config, "architectures", [])
  24. # Special handling for quantized Mixtral.
  25. # FIXME: This is a temporary hack.
  26. if (model_config.quantization is not None
  27. and "MixtralForCausalLM" in architectures):
  28. architectures = ["QuantMixtralForCausalLM"]
  29. for arch in architectures:
  30. model_cls = ModelRegistry.load_model_cls(arch)
  31. if model_cls is not None:
  32. return model_cls
  33. raise ValueError(
  34. f"Model architectures {architectures} are not supported for now. "
  35. f"Supported architectures: {ModelRegistry.get_supported_archs()}")
  36. def get_model(model_config: ModelConfig,
  37. device_config: DeviceConfig,
  38. lora_config: Optional[LoRAConfig] = None) -> nn.Module:
  39. model_class = _get_model_architecture(model_config)
  40. # Get the (maybe quantized) linear method.
  41. linear_method = None
  42. if model_config.quantization is not None:
  43. quant_config = get_quant_config(model_config)
  44. capability = torch.cuda.get_device_capability()
  45. capability = capability[0] * 10 + capability[1]
  46. if capability < quant_config.get_min_capability():
  47. raise ValueError(
  48. f"The quantization method {model_config.quantization} is not "
  49. "supported for the current GPU. "
  50. f"Minimum capability: {quant_config.get_min_capability()}. "
  51. f"Current capability: {capability}.")
  52. supported_dtypes = quant_config.get_supported_act_dtypes()
  53. if model_config.dtype not in supported_dtypes:
  54. # set the dtype to float16 for quantized models
  55. model_config.dtype = torch.float16
  56. logger.warning("Model is quantized. Forcing float16 datatype.")
  57. linear_method = quant_config.get_linear_method()
  58. with _set_default_torch_dtype(model_config.dtype):
  59. # Create a model instance.
  60. # The weights will be initialized as empty tensors.
  61. with torch.device(device_config.device) if not \
  62. (isinstance(linear_method, BNBLinearMethod) and
  63. linear_method.quant_config.from_float) else nullcontext():
  64. if hasattr(model_class, "supported_lora_modules"):
  65. model = model_class(model_config.hf_config, linear_method,
  66. lora_config)
  67. elif lora_config:
  68. raise ValueError(
  69. f"Model {model_class.__name__} does not support LoRA, "
  70. "but LoRA is enabled. Support for this model may "
  71. "be added in the future. If this is important to you, "
  72. "please open an issue on github.")
  73. else:
  74. model = model_class(model_config.hf_config, linear_method)
  75. if model_config.load_format == "dummy":
  76. # NOTE: For accurate performance evaluation, we assign
  77. # random values to the weights.
  78. initialize_dummy_weights(model)
  79. else:
  80. # Load the weights from the cached or downloaded files.
  81. model.load_weights(model_config.model, model_config.download_dir,
  82. model_config.load_format, model_config.revision)
  83. if isinstance(linear_method, BNBLinearMethod):
  84. replace_quant_params(model,
  85. quant_config=linear_method.quant_config,
  86. modules_to_not_convert="lm_head")
  87. torch.cuda.synchronize()
  88. if linear_method.quant_config.from_float:
  89. model = model.cuda()
  90. gc.collect()
  91. torch.cuda.empty_cache()
  92. logger.info("Memory allocated for converted model: {} GiB".format(
  93. round(
  94. torch.cuda.memory_allocated(torch.cuda.current_device()) /
  95. (1024 * 1024 * 1024), 2)))
  96. logger.info("Memory reserved for converted model: {} GiB".format(
  97. round(
  98. torch.cuda.memory_reserved(torch.cuda.current_device()) /
  99. (1024 * 1024 * 1024), 2)))
  100. return model.eval()