quantizer_hqq.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # Copyright 2024 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. from typing import TYPE_CHECKING, Any, Dict, List
  15. from ..integrations import prepare_for_hqq_linear
  16. from ..utils import is_accelerate_available, is_hqq_available, is_torch_available, logging
  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. if is_accelerate_available():
  22. from accelerate.hooks import remove_hook_from_module
  23. if is_torch_available():
  24. import torch
  25. logger = logging.get_logger(__name__)
  26. # Finds the parent of a node module named "name"
  27. def find_parent(model, name):
  28. module_tree = name.split(".")[:-1]
  29. parent = model
  30. for m in module_tree:
  31. parent = parent._modules[m]
  32. return parent
  33. class HqqHfQuantizer(HfQuantizer):
  34. """
  35. HQQ quantizer base HF class.
  36. nn.Linear modules are first tagged with quant_config in _process_model_before_weight_loading().
  37. The actual quantization and offloading to the GPU is done in check_quantized_param().
  38. """
  39. use_keep_in_fp32_modules = False
  40. requires_parameters_quantization = True
  41. requires_calibration = False
  42. required_packages = ["hqq"]
  43. def __init__(self, quantization_config, **kwargs):
  44. super().__init__(quantization_config, **kwargs)
  45. self.torch_dtype = None
  46. self.using_multi_gpu = False
  47. def validate_environment(self, *args, **kwargs):
  48. if not (is_hqq_available()):
  49. raise ImportError(
  50. "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
  51. )
  52. if kwargs.get("from_tf", False) or kwargs.get("from_flax", False):
  53. raise ValueError(
  54. "Converting weights from tf/flax weights is currently not supported, please make"
  55. " sure the weights are in PyTorch format."
  56. )
  57. if not torch.cuda.is_available():
  58. raise RuntimeError("No GPU found. A GPU is needed for quantization.")
  59. if self.torch_dtype is None:
  60. if "torch_dtype" in kwargs:
  61. self.torch_dtype = kwargs["torch_dtype"]
  62. else:
  63. self.torch_dtype = torch.float32
  64. logger.info("Setting torch_dtype to torch.float32 as the default value since it was not specified.")
  65. device_map = kwargs.get("device_map", None)
  66. if isinstance(device_map, dict):
  67. if "cpu" in device_map.values() or "disk" in device_map.values():
  68. raise ValueError(
  69. "You are attempting to use an HQQ model with a device_map that contains a CPU or disk device."
  70. " This is not supported. Please remove the CPU or disk device from the device_map."
  71. )
  72. else:
  73. self.using_multi_gpu = len(set(device_map.values())) > 1
  74. def update_missing_keys(
  75. self, model: "PreTrainedModel", missing_keys: List[str], prefix: str, **kwargs
  76. ) -> List[str]:
  77. if self.pre_quantized:
  78. return [key for key in missing_keys if ("weight" not in key)]
  79. else:
  80. return missing_keys
  81. # Adds missing keys for HQQLinear modules that are loaded but the model with initialized with torch.nn.Linear
  82. def update_expected_keys(
  83. self, model: "PreTrainedModel", expected_keys: List[str], loaded_keys: List[str]
  84. ) -> List[str]:
  85. if not self.pre_quantized:
  86. return expected_keys
  87. # Collects all quantizable (linear) layers
  88. def _find_hqq_quantizable_layers(model, layers):
  89. for name, module in model.named_children():
  90. if isinstance(module, (torch.nn.Linear)):
  91. layers.add(module.name)
  92. _find_hqq_quantizable_layers(module, layers)
  93. new_keys = set(expected_keys)
  94. if is_hqq_available():
  95. from hqq.core.quantize import HQQLinear
  96. # Name modules
  97. for name, module in model.named_modules():
  98. module.name = name
  99. # valid modules are Linear layers that have HQQLinear state_dict. We ignore skip_modules and any layers with Linear state_dict() params
  100. _valid_modules = set()
  101. _find_hqq_quantizable_layers(model, _valid_modules)
  102. _valid_modules -= set(model.config.quantization_config["skip_modules"])
  103. # Append new expected layers based on _ref_keys
  104. _ref_keys = HQQLinear(
  105. linear_layer=None, quant_config=None, compute_dtype=torch.float16, device="cpu"
  106. ).state_dict_keys() - {"bias"}
  107. # Clean-up
  108. _rm_keys = set()
  109. for key in new_keys:
  110. if any(_module in key for _module in _valid_modules):
  111. _rm_keys.add(key)
  112. new_keys -= _rm_keys
  113. # At this point, new_keys contains all the keys of the layers that are NOT HQQLinear or torch.nn.Linear
  114. # Re-populate Linear/HQQLinear
  115. for _module in _valid_modules:
  116. if _module + ".weight" in loaded_keys:
  117. new_keys.add(_module + ".weight")
  118. else:
  119. new_keys.update({_module + "." + _ref_key for _ref_key in _ref_keys})
  120. if _module + ".bias" in loaded_keys:
  121. new_keys.add(_module + ".bias")
  122. return list(new_keys)
  123. def check_quantized_param(
  124. self,
  125. model: "PreTrainedModel",
  126. param_value: "torch.Tensor",
  127. param_name: str,
  128. state_dict: Dict[str, Any],
  129. **kwargs,
  130. ) -> bool:
  131. if is_hqq_available():
  132. from hqq.core.quantize import HQQLinear
  133. module, tensor_name = get_module_from_name(model, param_name)
  134. if self.pre_quantized:
  135. return (
  136. (isinstance(module, torch.nn.Linear) or isinstance(module, HQQLinear))
  137. and tensor_name != "weight"
  138. and tensor_name != "bias"
  139. )
  140. else:
  141. return isinstance(module, torch.nn.Linear) and tensor_name == "weight"
  142. def create_quantized_param(
  143. self,
  144. model: "PreTrainedModel",
  145. param_value: "torch.Tensor",
  146. param_name: str,
  147. target_device: "torch.device",
  148. state_dict: Dict[str, Any],
  149. unexpected_keys: List[str],
  150. ):
  151. """
  152. Each nn.Linear layer is processsed here.
  153. We first check if the corresponding module state_dict contains already HQQ quantized parameters.
  154. If not, we create a temp linear layer with the module state_dict params and use it for quantization
  155. """
  156. if is_hqq_available():
  157. from hqq.core.quantize import HQQLinear
  158. module, tensor_name = get_module_from_name(model, param_name)
  159. layer_name = ".".join(param_name.split(".")[:-1])
  160. parent_module = find_parent(model, layer_name)
  161. node = layer_name.split(".")[-1]
  162. # set module state_dict
  163. module_state_dict = {}
  164. for k, v in state_dict.items():
  165. if layer_name + "." in k:
  166. module_state_dict[k.split(".")[-1]] = v
  167. if unexpected_keys is not None and k in unexpected_keys:
  168. unexpected_keys.remove(k)
  169. if self.pre_quantized:
  170. if isinstance(module, HQQLinear):
  171. return
  172. else:
  173. hqq_layer = HQQLinear(
  174. linear_layer=None,
  175. quant_config=None,
  176. compute_dtype=self.torch_dtype,
  177. device=target_device,
  178. )
  179. hqq_layer.load_state_dict(module_state_dict)
  180. if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor):
  181. hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias)
  182. if self.using_multi_gpu:
  183. hqq_layer = self._patch_layer_for_multigpu(hqq_layer)
  184. setattr(parent_module, node, hqq_layer)
  185. # cleanup
  186. del module.__dict__, module
  187. torch.cuda.empty_cache()
  188. return
  189. # Step 1: populate module with weight/bias from module state dict
  190. for key in module_state_dict:
  191. setattr(module, key, torch.nn.Parameter(module_state_dict[key]))
  192. # Step 2: Replace module with either HQQLinear or move it to device. We do this via setattr on the parent as doing on it on the module
  193. # directly doesn't work.
  194. if hasattr(module, "quant_config"):
  195. hqq_layer = HQQLinear(
  196. module,
  197. module.quant_config,
  198. compute_dtype=self.torch_dtype,
  199. device=target_device,
  200. del_orig=True,
  201. )
  202. if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor):
  203. hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias)
  204. if self.using_multi_gpu:
  205. hqq_layer = self._patch_layer_for_multigpu(hqq_layer)
  206. setattr(parent_module, node, hqq_layer)
  207. else:
  208. module = module.to(dtype=self.torch_dtype, device=target_device)
  209. setattr(parent_module, node, module)
  210. torch.cuda.empty_cache()
  211. # Remove accelerate hook and uses a simpler forward pass. Otherwise, this breaks with multi-gpu
  212. def _patch_layer_for_multigpu(self, hqq_layer):
  213. hqq_layer = remove_hook_from_module(hqq_layer)
  214. def forward_with_device(self, x):
  215. out = torch.matmul(x.to(self.device), self.dequantize().t())
  216. if self.bias is not None:
  217. out += self.bias
  218. return out
  219. hqq_layer.forward = lambda x: forward_with_device(hqq_layer, x)
  220. return hqq_layer
  221. def _process_model_before_weight_loading(
  222. self,
  223. model: "PreTrainedModel",
  224. device_map,
  225. keep_in_fp32_modules: List[str] = None,
  226. **kwargs,
  227. ):
  228. keep_in_fp32_modules = keep_in_fp32_modules if keep_in_fp32_modules is not None else []
  229. # Add the corresponding quant_config to each valid module. This allows us to do the actual nn.Linear -> HQQLinear conversion in create_quantized_param().
  230. # prepare_for_hqq_linear() also sets the right quantization config inside the model (model.config.quantization_config) and the layers (hqq_layer.quant_config)
  231. model = prepare_for_hqq_linear(model, quantization_config=self.quantization_config)
  232. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  233. model.is_hqq_quantized = True
  234. model.is_hqq_serializable = self.is_serializable()
  235. return model
  236. def is_serializable(self, safe_serialization=None):
  237. return True
  238. @property
  239. def is_trainable(self) -> bool:
  240. return True