quantizer_auto_round.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 import is_auto_round_available, logging
  19. from ..utils.quantization_config import QuantizationConfigMixin
  20. logger = logging.get_logger(__name__)
  21. class AutoRoundQuantizer(HfQuantizer):
  22. """
  23. Quantizer of the AutoRound method. (https://huggingface.co/papers/2309.05516)
  24. """
  25. # AutoRound requires data calibration - we support only inference
  26. requires_calibration = True
  27. def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
  28. super().__init__(quantization_config, **kwargs)
  29. def validate_environment(self, *args, **kwargs):
  30. self.device_map = kwargs.get("device_map")
  31. if not is_auto_round_available():
  32. raise ImportError(
  33. "Loading an AutoRound quantized model requires auto-round library (`pip install 'auto-round>=0.5'`)"
  34. )
  35. def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
  36. if model.__class__.main_input_name != "input_ids":
  37. logger.warning("AutoRound offers only limited support for models that are not strictly text-based.")
  38. from auto_round.inference.convert_model import convert_hf_model, infer_target_device
  39. if self.pre_quantized:
  40. target_device = infer_target_device(self.device_map)
  41. model, used_backends = convert_hf_model(model, target_device)
  42. self.used_backends = used_backends
  43. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  44. if self.pre_quantized:
  45. from auto_round.inference.convert_model import post_init
  46. post_init(model, self.used_backends)
  47. else:
  48. raise ValueError("AutoRound only sports pre-quantized models.")
  49. @property
  50. def is_trainable(self) -> bool:
  51. return False
  52. def is_serializable(self):
  53. ## for gptq/awq models, the quantization config will be changed
  54. return True