quantizer_vptq.py 2.5 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 typing import TYPE_CHECKING
  15. from .base import HfQuantizer
  16. if TYPE_CHECKING:
  17. from ..modeling_utils import PreTrainedModel
  18. from ..utils.quantization_config import VptqConfig
  19. from ..utils import is_accelerate_available, is_torch_available, is_vptq_available, logging
  20. from ..utils.quantization_config import QuantizationConfigMixin
  21. if is_torch_available():
  22. import torch
  23. logger = logging.get_logger(__name__)
  24. class VptqHfQuantizer(HfQuantizer):
  25. """
  26. Quantizer of the VPTQ method. Enables the loading of prequantized models.
  27. """
  28. requires_calibration = True
  29. quantization_config: "VptqConfig"
  30. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  31. super().__init__(quantization_config, **kwargs)
  32. def validate_environment(self, *args, **kwargs):
  33. if not is_accelerate_available():
  34. raise ImportError("Using `vptq` quantization requires Accelerate: `pip install accelerate`")
  35. if not is_vptq_available():
  36. raise ImportError("Using `vptq` quantization requires VPTQ>=0.0.4: `pip install -U vptq`")
  37. if not torch.cuda.is_available():
  38. raise RuntimeError("GPU is required to run VTPQ quantized model.")
  39. def _process_model_before_weight_loading(
  40. self,
  41. model: "PreTrainedModel",
  42. **kwargs,
  43. ):
  44. from ..integrations import replace_with_vptq_linear
  45. self.modules_to_not_convert = self.get_modules_to_not_convert(
  46. model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
  47. )
  48. replace_with_vptq_linear(
  49. model,
  50. quantization_config=self.quantization_config,
  51. modules_to_not_convert=self.modules_to_not_convert,
  52. )
  53. @property
  54. def is_trainable(self) -> bool:
  55. return False
  56. def is_serializable(self):
  57. return True