quantizer_spqr.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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, Optional
  15. from .base import HfQuantizer
  16. if TYPE_CHECKING:
  17. from ..modeling_utils import PreTrainedModel
  18. from ..integrations import replace_with_spqr_linear
  19. from ..utils import is_accelerate_available, is_spqr_available, is_torch_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 SpQRHfQuantizer(HfQuantizer):
  25. """
  26. Quantizer of the SpQR method. Enables the loading of prequantized models.
  27. """
  28. requires_calibration = True
  29. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  30. super().__init__(quantization_config, **kwargs)
  31. self.quantization_config = quantization_config
  32. def validate_environment(self, *args, **kwargs):
  33. if not torch.cuda.is_available():
  34. raise RuntimeError("GPU is required to run SpQR quantized model.")
  35. if not is_accelerate_available():
  36. raise ImportError("Using `spqr` quantization requires Accelerate: `pip install accelerate`")
  37. if not is_spqr_available():
  38. raise ImportError("Using `spqr` quantization requires SpQR: `pip install spqr_quant[gpu]`")
  39. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  40. if dtype is None:
  41. dtype = torch.float16
  42. logger.info("Assuming SpQR inference on GPU and loading the model in `torch.float16`.")
  43. elif dtype != torch.float16:
  44. raise ValueError(
  45. "You cannot use any type other than torch.float16 for SpQR. Please either leave it None or set it to"
  46. "torch.float16 explicitly."
  47. )
  48. return dtype
  49. def _process_model_before_weight_loading(
  50. self,
  51. model: "PreTrainedModel",
  52. keep_in_fp32_modules: Optional[list[str]] = None,
  53. **kwargs,
  54. ):
  55. self.modules_to_not_convert = self.get_modules_to_not_convert(
  56. model, self.quantization_config.modules_to_not_convert, keep_in_fp32_modules
  57. )
  58. replace_with_spqr_linear(
  59. model,
  60. quantization_config=self.quantization_config,
  61. modules_to_not_convert=self.modules_to_not_convert,
  62. )
  63. model.config.quantization_config = self.quantization_config
  64. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  65. return model
  66. @property
  67. def is_trainable(self):
  68. return False
  69. def is_serializable(self, safe_serialization=None):
  70. return True