quantizer_gptq.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. from importlib import metadata
  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_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. MIN_GPTQ_VERSION = "1.4.3"
  26. MIN_OPTIMUM_VERSION = "1.24.0"
  27. class GptqHfQuantizer(HfQuantizer):
  28. """
  29. Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through
  30. the GPT-QModel package (Python import name `gptqmodel`). Quantization is done under the hood for users if they
  31. load a non-prequantized model.
  32. """
  33. requires_calibration = False
  34. quantization_config: "GPTQConfig"
  35. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  36. super().__init__(quantization_config, **kwargs)
  37. if not is_optimum_available():
  38. raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)")
  39. from optimum.gptq import GPTQQuantizer
  40. self.optimum_quantizer = GPTQQuantizer.from_dict(self.quantization_config.to_dict_optimum())
  41. def validate_environment(self, *args, **kwargs):
  42. if not is_optimum_available():
  43. raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)")
  44. gptq_supports_cpu = is_gptqmodel_available()
  45. if not gptq_supports_cpu and not torch.cuda.is_available():
  46. raise RuntimeError("GPU is required to quantize or run quantize model.")
  47. elif not is_gptqmodel_available():
  48. raise ImportError("Loading a GPTQ quantized model requires gptqmodel (`pip install gptqmodel`) library.")
  49. elif is_gptqmodel_available() and (
  50. version.parse(metadata.version("gptqmodel")) < version.parse(MIN_GPTQ_VERSION)
  51. or version.parse(metadata.version("optimum")) < version.parse(MIN_OPTIMUM_VERSION)
  52. ):
  53. raise ImportError(
  54. f"The gptqmodel version should be >= {MIN_GPTQ_VERSION}, optimum version should >= {MIN_OPTIMUM_VERSION}"
  55. )
  56. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  57. if dtype != torch.float16:
  58. logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with GPTQ.")
  59. return dtype
  60. def update_device_map(self, device_map):
  61. if device_map is None:
  62. device_map = {"": torch.device("cpu")}
  63. return device_map
  64. def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
  65. if model.__class__.main_input_name != "input_ids":
  66. raise RuntimeError("We can only quantize pure text model.")
  67. if self.pre_quantized:
  68. # compat: latest optimum has gptqmodel refactor
  69. if version.parse(metadata.version("optimum")) < version.parse(MIN_OPTIMUM_VERSION):
  70. model = self.optimum_quantizer.convert_model(model)
  71. else:
  72. model = self.optimum_quantizer.convert_model(model, **kwargs)
  73. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  74. if self.pre_quantized:
  75. model = self.optimum_quantizer.post_init_model(model)
  76. else:
  77. if self.quantization_config.tokenizer is None:
  78. self.quantization_config.tokenizer = model.name_or_path
  79. self.optimum_quantizer.quantize_model(model, self.quantization_config.tokenizer)
  80. model.config.quantization_config = GPTQConfig.from_dict(self.optimum_quantizer.to_dict())
  81. @property
  82. def is_trainable(self) -> bool:
  83. return True
  84. def is_serializable(self):
  85. return True