quantizer_aqlm.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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.quantization_config import AqlmConfig
  21. from ..integrations import replace_with_aqlm_linear
  22. from ..utils import is_accelerate_available, is_aqlm_available, logging
  23. from ..utils.quantization_config import QuantizationConfigMixin
  24. logger = logging.get_logger(__name__)
  25. class AqlmHfQuantizer(HfQuantizer):
  26. """
  27. Quantizer of the AQLM method. Enables the loading of prequantized models.
  28. """
  29. requires_calibration = True
  30. quantization_config: "AqlmConfig"
  31. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  32. super().__init__(quantization_config, **kwargs)
  33. def validate_environment(self, *args, **kwargs):
  34. if not is_accelerate_available():
  35. raise ImportError("Using `aqlm` quantization requires Accelerate: `pip install accelerate`")
  36. if not is_aqlm_available():
  37. raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`")
  38. def _process_model_before_weight_loading(
  39. self,
  40. model: "PreTrainedModel",
  41. **kwargs,
  42. ):
  43. replace_with_aqlm_linear(
  44. model,
  45. modules_to_not_convert=self.quantization_config.linear_weights_not_to_quantize,
  46. quantization_config=self.quantization_config,
  47. )
  48. @property
  49. def is_trainable(self) -> bool:
  50. aqlm_supports_training = version.parse(metadata.version("aqlm")) >= version.parse("1.0.2")
  51. if aqlm_supports_training:
  52. return True
  53. else:
  54. logger.warning(
  55. f"Currently installed `aqlm` version ({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`"
  56. )
  57. return False
  58. def is_serializable(self):
  59. return True