quantizer_awq.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import importlib.metadata
  15. from typing import TYPE_CHECKING, Optional
  16. from packaging import version
  17. from .base import HfQuantizer
  18. if TYPE_CHECKING:
  19. from ..modeling_utils import PreTrainedModel
  20. from ..utils import is_accelerate_available, is_auto_awq_available, is_torch_available, logging
  21. from ..utils.quantization_config import AWQLinearVersion
  22. if is_torch_available():
  23. import torch
  24. logger = logging.get_logger(__name__)
  25. class AwqQuantizer(HfQuantizer):
  26. """
  27. 4-bit quantization for Activation-aware Weight Quantization(AWQ) (https://huggingface.co/papers/2306.00978)
  28. """
  29. # AWQ requires data calibration - we support only inference
  30. requires_calibration = True
  31. required_packages = ["awq", "accelerate"]
  32. def __init__(self, quantization_config, **kwargs):
  33. super().__init__(quantization_config, **kwargs)
  34. def validate_environment(self, device_map, **kwargs):
  35. if not is_auto_awq_available():
  36. raise ImportError("Loading an AWQ quantized model requires auto-awq library (`pip install autoawq`)")
  37. if not is_accelerate_available():
  38. raise ImportError("Loading an AWQ quantized model requires accelerate (`pip install accelerate`)")
  39. if (
  40. self.quantization_config.version == AWQLinearVersion.GEMM
  41. and not torch.cuda.is_available()
  42. and not torch.xpu.is_available()
  43. ):
  44. logger.warning_once("No CUDA or XPU found, consider switching to the IPEX version for CPU-only execution.")
  45. self.quantization_config.version = AWQLinearVersion.IPEX
  46. if self.quantization_config.version == AWQLinearVersion.IPEX:
  47. if version.parse(importlib.metadata.version("autoawq")) < version.parse("0.2.6"):
  48. raise RuntimeError(
  49. "To use IPEX backend, you need autoawq>0.2.6. Please install the latest version or from source."
  50. )
  51. if device_map is None:
  52. logger.warning_once(
  53. "You have loaded an AWQ model without setting device_map, please set 'cpu' or 'xpu' or 'auto'"
  54. )
  55. elif isinstance(device_map, dict) and "disk" in device_map.values():
  56. raise ValueError(
  57. "You are attempting to load an IPEX version AWQ model with a device_map that contains disk device."
  58. " This is not supported. Please make sure only cpu and xpu in the device_map."
  59. )
  60. else:
  61. if not torch.cuda.is_available() and not torch.xpu.is_available():
  62. raise RuntimeError(
  63. "GPU is required to run AWQ quantized model. You can use IPEX version AWQ if you have an Intel CPU"
  64. )
  65. if device_map is None:
  66. logger.warning_once(
  67. "You have loaded an AWQ model on CPU and have a CUDA/XPU device available, make sure to set "
  68. "your model on a GPU device in order to run your model."
  69. )
  70. elif device_map is not None:
  71. if isinstance(device_map, dict) and any(
  72. forbidden in device_map.values() for forbidden in ("cpu", torch.device("cpu"), "disk")
  73. ):
  74. raise ValueError(
  75. "You are attempting to load an AWQ model with a device_map that contains a CPU or disk device."
  76. " This is not supported. Please remove the CPU or disk device from the device_map."
  77. )
  78. def update_dtype(self, dtype):
  79. if dtype is None:
  80. dtype = torch.float16
  81. logger.info("Loading the model in `torch.float16`. To overwrite it, set `dtype` manually.")
  82. elif dtype == torch.bfloat16 and (torch.cuda.is_available() or torch.xpu.is_available()):
  83. logger.warning(
  84. "`torch.bfloat16` is not supported for AWQ CUDA/XPU kernels yet. Casting to `torch.float16`."
  85. )
  86. dtype = torch.float16
  87. elif dtype != torch.float16 and (torch.cuda.is_available() or torch.xpu.is_available()):
  88. logger.warning("We suggest you to set `dtype=torch.float16` for better efficiency on CUDA/XPU with AWQ.")
  89. return dtype
  90. def _process_model_before_weight_loading(
  91. self, model: "PreTrainedModel", keep_in_fp32_modules: Optional[list[str]] = None, **kwargs
  92. ):
  93. from ..integrations import replace_quantization_scales, replace_with_awq_linear
  94. self.modules_to_not_convert = self.get_modules_to_not_convert(
  95. model, self.quantization_config.modules_to_not_convert, keep_in_fp32_modules, add_default_skips=True
  96. )
  97. model, has_been_replaced = replace_with_awq_linear(
  98. model, quantization_config=self.quantization_config, modules_to_not_convert=self.modules_to_not_convert
  99. )
  100. model = replace_quantization_scales(model, model.config.model_type)
  101. if not has_been_replaced:
  102. logger.warning(
  103. "You are loading an AWQ model but no linear modules were found in your model."
  104. " Please double check your model architecture, or submit an issue on github if you think this is a bug."
  105. )
  106. def _process_model_after_weight_loading(self, model, **kwargs):
  107. if self.quantization_config.do_fuse:
  108. from ..integrations import fuse_awq_modules
  109. model = fuse_awq_modules(model, self.quantization_config)
  110. model._awq_is_fused = True # TODO: consider storing this flag in model.config instead
  111. if self.quantization_config.version == AWQLinearVersion.EXLLAMA:
  112. from ..integrations import post_init_awq_exllama_modules
  113. model = post_init_awq_exllama_modules(model, self.quantization_config.exllama_config)
  114. if self.quantization_config.version == AWQLinearVersion.IPEX:
  115. from ..integrations import post_init_awq_ipex_modules
  116. model = post_init_awq_ipex_modules(model)
  117. def is_serializable(self, safe_serialization=None):
  118. # AWQ through auto-awq has been always serializable, except if the model is fused.
  119. if self.quantization_config.do_fuse:
  120. logger.warning("You cannot save an AWQ model that uses fused modules!")
  121. return False
  122. if self.quantization_config.version == AWQLinearVersion.EXLLAMA:
  123. logger.warning("You cannot save an AWQ model that uses Exllama backend!")
  124. return False
  125. return True
  126. @property
  127. def is_trainable(self):
  128. # AWQ supports PEFT fine-tuning from version 0.2.0
  129. MIN_AWQ_VERSION_FOR_PEFT = "0.2.0"
  130. return version.parse(importlib.metadata.version("autoawq")) >= version.parse(MIN_AWQ_VERSION_FOR_PEFT)