quantizer_quark.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Copyright 2025 Advanced Micro Devices, Inc. and 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 QuarkConfig
  19. from ..utils import is_quark_available, logging
  20. logger = logging.get_logger(__name__)
  21. CHECKPOINT_KEYS = {
  22. "weight_scale": "weight_quantizer.scale",
  23. "bias_scale": "bias_quantizer.scale",
  24. "input_scale": "input_quantizer.scale",
  25. "output_scale": "output_quantizer.scale",
  26. "weight_zero_point": "weight_quantizer.zero_point",
  27. "bias_zero_point": "bias_quantizer.zero_point",
  28. "input_zero_point": "input_quantizer.zero_point",
  29. "output_zero_point": "output_quantizer.zero_point",
  30. }
  31. class QuarkHfQuantizer(HfQuantizer):
  32. """
  33. Quark quantizer (https://quark.docs.amd.com/latest/).
  34. """
  35. requires_calibration = True # On-the-fly quantization with quark is not supported for now.
  36. quantization_config: "QuarkConfig"
  37. def __init__(self, quantization_config, **kwargs):
  38. super().__init__(quantization_config, **kwargs)
  39. self.json_export_config = quantization_config.json_export_config
  40. def validate_environment(self, *args, **kwargs):
  41. if not is_quark_available():
  42. raise ImportError(
  43. "Loading a Quark quantized model requires the `quark` library but it was not found in the environment. Please refer to https://quark.docs.amd.com/latest/install.html."
  44. )
  45. def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
  46. from quark.torch.export.api import _map_to_quark
  47. _map_to_quark(
  48. model,
  49. self.quantization_config.quant_config,
  50. pack_method=self.json_export_config.pack_method,
  51. custom_mode=self.quantization_config.custom_mode,
  52. )
  53. return model
  54. def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
  55. return True
  56. def is_serializable(self):
  57. return False
  58. @property
  59. def is_trainable(self):
  60. return False
  61. def get_weight_conversions(self):
  62. from ..core_model_loading import WeightConverter
  63. from ..integrations.quark import QuarkDeserialize
  64. # In Quark, quantization is managed through a QParamsLinear module, which holds
  65. # separate quantizers for the weights, inputs, and biases (e.g. weight_quantizer
  66. # input_quantizer, bias_quantizer, etc.).
  67. #
  68. # The checkpoint stores keys like `weight_scale`, `input_scale`, etc.
  69. # but the model's state_dict() exposes `weight_quantizer.scale`, `input_quantizer.scale`, etc.
  70. # We rename from checkpoint format to model format, and the QuarkDeserialize operation
  71. # handles assigning values into the corresponding quantizer attributes.
  72. converters = []
  73. for source_key, target_key in CHECKPOINT_KEYS.items():
  74. converters.append(
  75. WeightConverter(
  76. source_patterns=[source_key],
  77. target_patterns=target_key,
  78. operations=[QuarkDeserialize(self)],
  79. )
  80. )
  81. return converters