fp8.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import os
  2. from typing import Any, Dict, List, Optional
  3. import torch
  4. from loguru import logger
  5. from torch.nn import Module
  6. from torch.nn.parameter import Parameter
  7. from aphrodite import _custom_ops as ops
  8. from aphrodite.common.utils import print_warning_once
  9. from aphrodite.modeling.layers.fused_moe import FusedMoE, FusedMoEMethodBase
  10. from aphrodite.modeling.layers.linear import (LinearBase, LinearMethodBase,
  11. UnquantizedLinearMethod)
  12. from aphrodite.modeling.utils import set_weight_attrs
  13. from aphrodite.platforms import current_platform
  14. from aphrodite.quantization.base_config import (QuantizationConfig,
  15. QuantizeMethodBase)
  16. from aphrodite.quantization.kv_cache import BaseKVCacheMethod
  17. from aphrodite.quantization.utils.marlin_utils_fp8 import (
  18. apply_fp8_marlin_linear, prepare_fp8_layer_for_marlin)
  19. from aphrodite.quantization.utils.quant_utils import is_layer_skipped
  20. from aphrodite.quantization.utils.w8a8_utils import (
  21. all_close_1d, apply_fp8_linear, convert_to_channelwise,
  22. create_per_tensor_scale_param, cutlass_fp8_supported,
  23. per_tensor_dequantize, requantize_with_max_scale)
  24. ACTIVATION_SCHEMES = ["static", "dynamic"]
  25. APHRODITE_TEST_FORCE_FP8_MARLIN = os.environ.get(
  26. "APHRODITE_TEST_FORCE_FP8_MARLIN", "0").strip().lower() in ("1", "true")
  27. class Fp8Config(QuantizationConfig):
  28. """Config class for FP8."""
  29. def __init__(
  30. self,
  31. is_checkpoint_fp8_serialized: bool = False,
  32. activation_scheme: str = "dynamic",
  33. ignored_layers: Optional[List[str]] = None,
  34. ) -> None:
  35. self.is_checkpoint_fp8_serialized = is_checkpoint_fp8_serialized
  36. if is_checkpoint_fp8_serialized:
  37. logger.warning("Detected fp8 checkpoint. Please note that the "
  38. "format is experimental and subject to change.")
  39. if activation_scheme not in ACTIVATION_SCHEMES:
  40. raise ValueError(
  41. f"Unsupported activation scheme {activation_scheme}")
  42. self.activation_scheme = activation_scheme
  43. self.ignored_layers = ignored_layers or []
  44. @classmethod
  45. def get_name(cls) -> str:
  46. return "fp8"
  47. @classmethod
  48. def get_supported_act_dtypes(cls) -> List[torch.dtype]:
  49. return [torch.bfloat16, torch.half]
  50. @classmethod
  51. def get_min_capability(cls) -> int:
  52. return 80
  53. @classmethod
  54. def get_config_filenames(cls) -> List[str]:
  55. return []
  56. @classmethod
  57. def from_config(cls, config: Dict[str, Any]) -> "Fp8Config":
  58. quant_method = cls.get_from_keys(config, ["quant_method"])
  59. is_checkpoint_fp8_serialized = ("fp8" in quant_method)
  60. activation_scheme = cls.get_from_keys(config, ["activation_scheme"])
  61. ignored_layers = cls.get_from_keys_or(config, ["ignored_layers"], None)
  62. return cls(is_checkpoint_fp8_serialized=is_checkpoint_fp8_serialized,
  63. activation_scheme=activation_scheme,
  64. ignored_layers=ignored_layers)
  65. def get_quant_method(self, layer: torch.nn.Module,
  66. prefix: str) -> Optional["QuantizeMethodBase"]:
  67. from aphrodite.attention.layer import (
  68. Attention) # Avoid circular import
  69. if isinstance(layer, LinearBase):
  70. if is_layer_skipped(prefix, self.ignored_layers):
  71. return UnquantizedLinearMethod()
  72. return Fp8LinearMethod(self)
  73. elif isinstance(layer, FusedMoE):
  74. return Fp8MoEMethod(self)
  75. elif isinstance(layer, Attention):
  76. return Fp8KVCacheMethod(self)
  77. return None
  78. def get_scaled_act_names(self) -> List[str]:
  79. return []
  80. class Fp8LinearMethod(LinearMethodBase):
  81. """Linear method for FP8.
  82. Supports loading FP8 checkpoints with static weight scale and
  83. dynamic/static activation scale.
  84. Also supports loading quantized FP16/BF16 model checkpoints with dynamic
  85. activation scaling. The weight scaling factor will be initialized after
  86. the model weights are loaded.
  87. Limitations:
  88. 1. Only support per-tensor quantization due to torch._scaled_mm support.
  89. 2. Only support float8_e4m3fn data type due to the limitation of
  90. torch._scaled_mm (https://github.com/pytorch/pytorch/blob/2e48b39603411a41c5025efbe52f89560b827825/aten/src/ATen/native/cuda/Blas.cpp#L854-L856)
  91. Args:
  92. quant_config: The quantization config.
  93. """
  94. def __init__(self, quant_config: Fp8Config):
  95. self.quant_config = quant_config
  96. self.cutlass_fp8_supported = cutlass_fp8_supported()
  97. # For GPUs that lack FP8 hardware support, we can leverage the Marlin
  98. # kernel for fast weight-only FP8 quantization
  99. capability = current_platform.get_device_capability()
  100. capability = capability[0] * 10 + capability[1]
  101. self.use_marlin = capability < 89 or APHRODITE_TEST_FORCE_FP8_MARLIN
  102. def create_weights(
  103. self,
  104. layer: torch.nn.Module,
  105. input_size_per_partition: int,
  106. output_partition_sizes: List[int],
  107. input_size: int,
  108. output_size: int,
  109. params_dtype: torch.dtype,
  110. **extra_weight_attrs,
  111. ):
  112. del input_size, output_size
  113. output_size_per_partition = sum(output_partition_sizes)
  114. layer.logical_widths = output_partition_sizes
  115. layer.input_size_per_partition = input_size_per_partition
  116. layer.output_size_per_partition = output_size_per_partition
  117. layer.orig_dtype = params_dtype
  118. # WEIGHT
  119. weight_dtype = (torch.float8_e4m3fn
  120. if self.quant_config.is_checkpoint_fp8_serialized else
  121. params_dtype)
  122. weight = Parameter(torch.empty(output_size_per_partition,
  123. input_size_per_partition,
  124. dtype=weight_dtype),
  125. requires_grad=False)
  126. layer.register_parameter("weight", weight)
  127. set_weight_attrs(weight, {
  128. **extra_weight_attrs,
  129. "input_dim": 1,
  130. "output_dim": 0,
  131. })
  132. # If checkpoint is serialized fp8, load them.
  133. # Otherwise, wait until process_weights_after_loading.
  134. if self.quant_config.is_checkpoint_fp8_serialized:
  135. # WEIGHT SCALE
  136. scale = create_per_tensor_scale_param(output_partition_sizes,
  137. **extra_weight_attrs)
  138. layer.register_parameter("weight_scale", scale)
  139. # INPUT ACTIVATION SCALE
  140. if self.quant_config.activation_scheme == "static":
  141. scale = create_per_tensor_scale_param(output_partition_sizes,
  142. **extra_weight_attrs)
  143. layer.register_parameter("input_scale", scale)
  144. def process_weights_after_loading(self, layer: Module) -> None:
  145. # If checkpoint not serialized fp8, quantize the weights.
  146. if not self.quant_config.is_checkpoint_fp8_serialized:
  147. qweight, weight_scale = ops.scaled_fp8_quant(layer.weight,
  148. scale=None)
  149. # If using marlin (w8a16), kernel uses channelwise weights,
  150. # so extend the weight scales to be channelwise.
  151. if self.use_marlin:
  152. assert weight_scale.numel() == 1
  153. weight_scale = convert_to_channelwise(
  154. weight_scale.expand(len(layer.logical_widths)),
  155. layer.logical_widths)
  156. # Update the layer with the new values.
  157. layer.weight = Parameter(qweight.t(), requires_grad=False)
  158. layer.weight_scale = Parameter(weight_scale, requires_grad=False)
  159. layer.input_scale = None
  160. # If checkpoint is fp8, handle that there are N scales for N
  161. # shards in a fused module
  162. else:
  163. # If using marlin (w8a16), kernel uses channelwise weights,
  164. # so extend the weight scales to be channelwise.
  165. if self.use_marlin:
  166. weight = layer.weight
  167. weight_scale = convert_to_channelwise(layer.weight_scale,
  168. layer.logical_widths)
  169. # If using w8a8, torch._scaled_mm needs per tensor, so
  170. # requantize the logical shards as a single weight.
  171. else:
  172. # Dequant -> Quant with max scale so we can run per tensor.
  173. weight_scale, weight = requantize_with_max_scale(
  174. weight=layer.weight,
  175. weight_scale=layer.weight_scale,
  176. logical_widths=layer.logical_widths,
  177. )
  178. # Update layer with new values.
  179. layer.weight = Parameter(weight.t(), requires_grad=False)
  180. layer.weight_scale = Parameter(weight_scale, requires_grad=False)
  181. if self.quant_config.activation_scheme == "static":
  182. layer.input_scale = Parameter(layer.input_scale.max(),
  183. requires_grad=False)
  184. else:
  185. layer.input_scale = None
  186. if self.use_marlin:
  187. prepare_fp8_layer_for_marlin(layer)
  188. # Activations not quantized for marlin.
  189. del layer.input_scale
  190. def apply(self,
  191. layer: torch.nn.Module,
  192. x: torch.Tensor,
  193. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  194. if self.use_marlin:
  195. return apply_fp8_marlin_linear(
  196. input=x,
  197. weight=layer.weight,
  198. weight_scale=layer.weight_scale,
  199. workspace=layer.workspace,
  200. size_n=layer.output_size_per_partition,
  201. size_k=layer.input_size_per_partition,
  202. bias=bias)
  203. return apply_fp8_linear(
  204. input=x,
  205. weight=layer.weight,
  206. weight_scale=layer.weight_scale,
  207. input_scale=layer.input_scale,
  208. bias=bias,
  209. cutlass_fp8_supported=self.cutlass_fp8_supported,
  210. use_per_token_if_dynamic=False)
  211. class Fp8MoEMethod(FusedMoEMethodBase):
  212. """MoE method for FP8.
  213. Supports loading FP8 checkpoints with static weight scale and
  214. dynamic/static activation scale.
  215. Also supports loading quantized FP16/BF16 model checkpoints with dynamic
  216. activation scaling. The weight scaling factor will be initialized after
  217. the model weights are loaded.
  218. Args:
  219. quant_config: The quantization config.
  220. """
  221. def __init__(self, quant_config: Fp8Config):
  222. self.quant_config = quant_config
  223. def create_weights(self, layer: Module, num_experts: int, hidden_size: int,
  224. intermediate_size: int, params_dtype: torch.dtype,
  225. **extra_weight_attrs):
  226. if self.quant_config.is_checkpoint_fp8_serialized:
  227. params_dtype = torch.float8_e4m3fn
  228. # WEIGHTS
  229. w13_weight = torch.nn.Parameter(torch.empty(num_experts,
  230. 2 * intermediate_size,
  231. hidden_size,
  232. dtype=params_dtype),
  233. requires_grad=False)
  234. layer.register_parameter("w13_weight", w13_weight)
  235. set_weight_attrs(w13_weight, extra_weight_attrs)
  236. w2_weight = torch.nn.Parameter(torch.empty(num_experts,
  237. hidden_size,
  238. intermediate_size,
  239. dtype=params_dtype),
  240. requires_grad=False)
  241. layer.register_parameter("w2_weight", w2_weight)
  242. set_weight_attrs(w2_weight, extra_weight_attrs)
  243. # WEIGHT_SCALES
  244. # Allocate 2 scales for w1 and w3 respectively.
  245. # They will be combined to a single scale after weight loading.
  246. w13_scale = torch.nn.Parameter(torch.ones(num_experts,
  247. 2,
  248. dtype=torch.float32),
  249. requires_grad=False)
  250. layer.register_parameter("w13_scale", w13_scale)
  251. w2_scale = torch.nn.Parameter(torch.ones(num_experts,
  252. dtype=torch.float32),
  253. requires_grad=False)
  254. layer.register_parameter("w2_scale", w2_scale)
  255. # If loading fp8 checkpoint, pass the weight loaders.
  256. # If loading an fp16 checkpoint, do not (we will quantize in
  257. # process_weights_after_loading()
  258. if self.quant_config.is_checkpoint_fp8_serialized:
  259. set_weight_attrs(w13_scale, extra_weight_attrs)
  260. set_weight_attrs(w2_scale, extra_weight_attrs)
  261. # INPUT_SCALES
  262. if self.quant_config.activation_scheme == "static":
  263. if not self.quant_config.is_checkpoint_fp8_serialized:
  264. raise ValueError(
  265. "Found static activation scheme for checkpoint that "
  266. "was not serialized fp8.")
  267. a13_scale = torch.nn.Parameter(torch.ones(num_experts,
  268. dtype=torch.float32),
  269. requires_grad=False)
  270. layer.register_parameter("a13_scale", a13_scale)
  271. set_weight_attrs(a13_scale, extra_weight_attrs)
  272. a2_scale = torch.nn.Parameter(torch.ones(num_experts,
  273. dtype=torch.float32),
  274. requires_grad=False)
  275. layer.register_parameter("a2_scale", a2_scale)
  276. set_weight_attrs(a2_scale, extra_weight_attrs)
  277. else:
  278. layer.a13_scale = None
  279. layer.a2_scale = None
  280. def process_weights_after_loading(self, layer: Module) -> None:
  281. # If checkpoint is fp16, quantize in place.
  282. if not self.quant_config.is_checkpoint_fp8_serialized:
  283. w13_weight = torch.empty_like(layer.w13_weight.data,
  284. dtype=torch.float8_e4m3fn)
  285. w2_weight = torch.empty_like(layer.w2_weight.data,
  286. dtype=torch.float8_e4m3fn)
  287. # Re-initialize w13_scale because we directly quantize
  288. # merged w13 weights and generate a single scaling factor.
  289. layer.w13_scale = torch.nn.Parameter(torch.ones(
  290. layer.num_experts,
  291. dtype=torch.float32,
  292. device=w13_weight.device),
  293. requires_grad=False)
  294. for expert in range(layer.num_experts):
  295. w13_weight[expert, :, :], layer.w13_scale[
  296. expert] = ops.scaled_fp8_quant(
  297. layer.w13_weight.data[expert, :, :])
  298. w2_weight[expert, :, :], layer.w2_scale[
  299. expert] = ops.scaled_fp8_quant(
  300. layer.w2_weight.data[expert, :, :])
  301. layer.w13_weight = torch.nn.Parameter(w13_weight,
  302. requires_grad=False)
  303. layer.w2_weight = torch.nn.Parameter(w2_weight,
  304. requires_grad=False)
  305. return
  306. # If checkpoint is fp8, we need to handle that the
  307. # MoE kernels require single activation scale and single weight
  308. # scale for w13 per expert.
  309. else:
  310. # Fp8 moe kernels require a single activation scale.
  311. # We take the max of all the scales in case they differ.
  312. if self.quant_config.activation_scheme == "static":
  313. if layer.a13_scale is None or layer.a2_scale is None:
  314. raise ValueError(
  315. "QuantConfig has static quantization, but found "
  316. "activation scales are None.")
  317. if (not all_close_1d(layer.a13_scale)
  318. or not all_close_1d(layer.a2_scale)):
  319. print_warning_once(
  320. "Found input_scales that are not equal for "
  321. "fp8 MoE layer. Using the maximum across experts "
  322. "for each layer. ")
  323. layer.a13_scale = torch.nn.Parameter(layer.a13_scale.max(),
  324. requires_grad=False)
  325. layer.a2_scale = torch.nn.Parameter(layer.a2_scale.max(),
  326. requires_grad=False)
  327. # Fp8 moe kernel needs single weight scale for w13 per expert.
  328. # We take the max then dequant and requant each expert.
  329. assert layer.w13_scale is not None
  330. shard_size = layer.intermediate_size_per_partition
  331. max_w13_scales = layer.w13_scale.max(dim=1).values
  332. for expert_id in range(layer.num_experts):
  333. start = 0
  334. for shard_id in range(2):
  335. dq_weight = per_tensor_dequantize(
  336. layer.w13_weight[expert_id][start:start +
  337. shard_size, :],
  338. layer.w13_scale[expert_id][shard_id])
  339. layer.w13_weight[expert_id][
  340. start:start + shard_size, :], _ = ops.scaled_fp8_quant(
  341. dq_weight, max_w13_scales[expert_id])
  342. start += shard_size
  343. layer.w13_scale = torch.nn.Parameter(max_w13_scales,
  344. requires_grad=False)
  345. return
  346. def apply(self,
  347. layer: torch.nn.Module,
  348. x: torch.Tensor,
  349. router_logits: torch.Tensor,
  350. top_k: int,
  351. renormalize: bool = True,
  352. use_grouped_topk: bool = False,
  353. num_expert_group: Optional[int] = None,
  354. topk_group: Optional[int] = None) -> torch.Tensor:
  355. from aphrodite.modeling.layers.fused_moe import fused_moe
  356. return fused_moe(x,
  357. layer.w13_weight,
  358. layer.w2_weight,
  359. router_logits,
  360. top_k,
  361. renormalize=renormalize,
  362. inplace=True,
  363. use_fp8=True,
  364. w1_scale=layer.w13_scale,
  365. w2_scale=layer.w2_scale,
  366. a1_scale=layer.a13_scale,
  367. a2_scale=layer.a2_scale,
  368. use_grouped_topk=use_grouped_topk,
  369. num_expert_group=num_expert_group,
  370. topk_group=topk_group)
  371. class Fp8KVCacheMethod(BaseKVCacheMethod):
  372. """
  373. Supports loading kv-cache scaling factors from FP8 checkpoints.
  374. """
  375. def __init__(self, quant_config: Fp8Config):
  376. super().__init__(quant_config)