quantizer_gptq.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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
  15. from typing import TYPE_CHECKING
  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_auto_gptq_available, is_gptqmodel_available, is_optimum_available, is_torch_available, logging
  21. from ..utils.quantization_config import GPTQConfig, QuantizationConfigMixin
  22. if is_torch_available():
  23. import torch
  24. logger = logging.get_logger(__name__)
  25. class GptqHfQuantizer(HfQuantizer):
  26. """
  27. Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through
  28. `auto_gptq` or `gptqmodel` package. Quantization is done under the hood for users if they load a non-prequantized model.
  29. """
  30. requires_calibration = False
  31. required_packages = ["optimum", "auto_gptq", "gptqmodel"]
  32. optimum_quantizer = None
  33. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  34. super().__init__(quantization_config, **kwargs)
  35. if not is_optimum_available():
  36. raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)")
  37. from optimum.gptq import GPTQQuantizer
  38. self.optimum_quantizer = GPTQQuantizer.from_dict(self.quantization_config.to_dict_optimum())
  39. def validate_environment(self, *args, **kwargs):
  40. if not is_optimum_available():
  41. raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)")
  42. if is_auto_gptq_available() and is_gptqmodel_available():
  43. logger.warning("Detected gptqmodel and auto-gptq, will use gptqmodel")
  44. gptq_supports_cpu = (
  45. is_auto_gptq_available()
  46. and version.parse(importlib.metadata.version("auto-gptq")) > version.parse("0.4.2")
  47. ) or is_gptqmodel_available()
  48. if not gptq_supports_cpu and not torch.cuda.is_available():
  49. raise RuntimeError("GPU is required to quantize or run quantize model.")
  50. elif not (is_auto_gptq_available() or is_gptqmodel_available()):
  51. raise ImportError(
  52. "Loading a GPTQ quantized model requires gptqmodel (`pip install gptqmodel`) or auto-gptq (`pip install auto-gptq`) library. "
  53. )
  54. elif is_auto_gptq_available() and version.parse(importlib.metadata.version("auto_gptq")) < version.parse(
  55. "0.4.2"
  56. ):
  57. raise ImportError(
  58. "You need a version of auto_gptq >= 0.4.2 to use GPTQ: `pip install --upgrade auto-gptq` or use gptqmodel by `pip install gptqmodel>=1.4.3`."
  59. )
  60. elif is_gptqmodel_available() and (
  61. version.parse(importlib.metadata.version("gptqmodel")) < version.parse("1.4.3")
  62. or version.parse(importlib.metadata.version("optimum")) < version.parse("1.23.99")
  63. ):
  64. raise ImportError("The gptqmodel version should be >= 1.4.3, optimum version should >= 1.24.0")
  65. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  66. if dtype is None:
  67. dtype = torch.float16
  68. logger.info("Loading the model in `torch.float16`. To overwrite it, set `dtype` manually.")
  69. elif dtype != torch.float16:
  70. logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with GPTQ.")
  71. return dtype
  72. def update_device_map(self, device_map):
  73. if device_map is None:
  74. device_map = {"": torch.device("cpu")}
  75. # Only with auto-gptq do not support CPU, we should move the model to cuda if available.
  76. if not is_gptqmodel_available() and device_map in ("cpu", {"": torch.device("cpu")}):
  77. device_map == {"": 0}
  78. return device_map
  79. def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
  80. if model.__class__.main_input_name != "input_ids":
  81. raise RuntimeError("We can only quantize pure text model.")
  82. if self.pre_quantized:
  83. # compat: latest optimum has gptqmodel refactor
  84. if version.parse(importlib.metadata.version("optimum")) <= version.parse("1.23.99"):
  85. model = self.optimum_quantizer.convert_model(model)
  86. else:
  87. model = self.optimum_quantizer.convert_model(model, **kwargs)
  88. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  89. if self.pre_quantized:
  90. model = self.optimum_quantizer.post_init_model(model)
  91. else:
  92. if self.quantization_config.tokenizer is None:
  93. self.quantization_config.tokenizer = model.name_or_path
  94. self.optimum_quantizer.quantize_model(model, self.quantization_config.tokenizer)
  95. model.config.quantization_config = GPTQConfig.from_dict(self.optimum_quantizer.to_dict())
  96. @property
  97. def is_trainable(self) -> bool:
  98. return True
  99. def is_serializable(self, safe_serialization=None):
  100. return True