fbgemm_fp8.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from torch.nn import Module
  4. from torch.nn.parameter import Parameter
  5. from aphrodite.common.utils import is_hip
  6. from aphrodite.modeling.layers.linear import (LinearBase, LinearMethodBase,
  7. UnquantizedLinearMethod)
  8. from aphrodite.modeling.parameter import (ChannelQuantScaleParameter,
  9. ModelWeightParameter)
  10. from aphrodite.platforms import current_platform
  11. from aphrodite.quantization.base_config import (QuantizationConfig,
  12. QuantizeMethodBase)
  13. from aphrodite.quantization.fp8 import cutlass_fp8_supported
  14. from aphrodite.quantization.utils.marlin_utils_fp8 import (
  15. apply_fp8_marlin_linear, prepare_fp8_layer_for_marlin)
  16. from aphrodite.quantization.utils.quant_utils import is_layer_skipped
  17. from aphrodite.quantization.utils.w8a8_utils import (
  18. apply_fp8_linear, normalize_e4m3fn_to_e4m3fnuz)
  19. class FBGEMMFp8Config(QuantizationConfig):
  20. """Config class for FBGEMM Fp8."""
  21. def __init__(self, ignore_list: List[str], input_scale_ub: float):
  22. self.ignore_list = ignore_list if ignore_list else []
  23. self.input_scale_ub = input_scale_ub
  24. # For GPUs that lack FP8 hardware support, we can leverage the Marlin
  25. # kernel for fast weight-only FP8 quantization
  26. capability = current_platform.get_device_capability()
  27. capability = capability[0] * 10 + capability[1]
  28. self.use_marlin = capability < 89
  29. @classmethod
  30. def get_name(cls) -> str:
  31. return "fbgemm_fp8"
  32. @classmethod
  33. def get_supported_act_dtypes(cls) -> List[torch.dtype]:
  34. return [torch.bfloat16, torch.float16]
  35. @classmethod
  36. def get_min_capability(cls) -> int:
  37. return 80
  38. @classmethod
  39. def get_config_filenames(cls) -> List[str]:
  40. return []
  41. @classmethod
  42. def from_config(cls, config: Dict[str, Any]) -> "FBGEMMFp8Config":
  43. ignore_list = cls.get_from_keys(config, ["modules_to_not_convert"])
  44. input_scale_ub = cls.get_from_keys(config, ["activation_scale_ub"])
  45. return cls(ignore_list=ignore_list, input_scale_ub=input_scale_ub)
  46. def get_quant_method(self, layer: torch.nn.Module,
  47. prefix: str) -> Optional["QuantizeMethodBase"]:
  48. if isinstance(layer, LinearBase):
  49. if is_layer_skipped(prefix, self.ignore_list):
  50. return UnquantizedLinearMethod()
  51. return FBGEMMFp8LinearMethod(self)
  52. return None
  53. def get_scaled_act_names(self) -> List[str]:
  54. return []
  55. class FBGEMMFp8LinearMethod(LinearMethodBase):
  56. def __init__(self, quant_config: FBGEMMFp8Config):
  57. self.quant_config = quant_config
  58. self.cutlass_fp8_supported = cutlass_fp8_supported()
  59. def create_weights(
  60. self,
  61. layer: torch.nn.Module,
  62. input_size_per_partition: int,
  63. output_partition_sizes: List[int],
  64. input_size: int,
  65. output_size: int,
  66. params_dtype: torch.dtype,
  67. **extra_weight_attrs,
  68. ):
  69. weight_loader = extra_weight_attrs.get("weight_loader")
  70. del input_size, output_size
  71. output_size_per_partition = sum(output_partition_sizes)
  72. layer.logical_widths = output_partition_sizes
  73. layer.input_size_per_partition = input_size_per_partition
  74. layer.output_size_per_partition = output_size_per_partition
  75. layer.orig_dtype = params_dtype
  76. # WEIGHT
  77. weight = ModelWeightParameter(data=torch.empty(
  78. output_size_per_partition,
  79. input_size_per_partition,
  80. dtype=torch.float8_e4m3fn),
  81. input_dim=1,
  82. output_dim=0,
  83. weight_loader=weight_loader)
  84. layer.register_parameter("weight", weight)
  85. # WEIGHT SCALE
  86. weight_scale = ChannelQuantScaleParameter(data=torch.empty(
  87. (sum(output_partition_sizes), 1), dtype=torch.float32),
  88. output_dim=0,
  89. weight_loader=weight_loader)
  90. weight_scale[:] = torch.finfo(torch.float32).min
  91. layer.register_parameter("weight_scale", weight_scale)
  92. # INPUT SCALE UPPER BOUND
  93. input_scale_ub = torch.nn.Parameter(torch.tensor(
  94. (self.quant_config.input_scale_ub), dtype=torch.float32),
  95. requires_grad=False)
  96. layer.input_scale_ub = input_scale_ub
  97. def process_weights_after_loading(self, layer: Module) -> None:
  98. # required by torch.compile
  99. layer.weight_scale = Parameter(layer.weight_scale.data,
  100. requires_grad=False)
  101. layer.weight = Parameter(layer.weight.data, requires_grad=False)
  102. weight = layer.weight
  103. if is_hip():
  104. weight, weight_scale, input_scale = \
  105. normalize_e4m3fn_to_e4m3fnuz(
  106. weight=weight,
  107. weight_scale=layer.weight_scale,
  108. input_scale=None)
  109. if input_scale is not None:
  110. layer.input_scale = Parameter(input_scale, requires_grad=False)
  111. layer.weight_scale = Parameter(weight_scale, requires_grad=False)
  112. layer.weight = Parameter(weight.t(), requires_grad=False)
  113. if self.quant_config.use_marlin:
  114. prepare_fp8_layer_for_marlin(layer)
  115. # Activations not quantized for marlin.
  116. del layer.input_scale_ub
  117. def apply(self,
  118. layer: torch.nn.Module,
  119. x: torch.Tensor,
  120. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  121. if self.quant_config.use_marlin:
  122. return apply_fp8_marlin_linear(
  123. input=x,
  124. weight=layer.weight,
  125. weight_scale=layer.weight_scale,
  126. workspace=layer.workspace,
  127. size_n=layer.output_size_per_partition,
  128. size_k=layer.input_size_per_partition,
  129. bias=bias)
  130. return apply_fp8_linear(
  131. input=x,
  132. weight=layer.weight,
  133. weight_scale=layer.weight_scale,
  134. input_scale=None,
  135. input_scale_ub=layer.input_scale_ub,
  136. bias=bias,
  137. cutlass_fp8_supported=self.cutlass_fp8_supported,
  138. use_per_token_if_dynamic=True)