quantizer_spqr.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/lic enses/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 SpQRConfig
  19. from ..integrations import replace_with_spqr_linear
  20. from ..utils import is_accelerate_available, is_spqr_available, is_torch_available, logging
  21. from ..utils.quantization_config import QuantizationConfigMixin
  22. if is_torch_available():
  23. import torch
  24. logger = logging.get_logger(__name__)
  25. class SpQRHfQuantizer(HfQuantizer):
  26. """
  27. Quantizer of the SpQR method. Enables the loading of prequantized models.
  28. """
  29. requires_calibration = True
  30. quantization_config: "SpQRConfig"
  31. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  32. super().__init__(quantization_config, **kwargs)
  33. def validate_environment(self, *args, **kwargs):
  34. if not torch.cuda.is_available():
  35. raise RuntimeError("GPU is required to run SpQR quantized model.")
  36. if not is_accelerate_available():
  37. raise ImportError("Using `spqr` quantization requires Accelerate: `pip install accelerate`")
  38. if not is_spqr_available():
  39. raise ImportError("Using `spqr` quantization requires SpQR: `pip install spqr_quant[gpu]`")
  40. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  41. if dtype != torch.float16:
  42. raise ValueError(
  43. "You cannot use any type other than torch.float16 for SpQR. Please set it totorch.float16 explicitly."
  44. )
  45. return dtype
  46. def _process_model_before_weight_loading(
  47. self,
  48. model: "PreTrainedModel",
  49. **kwargs,
  50. ):
  51. self.modules_to_not_convert = self.get_modules_to_not_convert(
  52. model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
  53. )
  54. replace_with_spqr_linear(
  55. model,
  56. quantization_config=self.quantization_config,
  57. modules_to_not_convert=self.modules_to_not_convert,
  58. )
  59. @property
  60. def is_trainable(self):
  61. return False
  62. def is_serializable(self):
  63. return True