fp8.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from loguru import logger
  4. from torch.nn import Module
  5. from torch.nn.parameter import Parameter
  6. import aphrodite.common.envs as envs
  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 = envs.APHRODITE_TEST_FORCE_FP8_MARLIN
  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. # Disable marlin for rocm
  103. if is_hip():
  104. self.use_marlin = False
  105. def create_weights(
  106. self,
  107. layer: torch.nn.Module,
  108. input_size_per_partition: int,
  109. output_partition_sizes: List[int],
  110. input_size: int,
  111. output_size: int,
  112. params_dtype: torch.dtype,
  113. **extra_weight_attrs,
  114. ):
  115. del input_size, output_size
  116. output_size_per_partition = sum(output_partition_sizes)
  117. layer.logical_widths = output_partition_sizes
  118. layer.input_size_per_partition = input_size_per_partition
  119. layer.output_size_per_partition = output_size_per_partition
  120. layer.orig_dtype = params_dtype
  121. # WEIGHT
  122. weight_dtype = (torch.float8_e4m3fn
  123. if self.quant_config.is_checkpoint_fp8_serialized else
  124. params_dtype)
  125. weight = Parameter(torch.empty(output_size_per_partition,
  126. input_size_per_partition,
  127. dtype=weight_dtype),
  128. requires_grad=False)
  129. layer.register_parameter("weight", weight)
  130. set_weight_attrs(weight, {
  131. **extra_weight_attrs,
  132. "input_dim": 1,
  133. "output_dim": 0,
  134. })
  135. # If checkpoint is serialized fp8, load them.
  136. # Otherwise, wait until process_weights_after_loading.
  137. if self.quant_config.is_checkpoint_fp8_serialized:
  138. # WEIGHT SCALE
  139. scale = create_per_tensor_scale_param(output_partition_sizes,
  140. **extra_weight_attrs)
  141. layer.register_parameter("weight_scale", scale)
  142. # INPUT ACTIVATION SCALE
  143. if self.quant_config.activation_scheme == "static":
  144. scale = create_per_tensor_scale_param(output_partition_sizes,
  145. **extra_weight_attrs)
  146. layer.register_parameter("input_scale", scale)
  147. else:
  148. layer.register_parameter("input_scale", None)
  149. def process_weights_after_loading(self, layer: Module) -> None:
  150. # If checkpoint not serialized fp8, quantize the weights.
  151. if not self.quant_config.is_checkpoint_fp8_serialized:
  152. qweight, weight_scale = ops.scaled_fp8_quant(layer.weight,
  153. scale=None)
  154. # If using marlin (w8a16), kernel uses channelwise weights,
  155. # so extend the weight scales to be channelwise.
  156. if self.use_marlin:
  157. assert weight_scale.numel() == 1
  158. weight_scale = convert_to_channelwise(
  159. weight_scale.expand(len(layer.logical_widths)),
  160. layer.logical_widths)
  161. # Update the layer with the new values.
  162. layer.weight = Parameter(qweight.t(), requires_grad=False)
  163. layer.weight_scale = Parameter(weight_scale, requires_grad=False)
  164. layer.input_scale = None
  165. # If checkpoint is fp8, handle that there are N scales for N
  166. # shards in a fused module
  167. else:
  168. # If using marlin (w8a16), kernel uses channelwise weights,
  169. # so extend the weight scales to be channelwise.
  170. if self.use_marlin:
  171. weight = layer.weight
  172. weight_scale = convert_to_channelwise(layer.weight_scale,
  173. layer.logical_widths)
  174. # If using w8a8, torch._scaled_mm needs per tensor, so
  175. # requantize the logical shards as a single weight.
  176. else:
  177. # Dequant -> Quant with max scale so we can run per tensor.
  178. weight = layer.weight
  179. weight_scale = layer.weight_scale
  180. # If rocm, use float8_e4m3fnuz.
  181. if is_hip():
  182. weight, weight_scale, input_scale = \
  183. normalize_e4m3fn_to_e4m3fnuz(
  184. weight=weight,
  185. weight_scale=weight_scale,
  186. input_scale=layer.input_scale)
  187. if input_scale is not None:
  188. layer.input_scale = Parameter(input_scale,
  189. requires_grad=False)
  190. weight_scale, weight = requantize_with_max_scale(
  191. weight=weight,
  192. weight_scale=weight_scale,
  193. logical_widths=layer.logical_widths,
  194. )
  195. # Update layer with new values.
  196. layer.weight = Parameter(weight.t(), requires_grad=False)
  197. layer.weight_scale = Parameter(weight_scale, requires_grad=False)
  198. if self.quant_config.activation_scheme == "static":
  199. layer.input_scale = Parameter(layer.input_scale.max(),
  200. requires_grad=False)
  201. if self.use_marlin:
  202. prepare_fp8_layer_for_marlin(layer)
  203. # Activations not quantized for marlin.
  204. del layer.input_scale
  205. def apply(self,
  206. layer: torch.nn.Module,
  207. x: torch.Tensor,
  208. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  209. if self.use_marlin:
  210. return apply_fp8_marlin_linear(
  211. input=x,
  212. weight=layer.weight,
  213. weight_scale=layer.weight_scale,
  214. workspace=layer.workspace,
  215. size_n=layer.output_size_per_partition,
  216. size_k=layer.input_size_per_partition,
  217. bias=bias)
  218. return apply_fp8_linear(
  219. input=x,
  220. weight=layer.weight,
  221. weight_scale=layer.weight_scale,
  222. input_scale=layer.input_scale,
  223. bias=bias,
  224. cutlass_fp8_supported=self.cutlass_fp8_supported,
  225. use_per_token_if_dynamic=False)
  226. class Fp8MoEMethod(FusedMoEMethodBase):
  227. """MoE method for FP8.
  228. Supports loading FP8 checkpoints with static weight scale and
  229. dynamic/static activation scale.
  230. Also supports loading quantized FP16/BF16 model checkpoints with dynamic
  231. activation scaling. The weight scaling factor will be initialized after
  232. the model weights are loaded.
  233. Args:
  234. quant_config: The quantization config.
  235. """
  236. def __init__(self, quant_config: Fp8Config):
  237. self.quant_config = quant_config
  238. def create_weights(self, layer: Module, num_experts: int, hidden_size: int,
  239. intermediate_size: int, params_dtype: torch.dtype,
  240. **extra_weight_attrs):
  241. if self.quant_config.is_checkpoint_fp8_serialized:
  242. params_dtype = torch.float8_e4m3fn
  243. # WEIGHTS
  244. w13_weight = torch.nn.Parameter(torch.empty(num_experts,
  245. 2 * intermediate_size,
  246. hidden_size,
  247. dtype=params_dtype),
  248. requires_grad=False)
  249. layer.register_parameter("w13_weight", w13_weight)
  250. set_weight_attrs(w13_weight, extra_weight_attrs)
  251. w2_weight = torch.nn.Parameter(torch.empty(num_experts,
  252. hidden_size,
  253. intermediate_size,
  254. dtype=params_dtype),
  255. requires_grad=False)
  256. layer.register_parameter("w2_weight", w2_weight)
  257. set_weight_attrs(w2_weight, extra_weight_attrs)
  258. # WEIGHT_SCALES
  259. # Allocate 2 scales for w1 and w3 respectively.
  260. # They will be combined to a single scale after weight loading.
  261. w13_weight_scale = torch.nn.Parameter(torch.ones(num_experts,
  262. 2,
  263. dtype=torch.float32),
  264. requires_grad=False)
  265. layer.register_parameter("w13_weight_scale", w13_weight_scale)
  266. w2_weight_scale = torch.nn.Parameter(torch.ones(num_experts,
  267. dtype=torch.float32),
  268. requires_grad=False)
  269. layer.register_parameter("w2_weight_scale", w2_weight_scale)
  270. # If loading fp8 checkpoint, pass the weight loaders.
  271. # If loading an fp16 checkpoint, do not (we will quantize in
  272. # process_weights_after_loading()
  273. if self.quant_config.is_checkpoint_fp8_serialized:
  274. set_weight_attrs(w13_weight_scale, {
  275. "is_fp8_scale": True,
  276. **extra_weight_attrs
  277. })
  278. set_weight_attrs(w2_weight_scale, {
  279. "is_fp8_scale": True,
  280. **extra_weight_attrs
  281. })
  282. # INPUT_SCALES
  283. if self.quant_config.activation_scheme == "static":
  284. if not self.quant_config.is_checkpoint_fp8_serialized:
  285. raise ValueError(
  286. "Found static activation scheme for checkpoint that "
  287. "was not serialized fp8.")
  288. w13_input_scale = torch.nn.Parameter(torch.ones(
  289. num_experts, dtype=torch.float32),
  290. requires_grad=False)
  291. layer.register_parameter("w13_input_scale", w13_input_scale)
  292. set_weight_attrs(w13_input_scale, {
  293. "is_fp8_scale": True,
  294. **extra_weight_attrs
  295. })
  296. w2_input_scale = torch.nn.Parameter(torch.ones(
  297. num_experts, dtype=torch.float32),
  298. requires_grad=False)
  299. layer.register_parameter("w2_input_scale", w2_input_scale)
  300. set_weight_attrs(w2_input_scale, {
  301. "is_fp8_scale": True,
  302. **extra_weight_attrs
  303. })
  304. else:
  305. layer.w13_input_scale = None
  306. layer.w2_input_scale = None
  307. def process_weights_after_loading(self, layer: Module) -> None:
  308. # If checkpoint is fp16, quantize in place.
  309. if not self.quant_config.is_checkpoint_fp8_serialized:
  310. # If rocm, use float8_e4m3fnuz as dtype
  311. fp8_dtype = torch.float8_e4m3fnuz \
  312. if is_hip() else torch.float8_e4m3fn
  313. w13_weight = torch.empty_like(layer.w13_weight.data,
  314. dtype=fp8_dtype)
  315. w2_weight = torch.empty_like(layer.w2_weight.data, dtype=fp8_dtype)
  316. # Re-initialize w13_scale because we directly quantize
  317. # merged w13 weights and generate a single scaling factor.
  318. layer.w13_weight_scale = torch.nn.Parameter(torch.ones(
  319. layer.num_experts,
  320. dtype=torch.float32,
  321. device=w13_weight.device),
  322. requires_grad=False)
  323. for expert in range(layer.num_experts):
  324. w13_weight[expert, :, :], layer.w13_weight_scale[
  325. expert] = ops.scaled_fp8_quant(
  326. layer.w13_weight.data[expert, :, :])
  327. w2_weight[expert, :, :], layer.w2_weight_scale[
  328. expert] = ops.scaled_fp8_quant(
  329. layer.w2_weight.data[expert, :, :])
  330. layer.w13_weight = torch.nn.Parameter(w13_weight,
  331. requires_grad=False)
  332. layer.w2_weight = torch.nn.Parameter(w2_weight,
  333. requires_grad=False)
  334. return
  335. # If checkpoint is fp8, we need to handle that the
  336. # MoE kernels require single activation scale and single weight
  337. # scale for w13 per expert.
  338. else:
  339. # Fp8 moe kernels require a single activation scale.
  340. # We take the max of all the scales in case they differ.
  341. if self.quant_config.activation_scheme == "static":
  342. if (layer.w13_input_scale is None
  343. or layer.w2_input_scale is None):
  344. raise ValueError(
  345. "QuantConfig has static quantization, but found "
  346. "activation scales are None.")
  347. if (not all_close_1d(layer.w13_input_scale)
  348. or not all_close_1d(layer.w2_input_scale)):
  349. print_warning_once(
  350. "Found input_scales that are not equal for "
  351. "fp8 MoE layer. Using the maximum across experts "
  352. "for each layer. ")
  353. layer.w13_input_scale = torch.nn.Parameter(
  354. layer.w13_input_scale.max(), requires_grad=False)
  355. layer.w2_input_scale = torch.nn.Parameter(
  356. layer.w2_input_scale.max(), requires_grad=False)
  357. # If rocm, normalize the weights and scales to e4m3fnuz
  358. if is_hip():
  359. # Normalize the weights and scales
  360. w13_weight, w13_weight_scale, w13_input_scale = \
  361. normalize_e4m3fn_to_e4m3fnuz(
  362. layer.w13_weight, layer.w13_weight_scale,
  363. layer.w13_input_scale)
  364. w2_weight, w2_weight_scale, w2_input_scale = \
  365. normalize_e4m3fn_to_e4m3fnuz(
  366. layer.w2_weight, layer.w2_weight_scale,
  367. layer.w2_input_scale)
  368. # Reset the parameter
  369. layer.w13_weight = torch.nn.Parameter(w13_weight,
  370. requires_grad=False)
  371. layer.w13_weight_scale = torch.nn.Parameter(
  372. w13_weight_scale, requires_grad=False)
  373. if w13_input_scale is not None:
  374. layer.w13_input_scale = torch.nn.Parameter(
  375. w13_input_scale, requires_grad=False)
  376. layer.w2_weight = torch.nn.Parameter(w2_weight,
  377. requires_grad=False)
  378. layer.w2_weight_scale = torch.nn.Parameter(w2_weight_scale,
  379. requires_grad=False)
  380. if w2_input_scale is not None:
  381. layer.w2_input_scale = torch.nn.Parameter(
  382. w2_input_scale, requires_grad=False)
  383. # Fp8 moe kernel needs single weight scale for w13 per expert.
  384. # We take the max then dequant and requant each expert.
  385. assert layer.w13_weight_scale is not None
  386. shard_size = layer.intermediate_size_per_partition
  387. max_w13_scales = layer.w13_weight_scale.max(dim=1).values
  388. for expert_id in range(layer.num_experts):
  389. start = 0
  390. for shard_id in range(2):
  391. dq_weight = per_tensor_dequantize(
  392. layer.w13_weight[expert_id][start:start +
  393. shard_size, :],
  394. layer.w13_weight_scale[expert_id][shard_id])
  395. layer.w13_weight[expert_id][
  396. start:start + shard_size, :], _ = ops.scaled_fp8_quant(
  397. dq_weight, max_w13_scales[expert_id])
  398. start += shard_size
  399. layer.w13_weight_scale = torch.nn.Parameter(max_w13_scales,
  400. requires_grad=False)
  401. return
  402. def apply(self,
  403. layer: torch.nn.Module,
  404. x: torch.Tensor,
  405. router_logits: torch.Tensor,
  406. top_k: int,
  407. renormalize: bool,
  408. use_grouped_topk: bool,
  409. topk_group: Optional[int] = None,
  410. num_expert_group: Optional[int] = None) -> torch.Tensor:
  411. from aphrodite.modeling.layers.fused_moe import fused_experts
  412. topk_weights, topk_ids = FusedMoE.select_experts(
  413. hidden_states=x,
  414. router_logits=router_logits,
  415. use_grouped_topk=use_grouped_topk,
  416. top_k=top_k,
  417. renormalize=renormalize,
  418. topk_group=topk_group,
  419. num_expert_group=num_expert_group)
  420. return fused_experts(x,
  421. layer.w13_weight,
  422. layer.w2_weight,
  423. topk_weights=topk_weights,
  424. topk_ids=topk_ids,
  425. inplace=True,
  426. use_fp8_w8a8=True,
  427. w1_scale=layer.w13_weight_scale,
  428. w2_scale=layer.w2_weight_scale,
  429. a1_scale=layer.w13_input_scale,
  430. a2_scale=layer.w2_input_scale)
  431. class Fp8KVCacheMethod(BaseKVCacheMethod):
  432. """
  433. Supports loading kv-cache scaling factors from FP8 checkpoints.
  434. """
  435. def __init__(self, quant_config: Fp8Config):
  436. super().__init__(quant_config)