fp8.py 22 KB

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