fp_quant.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright 2025 The HuggingFace 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. "FP-Quant integration file"
  15. import torch
  16. from ..utils import (
  17. is_fp_quant_available,
  18. )
  19. if is_fp_quant_available():
  20. from fp_quant import FPQuantConfig as FPQuantLinearConfig
  21. from fp_quant import FPQuantDtype
  22. from transformers.utils.quantization_config import FPQuantConfig
  23. from ..core_model_loading import ConversionOps
  24. from ..quantizers.quantizers_utils import get_module_from_name
  25. class FpQuantQuantize(ConversionOps):
  26. def __init__(self, hf_quantizer):
  27. self.hf_quantizer = hf_quantizer
  28. def convert(
  29. self,
  30. input_dict: torch.Tensor,
  31. model: torch.nn.Module | None = None,
  32. missing_keys: list[str] | None = None,
  33. **kwargs,
  34. ) -> dict[str, torch.Tensor]:
  35. target_key, value = tuple(input_dict.items())[0]
  36. value = value[0]
  37. # Loading master weights or an unquantized checkpoint
  38. weight = torch.nn.Parameter(value)
  39. module, _ = get_module_from_name(model, target_key)
  40. module.weight = weight
  41. # Let pre-forward handle the quantization and set None where necessary
  42. # This operation will quantize the weights internally
  43. torch_accelerator_module = getattr(torch, value.device.type, torch.cuda)
  44. with torch_accelerator_module.device(value.device):
  45. module.pre_forward()
  46. prefix_target_key = target_key.rsplit(".", 1)[0]
  47. # keys are set inside the module.pre_forward() method, we don't need remove them from the missing keys list
  48. missing_keys.discard(target_key)
  49. missing_keys.discard(f"{prefix_target_key}.backward_hadamard_matrix")
  50. missing_keys.discard(f"{prefix_target_key}.forward_hadamard_matrix")
  51. missing_keys.discard(f"{prefix_target_key}.act_global_scale")
  52. missing_keys.discard(f"{prefix_target_key}.weight_global_scale")
  53. missing_keys.discard(f"{prefix_target_key}.qweight")
  54. missing_keys.discard(f"{prefix_target_key}.scales")
  55. missing_keys.discard(f"{prefix_target_key}.dqweight")
  56. return {}
  57. class FpQuantDeserialize(ConversionOps):
  58. def __init__(self, hf_quantizer):
  59. self.hf_quantizer = hf_quantizer
  60. def convert(
  61. self,
  62. input_dict: torch.Tensor,
  63. model: torch.nn.Module | None = None,
  64. full_layer_name: str | None = None,
  65. missing_keys: list[str] | None = None,
  66. **kwargs,
  67. ) -> dict[str, torch.Tensor]:
  68. target_key, value = tuple(input_dict.items())[0]
  69. value = value[0] if isinstance(value, list) else value
  70. module, _ = get_module_from_name(model, target_key)
  71. # The module holds either:
  72. # * `weight` when `store_master_weights=True`
  73. # * `qweight` and `scales` when `store_master_weights=False` and `pseudoquantization=False`
  74. # * `dqweight` when `store_master_weights=False` and `pseudoquantization=True`
  75. if target_key == ".qweight":
  76. # Loading a real quantized checkpoint without master weights
  77. qweight = torch.nn.Parameter(
  78. value,
  79. requires_grad=False,
  80. )
  81. return {
  82. ".qweight": qweight,
  83. # the way the FPQuantLinear module is designed, these parameters are expected in the model
  84. # even though they are not used so we need to set them to zeros
  85. ".weight": torch.nn.Parameter(torch.zeros(0)),
  86. ".dqweight": torch.nn.Parameter(torch.zeros(0)),
  87. }
  88. if target_key == ".dqweight":
  89. # Loading a pseudo-quantized checkpoint without master weights
  90. dqweight = torch.nn.Parameter(value)
  91. return {
  92. ".dqweight": dqweight,
  93. # the way the FPQuantLinear module ips designed, these parameters are expected in the model
  94. # even though they are not used so we need to set them to zeros
  95. ".weight": torch.nn.Parameter(torch.zeros(0)),
  96. ".qweight": torch.nn.Parameter(torch.zeros(0)),
  97. ".scales": torch.nn.Parameter(torch.zeros(0)),
  98. }
  99. def adapt_fp_quant_config(config: FPQuantConfig):
  100. if config.forward_dtype == "mxfp4":
  101. forward_dtype = FPQuantDtype.MXFP4
  102. elif config.forward_dtype == "nvfp4":
  103. forward_dtype = FPQuantDtype.NVFP4
  104. else:
  105. raise ValueError(f"Unsupported forward dtype: {config.forward_dtype}")
  106. if config.backward_dtype == "bf16":
  107. backward_dtype = FPQuantDtype.BF16
  108. elif config.backward_dtype == "mxfp8":
  109. backward_dtype = FPQuantDtype.MXFP8
  110. elif config.backward_dtype == "mxfp4":
  111. backward_dtype = FPQuantDtype.MXFP4
  112. else:
  113. raise ValueError(f"Unsupported backward dtype: {config.backward_dtype}")
  114. return FPQuantLinearConfig(
  115. forward_dtype=forward_dtype,
  116. forward_method=config.forward_method,
  117. backward_dtype=backward_dtype,
  118. store_master_weights=config.store_master_weights,
  119. hadamard_group_size=config.hadamard_group_size,
  120. pseudoquantization=config.pseudoquantization,
  121. transform_init=config.transform_init,
  122. modules_to_not_convert=config.modules_to_not_convert,
  123. )