quantizer_aqlm.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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, Optional
  16. from packaging import version
  17. from .base import HfQuantizer
  18. if TYPE_CHECKING:
  19. from ..modeling_utils import PreTrainedModel
  20. from ..integrations import replace_with_aqlm_linear
  21. from ..utils import is_accelerate_available, is_aqlm_available, is_torch_available, logging
  22. from ..utils.quantization_config import QuantizationConfigMixin
  23. if is_torch_available():
  24. import torch
  25. logger = logging.get_logger(__name__)
  26. class AqlmHfQuantizer(HfQuantizer):
  27. """
  28. Quantizer of the AQLM method. Enables the loading of prequantized models.
  29. """
  30. requires_calibration = True
  31. required_packages = ["aqlm"]
  32. optimum_quantizer = None
  33. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  34. super().__init__(quantization_config, **kwargs)
  35. self.quantization_config = quantization_config
  36. def validate_environment(self, *args, **kwargs):
  37. if not is_accelerate_available():
  38. raise ImportError("Using `aqlm` quantization requires Accelerate: `pip install accelerate`")
  39. if not is_aqlm_available():
  40. raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`")
  41. def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
  42. if torch_dtype is None:
  43. if torch.cuda.is_available():
  44. torch_dtype = torch.float16
  45. logger.info(
  46. "CUDA available. Assuming AQLM inference on GPU and loading the model in `torch.float16`. To overwrite it, set `torch_dtype` manually."
  47. )
  48. else:
  49. torch_dtype = torch.float32
  50. logger.info(
  51. "CUDA is unavailable. Assuming AQLM inference on CPU and loading the model in `torch.float32`. To overwrite it, set `torch_dtype` manually."
  52. )
  53. return torch_dtype
  54. def _process_model_before_weight_loading(
  55. self,
  56. model: "PreTrainedModel",
  57. **kwargs,
  58. ):
  59. replace_with_aqlm_linear(
  60. model,
  61. quantization_config=self.quantization_config,
  62. linear_weights_not_to_quantize=self.quantization_config.linear_weights_not_to_quantize,
  63. )
  64. model.config.quantization_config = self.quantization_config
  65. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  66. return model
  67. @property
  68. def is_trainable(self, model: Optional["PreTrainedModel"] = None):
  69. aqlm_supports_training = version.parse(importlib.metadata.version("aqlm")) >= version.parse("1.0.2")
  70. if aqlm_supports_training:
  71. return True
  72. else:
  73. logger.warning(
  74. f"Currently installed `aqlm` version ({importlib.metadata.version('aqlm')}) doesn't support training. If you wish to train a quantized model, please update `aqlm` with `pip install aqlm>=1.0.2`"
  75. )
  76. return False
  77. def is_serializable(self, safe_serialization=None):
  78. return True