quantizer_quanto.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. import importlib
  15. from typing import TYPE_CHECKING, Optional, Union
  16. from packaging import version
  17. from .base import HfQuantizer
  18. from .quantizers_utils import get_module_from_name
  19. if TYPE_CHECKING:
  20. from ..modeling_utils import PreTrainedModel
  21. from ..utils import (
  22. is_accelerate_available,
  23. is_optimum_quanto_available,
  24. is_torch_available,
  25. logging,
  26. )
  27. from ..utils.quantization_config import QuantoConfig
  28. if is_torch_available():
  29. import torch
  30. logger = logging.get_logger(__name__)
  31. class QuantoHfQuantizer(HfQuantizer):
  32. """
  33. Quantizer for the quanto library
  34. """
  35. required_packages = ["quanto", "accelerate"]
  36. requires_parameters_quantization = True
  37. requires_calibration = False
  38. def __init__(self, quantization_config: QuantoConfig, **kwargs):
  39. super().__init__(quantization_config, **kwargs)
  40. self.post_init()
  41. def post_init(self):
  42. r"""
  43. Safety checker
  44. """
  45. if self.quantization_config.activations is not None and not self.pre_quantized:
  46. raise ValueError(
  47. "We don't support quantizing the activations with transformers library."
  48. "Use quanto library for more complex use cases such as activations quantization, calibration and quantization aware training."
  49. )
  50. def validate_environment(self, *args, **kwargs):
  51. if not is_optimum_quanto_available():
  52. raise ImportError(
  53. "Loading an optimum-quanto quantized model requires optimum-quanto library (`pip install optimum-quanto`)"
  54. )
  55. if not is_accelerate_available():
  56. raise ImportError(
  57. "Loading an optimum-quanto quantized model requires accelerate library (`pip install accelerate`)"
  58. )
  59. def update_device_map(self, device_map):
  60. if device_map is None:
  61. device_map = {"": "cpu"}
  62. logger.info(
  63. "The device_map was not initialized. "
  64. "Setting device_map to {'':'cpu'}. "
  65. "If you want to use the model for inference, please set device_map ='auto'"
  66. )
  67. return device_map
  68. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  69. if dtype is None:
  70. logger.info("You did not specify `dtype` in `from_pretrained`. Setting it to `torch.float32`.")
  71. dtype = torch.float32
  72. return dtype
  73. def update_missing_keys(self, model, missing_keys: list[str], prefix: str) -> list[str]:
  74. if is_optimum_quanto_available():
  75. from optimum.quanto import QModuleMixin
  76. not_missing_keys = []
  77. for name, module in model.named_modules():
  78. if isinstance(module, QModuleMixin):
  79. for missing in missing_keys:
  80. if (
  81. (name in missing or name in f"{prefix}.{missing}")
  82. and not missing.endswith(".weight")
  83. and not missing.endswith(".bias")
  84. ):
  85. not_missing_keys.append(missing)
  86. return [k for k in missing_keys if k not in not_missing_keys]
  87. def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
  88. if is_optimum_quanto_available():
  89. from optimum.quanto import QModuleMixin
  90. module, tensor_name = get_module_from_name(model, param_name)
  91. # We only quantize the weights and the bias is not quantized.
  92. if isinstance(module, QModuleMixin) and "weight" in tensor_name:
  93. # if the weights are quantized, don't need to recreate it again with `create_quantized_param`
  94. return not module.frozen
  95. else:
  96. return False
  97. def adjust_max_memory(self, max_memory: dict[str, Union[int, str]]) -> dict[str, Union[int, str]]:
  98. max_memory = {key: val * 0.90 for key, val in max_memory.items()}
  99. return max_memory
  100. def create_quantized_param(
  101. self,
  102. model: "PreTrainedModel",
  103. param_value: "torch.Tensor",
  104. param_name: str,
  105. target_device: "torch.device",
  106. **kwargs,
  107. ):
  108. from ..modeling_utils import _load_parameter_into_model
  109. _load_parameter_into_model(model, param_name, param_value.to(target_device))
  110. module, _ = get_module_from_name(model, param_name)
  111. module.freeze()
  112. module.weight.requires_grad = False
  113. def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
  114. if version.parse(importlib.metadata.version("accelerate")) > version.parse("0.27.0"):
  115. from accelerate.utils import CustomDtype
  116. mapping = {
  117. "int8": torch.int8,
  118. "float8": CustomDtype.FP8,
  119. "int4": CustomDtype.INT4,
  120. "int2": CustomDtype.INT2,
  121. }
  122. target_dtype = mapping[self.quantization_config.weights]
  123. return target_dtype
  124. else:
  125. raise ValueError(
  126. "You are using `device_map='auto'` on an optimum-quanto quantized model. To automatically compute"
  127. " the appropriate device map, you should upgrade your `accelerate` library,"
  128. "`pip install --upgrade accelerate` or install it from source."
  129. )
  130. def _process_model_before_weight_loading(
  131. self, model: "PreTrainedModel", keep_in_fp32_modules: Optional[list[str]] = None, **kwargs
  132. ):
  133. from ..integrations import replace_with_quanto_layers
  134. self.modules_to_not_convert = self.get_modules_to_not_convert(
  135. model, self.quantization_config.modules_to_not_convert, keep_in_fp32_modules
  136. )
  137. model, _ = replace_with_quanto_layers(
  138. model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
  139. )
  140. model.config.quantization_config = self.quantization_config
  141. def _process_model_after_weight_loading(self, model, **kwargs):
  142. return model
  143. @property
  144. def is_trainable(self) -> bool:
  145. return True
  146. def is_serializable(self, safe_serialization=None):
  147. return False