awq.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from torch.nn.parameter import Parameter
  4. from aphrodite._C import ops
  5. from aphrodite.modeling.layers.fused_moe import (moe_align_block_size,
  6. fused_moe, fused_topk)
  7. from aphrodite.modeling.layers.linear import (LinearMethodBase,
  8. set_weight_attrs)
  9. from aphrodite.modeling.layers.quantization.base_config import (
  10. QuantizationConfig)
  11. class AWQConfig(QuantizationConfig):
  12. """Config class for AWQ.
  13. Reference: https://arxiv.org/abs/2306.00978
  14. """
  15. def __init__(
  16. self,
  17. weight_bits: int,
  18. group_size: int,
  19. zero_point: bool,
  20. ) -> None:
  21. self.weight_bits = weight_bits
  22. self.group_size = group_size
  23. self.zero_point = zero_point
  24. if self.weight_bits != 4:
  25. raise ValueError(
  26. "Currently, only 4-bit weight quantization is supported for "
  27. f"AWQ, but got {self.weight_bits} bits.")
  28. self.pack_factor = 32 // self.weight_bits
  29. def __repr__(self) -> str:
  30. return (f"AWQConfig(weight_bits={self.weight_bits}, "
  31. f"group_size={self.group_size}, "
  32. f"zero_point={self.zero_point})")
  33. def get_name(self) -> str:
  34. return "awq"
  35. def get_supported_act_dtypes(self) -> List[torch.dtype]:
  36. return [torch.half]
  37. def get_min_capability(self) -> int:
  38. # The AWQ kernel only supports Turing or newer GPUs.
  39. return 75
  40. @staticmethod
  41. def get_config_filenames() -> List[str]:
  42. return [
  43. "quant_config.json",
  44. "quantize_config.json",
  45. ]
  46. @classmethod
  47. def from_config(cls, config: Dict[str, Any]) -> "AWQConfig":
  48. weight_bits = cls.get_from_keys(config, ["w_bit", "bits"])
  49. group_size = cls.get_from_keys(config, ["q_group_size", "group_size"])
  50. zero_point = cls.get_from_keys(config, ["zero_point"])
  51. return cls(weight_bits, group_size, zero_point)
  52. def get_linear_method(self) -> "AWQLinearMethod":
  53. return AWQLinearMethod(self)
  54. def get_scaled_act_names(self) -> List[str]:
  55. return ["gelu", "gelu_fast", "gelu_new", "gelu_pytorch_tanh"]
  56. def merge_weight(self) -> bool:
  57. return True
  58. def rope_style(self) -> Optional[bool]:
  59. return None
  60. def quant_vocab(self) -> List[bool]:
  61. return [False, False]
  62. def support_fused_moe(self) -> bool:
  63. return True
  64. class AWQLinearMethod(LinearMethodBase):
  65. """Linear method for AWQ.
  66. Args:
  67. quant_config: The AWQ quantization config.
  68. """
  69. def __init__(self, quant_config: AWQConfig):
  70. self.quant_config = quant_config
  71. def create_weights(
  72. self,
  73. input_size_per_partition: int,
  74. output_partition_sizes: List[int],
  75. input_size: int,
  76. output_size: int,
  77. params_dtype: torch.dtype,
  78. ) -> Dict[str, Any]:
  79. if input_size_per_partition % self.quant_config.group_size != 0:
  80. raise ValueError(
  81. "The input size is not aligned with the quantized "
  82. "weight shape. This can be caused by too large "
  83. "tensor parallel size.")
  84. output_size_per_partition = sum(output_partition_sizes)
  85. if output_size_per_partition % self.quant_config.pack_factor != 0:
  86. raise ValueError(
  87. "The output size is not aligned with the quantized "
  88. "weight shape. This can be caused by too large "
  89. "tensor parallel size.")
  90. qweight = Parameter(
  91. torch.empty(
  92. input_size_per_partition,
  93. output_size_per_partition // self.quant_config.pack_factor,
  94. dtype=torch.int32,
  95. ),
  96. requires_grad=False,
  97. )
  98. set_weight_attrs(
  99. qweight, {
  100. "input_dim": 0,
  101. "output_dim": 1,
  102. "packed_dim": 1,
  103. "pack_factor": self.quant_config.pack_factor,
  104. })
  105. qzeros = Parameter(
  106. torch.empty(
  107. input_size_per_partition // self.quant_config.group_size,
  108. output_size_per_partition // self.quant_config.pack_factor,
  109. dtype=torch.int32,
  110. ),
  111. requires_grad=False,
  112. )
  113. set_weight_attrs(
  114. qzeros, {
  115. "input_dim": 0,
  116. "output_dim": 1,
  117. "packed_dim": 1,
  118. "pack_factor": self.quant_config.pack_factor,
  119. })
  120. scales = Parameter(
  121. torch.empty(
  122. input_size_per_partition // self.quant_config.group_size,
  123. output_size_per_partition,
  124. dtype=params_dtype,
  125. ),
  126. requires_grad=False,
  127. )
  128. set_weight_attrs(scales, {
  129. "input_dim": 0,
  130. "output_dim": 1,
  131. })
  132. return {
  133. "qweight": qweight,
  134. "qzeros": qzeros,
  135. "scales": scales,
  136. }
  137. def apply_weights(self,
  138. weights: Dict[str, Any],
  139. x: torch.Tensor,
  140. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  141. qweight = weights["qweight"]
  142. qzeros = weights["qzeros"]
  143. scales = weights["scales"]
  144. pack_factor = self.quant_config.pack_factor
  145. out_shape = (x.shape[:-1] + (qweight.shape[-1] * pack_factor, ))
  146. reshaped_x = x.reshape(-1, x.shape[-1])
  147. # num_tokens >= threshold
  148. FP16_MATMUL_HEURISTIC_CONDITION = x.shape[:-1].numel() >= 256
  149. if FP16_MATMUL_HEURISTIC_CONDITION:
  150. out = ops.awq_dequantize(qweight, scales, qzeros, 0, 0, 0)
  151. out = torch.matmul(reshaped_x, out)
  152. else:
  153. out = ops.awq_gemm(reshaped_x, qweight, scales, qzeros,
  154. pack_factor)
  155. if bias is not None:
  156. out = out + bias
  157. return out.reshape(out_shape)
  158. def apply_moe_weights(self, w1: Dict[str,
  159. torch.Tensor], w2: Dict[str,
  160. torch.Tensor],
  161. x: torch.Tensor, gating_output: torch.Tensor,
  162. topk: int, renormalize: bool) -> torch.Tensor:
  163. FP16_MATMUL_HEURISTIC_CONDITION = x.shape[:-1].numel() >= 1024
  164. if FP16_MATMUL_HEURISTIC_CONDITION:
  165. dequant_w1 = ops.awq_dequantize(w1["qweight"], w1["scales"],
  166. w1["qzeros"], 0, 0,
  167. 0).permute(0, 2, 1)
  168. dequant_w2 = ops.awq_dequantize(w2["qweight"], w2["scales"],
  169. w2["qzeros"], 0, 0,
  170. 0).permute(0, 2, 1)
  171. return fused_moe(x, dequant_w1, dequant_w2, gating_output, topk,
  172. renormalize)
  173. topk_weights, topk_ids = fused_topk(gating_output, topk, renormalize)
  174. (sorted_token_ids, expert_ids,
  175. num_tokens_post_padded) = moe_align_block_size(
  176. topk_ids, 16, w1["qweight"].shape[0])
  177. x = x.view(x.shape[0], 1, *x.shape[1:])
  178. pack_factor = self.quant_config.pack_factor
  179. gate_up = ops.awq_group_gemm(x, w1["qweight"], w1["scales"],
  180. w1["qzeros"], topk_weights,
  181. sorted_token_ids, expert_ids,
  182. num_tokens_post_padded, False,
  183. pack_factor)
  184. out = torch.empty((gate_up.shape[:-1] + (gate_up.shape[-1] // 2, )),
  185. dtype=x.dtype,
  186. device=x.device)
  187. ops.silu_and_mul(out, gate_up)
  188. out = ops.awq_group_gemm(out, w2["qweight"], w2["scales"],
  189. w2["qzeros"], topk_weights, sorted_token_ids,
  190. expert_ids, num_tokens_post_padded, True,
  191. pack_factor)
  192. return torch.sum(out, dim=1)