quantizer_eetq.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 EetqConfig
  19. from ..utils import is_accelerate_available, is_kernels_available, is_torch_available, logging
  20. from .quantizers_utils import get_module_from_name
  21. if is_torch_available():
  22. import torch
  23. logger = logging.get_logger(__name__)
  24. class EetqHfQuantizer(HfQuantizer):
  25. """
  26. 8-bit quantization from EETQ quantization method
  27. """
  28. requires_calibration = False
  29. quantization_config: "EetqConfig"
  30. def __init__(self, quantization_config, **kwargs):
  31. super().__init__(quantization_config, **kwargs)
  32. def validate_environment(self, *args, **kwargs):
  33. if not is_kernels_available():
  34. raise ImportError("Loading an EETQ quantized model requires kernels (`pip install kernels`)")
  35. if not is_accelerate_available():
  36. raise ImportError("Loading an EETQ quantized model requires accelerate (`pip install accelerate`)")
  37. if not torch.cuda.is_available():
  38. raise RuntimeError("No GPU found. A GPU is needed for quantization.")
  39. device_map = kwargs.get("device_map")
  40. if device_map is None:
  41. logger.warning_once(
  42. "You have loaded an EETQ model on CPU and have a CUDA device available, make sure to set "
  43. "your model on a GPU device in order to run your model."
  44. )
  45. elif isinstance(device_map, dict):
  46. if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values():
  47. raise ValueError(
  48. "You are attempting to load an EETQ model with a device_map that contains a CPU or disk device."
  49. " This is not supported. Please remove the CPU or disk device from the device_map."
  50. )
  51. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  52. if dtype != torch.float16:
  53. logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with EETQ.")
  54. return dtype
  55. def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
  56. from ..integrations.eetq import EetqLinear
  57. module, tensor_name = get_module_from_name(model, param_name)
  58. if isinstance(module, EetqLinear):
  59. if self.pre_quantized or tensor_name == "bias":
  60. return False
  61. else:
  62. return True
  63. return False
  64. def _process_model_before_weight_loading(
  65. self,
  66. model: "PreTrainedModel",
  67. **kwargs,
  68. ):
  69. from ..integrations import replace_with_eetq_linear
  70. self.modules_to_not_convert = self.get_modules_to_not_convert(
  71. model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
  72. )
  73. model = replace_with_eetq_linear(
  74. model, modules_to_not_convert=self.modules_to_not_convert, pre_quantized=self.pre_quantized
  75. )
  76. def is_serializable(self):
  77. return True
  78. @property
  79. def is_trainable(self) -> bool:
  80. return True
  81. def get_quantize_ops(self):
  82. from ..integrations.eetq import EetqQuantize
  83. return EetqQuantize(self)