quantizer_fbgemm_fp8.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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, Optional
  15. from .base import HfQuantizer
  16. if TYPE_CHECKING:
  17. from ..modeling_utils import PreTrainedModel
  18. from ..utils import is_accelerate_available, is_fbgemm_gpu_available, is_torch_available, logging
  19. from .quantizers_utils import get_module_from_name
  20. if is_torch_available():
  21. import torch
  22. logger = logging.get_logger(__name__)
  23. class FbgemmFp8HfQuantizer(HfQuantizer):
  24. """
  25. FP8 quantization using fbgemm kernels
  26. """
  27. requires_parameters_quantization = True
  28. requires_calibration = False
  29. required_packages = ["fbgemm-gpu", "accelerate"]
  30. def __init__(self, quantization_config, **kwargs):
  31. super().__init__(quantization_config, **kwargs)
  32. self.quantization_config = quantization_config
  33. def validate_environment(self, *args, **kwargs):
  34. if not is_torch_available():
  35. raise ImportError(
  36. "Using fbgemm fp8 quantization requires torch >= 2.1.0"
  37. "Please install the latest version of torch ( pip install --upgrade torch )"
  38. )
  39. if not is_fbgemm_gpu_available():
  40. raise ImportError(
  41. "Using fbgemm fp8 quantization requires fbgemm-gpu library"
  42. "Please install the latest version of fbgemm-gpu library by following : https://pytorch.org/FBGEMM/fbgemm_gpu-development/InstallationInstructions.html#fbgemm-gpu-install-libraries"
  43. )
  44. if not is_accelerate_available("0.32.2"):
  45. raise ImportError(
  46. "Loading an FP8 quantized model requires accelerate > 0.32.1 (`pip install --upgrade accelerate`)"
  47. )
  48. if not torch.cuda.is_available():
  49. raise RuntimeError("Using FP8 quantized models with fbgemm kernels requires a GPU")
  50. compute_capability = torch.cuda.get_device_capability()
  51. major, minor = compute_capability
  52. if major < 9:
  53. raise ValueError(
  54. "FP8 quantized models is only supported on GPUs with compute capability >= 9.0 (e.g H100)"
  55. )
  56. device_map = kwargs.get("device_map")
  57. if device_map is None:
  58. logger.warning_once(
  59. "You have loaded an FP8 model on CPU and have a CUDA device available, make sure to set "
  60. "your model on a GPU device in order to run your model. To remove this warning, pass device_map = 'cuda'. "
  61. )
  62. elif device_map is not None:
  63. if (
  64. not self.pre_quantized
  65. and isinstance(device_map, dict)
  66. and ("cpu" in device_map.values() or "disk" in device_map.values())
  67. ):
  68. raise ValueError(
  69. "You are attempting to load an FP8 model with a device_map that contains a CPU or disk device."
  70. "This is not supported when the model is quantized on the fly. "
  71. "Please use a quantized checkpoint or remove the CPU or disk device from the device_map."
  72. )
  73. def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
  74. if dtype is None:
  75. dtype = torch.bfloat16
  76. logger.info(
  77. "Overriding dtype=%s with `dtype=torch.bloat16` due to "
  78. "requirements of `fbgemm-gpu` to enable model loading in fp8. "
  79. "Pass your own dtype to specify the dtype of the remaining non-linear layers or pass"
  80. " dtype=torch.bfloat16 to remove this warning.",
  81. dtype,
  82. )
  83. elif dtype == torch.float16:
  84. raise ValueError(
  85. "You cannot use FP8 with dtype=torch.float16.We recommend you passing dtype=torch.bfloat16"
  86. )
  87. return dtype
  88. def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
  89. from ..integrations import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts
  90. module, tensor_name = get_module_from_name(model, param_name)
  91. if isinstance(module, FbgemmFp8Linear):
  92. if self.pre_quantized or tensor_name == "bias":
  93. return False
  94. else:
  95. return True
  96. if isinstance(module, FbgemmFp8Llama4TextExperts):
  97. if self.pre_quantized or tensor_name == "bias":
  98. return False
  99. else:
  100. return True
  101. return False
  102. def create_quantized_param(
  103. self,
  104. model: "PreTrainedModel",
  105. param_value: "torch.Tensor",
  106. param_name: str,
  107. target_device: "torch.device",
  108. **kwargs,
  109. ):
  110. from ..integrations import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts
  111. module, tensor_name = get_module_from_name(model, param_name)
  112. # Sanity checks
  113. if isinstance(module, FbgemmFp8Linear):
  114. if self.pre_quantized or tensor_name == "bias":
  115. if tensor_name == "weight" and param_value.dtype != torch.float8_e4m3fn:
  116. raise ValueError("Expect quantized weights but got an unquantized weight")
  117. else:
  118. if tensor_name == "weight_scale":
  119. raise ValueError("Expect unquantized weights but got a quantized weight_scale")
  120. if isinstance(module, FbgemmFp8Llama4TextExperts):
  121. if not (self.pre_quantized or tensor_name == "bias"):
  122. if tensor_name == "gate_up_proj_scale" or tensor_name == "down_proj_scale":
  123. raise ValueError("Expect unquantized weights but got a quantized weight_scale")
  124. if isinstance(module, FbgemmFp8Llama4TextExperts):
  125. if tensor_name == "gate_up_proj":
  126. # Process each expert separately
  127. # Transpose the second and third dimension
  128. transposed_param = param_value.transpose(1, 2)
  129. # Reshape to 2D for quantization
  130. original_shape = transposed_param.shape
  131. flattened_param = transposed_param.reshape(-1, original_shape[-1])
  132. # Quantize using per row instead of per column
  133. new_value_flat, weight_scale_flat = torch.ops.fbgemm.quantize_fp8_per_row(flattened_param)
  134. # Reshape back to original dimensions
  135. new_value = new_value_flat.reshape(original_shape)
  136. new_value = new_value.transpose(1, 2)
  137. weight_scale = weight_scale_flat.reshape(original_shape[0], 1, original_shape[1])
  138. elif tensor_name == "down_proj":
  139. # Process each expert separately
  140. # Transpose the weights for proper quantization
  141. transposed_param = param_value.transpose(1, 2)
  142. # Reshape to 2D for quantization
  143. original_shape = transposed_param.shape
  144. flattened_param = transposed_param.reshape(-1, original_shape[-1])
  145. # Quantize using per column
  146. new_value_flat, weight_scale_flat = torch.ops.fbgemm.quantize_fp8_per_row(flattened_param)
  147. # Reshape back to original dimensions
  148. new_value = new_value_flat.reshape(original_shape)
  149. new_value = new_value.transpose(1, 2)
  150. weight_scale = weight_scale_flat.reshape(original_shape[0], original_shape[1], 1)
  151. module._parameters[f"{tensor_name}_scale"] = torch.nn.Parameter(weight_scale.to(target_device))
  152. else:
  153. new_value, weight_scale = torch.ops.fbgemm.quantize_fp8_per_row(param_value)
  154. module._parameters[f"{tensor_name}_scale"] = torch.nn.Parameter(
  155. weight_scale.view(weight_scale.shape[0], 1).to(target_device)
  156. )
  157. module._parameters[tensor_name] = torch.nn.Parameter(new_value.to(target_device))
  158. del param_name
  159. def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
  160. return model
  161. def _process_model_before_weight_loading(
  162. self,
  163. model: "PreTrainedModel",
  164. keep_in_fp32_modules: Optional[list[str]] = None,
  165. **kwargs,
  166. ):
  167. from ..integrations import replace_with_fbgemm_fp8_linear
  168. tp_plan = model._tp_plan
  169. self.modules_to_not_convert = self.get_modules_to_not_convert(
  170. model, self.quantization_config.modules_to_not_convert, keep_in_fp32_modules
  171. )
  172. config = model.config
  173. model = replace_with_fbgemm_fp8_linear(
  174. model,
  175. modules_to_not_convert=self.modules_to_not_convert,
  176. quantization_config=self.quantization_config,
  177. pre_quantized=self.pre_quantized,
  178. config=config,
  179. tp_plan=tp_plan,
  180. )
  181. model.config.quantization_config = self.quantization_config
  182. def update_missing_keys(self, model, missing_keys: list[str], prefix: str) -> list[str]:
  183. from ..integrations import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts
  184. not_missing_keys = []
  185. for name, module in model.named_modules():
  186. if isinstance(module, (FbgemmFp8Linear, FbgemmFp8Llama4TextExperts)):
  187. for missing in missing_keys:
  188. if (
  189. (name in missing or name in f"{prefix}.{missing}")
  190. and not missing.endswith(".weight")
  191. and not missing.endswith(".bias")
  192. ):
  193. not_missing_keys.append(missing)
  194. return [k for k in missing_keys if k not in not_missing_keys]
  195. def update_tp_plan(self, config):
  196. if "Llama4" in config.__class__.__name__:
  197. text_plan = {
  198. # We are using a different tp plan with local_colwise and local_rowwise for the attention because fbgemm operations cannot be parallelized
  199. # With local_colwise and local_rowwise, all the operations are done locally, and we add a gather operation to gather the results instead of
  200. # using dtensors
  201. "layers.*.self_attn.q_proj.weight": "local_colwise",
  202. "layers.*.self_attn.q_proj.weight_scale": "local_colwise",
  203. "layers.*.self_attn.k_proj.weight": "local_colwise",
  204. "layers.*.self_attn.k_proj.weight_scale": "local_colwise",
  205. "layers.*.self_attn.v_proj.weight": "local_colwise",
  206. "layers.*.self_attn.v_proj.weight_scale": "local_colwise",
  207. "layers.*.self_attn.o_proj.weight": "local_rowwise",
  208. "layers.*.self_attn": "gather",
  209. # We keep the same sequence_parallel plan for layernorms
  210. "layers.*.input_layernorm.weight": "sequence_parallel",
  211. "layers.*.post_attention_layernorm.weight": "sequence_parallel",
  212. "norm.weight": "sequence_parallel",
  213. # We keep the same local_colwise and local_rowwise plan for the feed forward shared expert
  214. # We also add scales for the shared expert, for local_colwise the scale is also local_colwise
  215. # For local_rowwise the scale is replicated, so we don't need to add it
  216. "layers.*.feed_forward.shared_expert.gate_proj.weight": "local_colwise",
  217. "layers.*.feed_forward.shared_expert.gate_proj.weight_scale": "local_colwise",
  218. "layers.*.feed_forward.shared_expert.up_proj.weight": "local_colwise",
  219. "layers.*.feed_forward.shared_expert.up_proj.weight_scale": "local_colwise",
  220. "layers.*.feed_forward.shared_expert.down_proj.weight": "local_rowwise",
  221. "layers.*.feed_forward.experts": "local",
  222. "layers.*.feed_forward": "gather",
  223. "layers.*.feed_forward.experts.*.gate_proj.weight": "local_colwise",
  224. "layers.*.feed_forward.experts.*.gate_proj.weight_scale": "local_colwise",
  225. "layers.*.feed_forward.experts.*.up_proj.weight": "local_colwise",
  226. "layers.*.feed_forward.experts.*.up_proj.weight_scale": "local_colwise",
  227. "layers.*.feed_forward.experts.*.down_proj.weight": "local_rowwise",
  228. # For Fused implementation we use local_packed_rowwise for the gate_up_proj, and the same for the packed scales
  229. # We use local_colwise for the down_proj, and the scales are replicated so we don't add them
  230. "layers.*.feed_forward.experts.gate_up_proj": "local_packed_rowwise",
  231. "layers.*.feed_forward.experts.gate_up_proj_scale": "local_packed_rowwise",
  232. "layers.*.feed_forward.experts.down_proj": "local_colwise",
  233. }
  234. if config.get_text_config() is not None:
  235. config.get_text_config().base_model_tp_plan = text_plan
  236. else:
  237. config.base_model_tp_plan = text_plan
  238. return config
  239. return config
  240. def is_serializable(self, safe_serialization=None):
  241. return True
  242. @property
  243. def is_trainable(self) -> bool:
  244. return False