awq.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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.linear import (LinearMethodBase,
  6. set_weight_attrs)
  7. from aphrodite.modeling.layers.quantization.base_config import QuantizationConfig
  8. class AWQConfig(QuantizationConfig):
  9. """Config class for AWQ.
  10. Reference: https://arxiv.org/abs/2306.00978
  11. """
  12. def __init__(
  13. self,
  14. weight_bits: int,
  15. group_size: int,
  16. zero_point: bool,
  17. ) -> None:
  18. self.weight_bits = weight_bits
  19. self.group_size = group_size
  20. self.zero_point = zero_point
  21. if self.weight_bits != 4:
  22. raise ValueError(
  23. "Currently, only 4-bit weight quantization is supported for "
  24. f"AWQ, but got {self.weight_bits} bits.")
  25. self.pack_factor = 32 // self.weight_bits
  26. def __repr__(self) -> str:
  27. return (f"AWQConfig(weight_bits={self.weight_bits}, "
  28. f"group_size={self.group_size}, "
  29. f"zero_point={self.zero_point})")
  30. def get_name(self) -> str:
  31. return "awq"
  32. def get_supported_act_dtypes(self) -> List[torch.dtype]:
  33. return [torch.half]
  34. def get_min_capability(self) -> int:
  35. # The AWQ kernel only supports Turing or newer GPUs.
  36. return 75
  37. @staticmethod
  38. def get_config_filenames() -> List[str]:
  39. return [
  40. "quant_config.json", # E.g., casperhansen/vicuna-7b-v1.5-awq
  41. "quantize_config.json", # E.g., abhinavkulkarni/mosaicml-mpt-7b-instruct-w4-g128-awq # pylint: disable=line-too-long
  42. ]
  43. @classmethod
  44. def from_config(cls, config: Dict[str, Any]) -> "AWQConfig":
  45. weight_bits = cls.get_from_keys(config, ["w_bit", "bits"])
  46. group_size = cls.get_from_keys(config, ["q_group_size", "group_size"])
  47. zero_point = cls.get_from_keys(config, ["zero_point"])
  48. return cls(weight_bits, group_size, zero_point)
  49. def get_linear_method(self) -> "AWQLinearMethod":
  50. return AWQLinearMethod(self)
  51. def get_scaled_act_names(self) -> List[str]:
  52. return ["gelu", "gelu_fast", "gelu_new", "gelu_pytorch_tanh"]
  53. def merge_weight(self) -> bool:
  54. return True
  55. def rope_style(self) -> Optional[bool]:
  56. return None
  57. class AWQLinearMethod(LinearMethodBase):
  58. """Linear method for AWQ.
  59. Args:
  60. quant_config: The AWQ quantization config.
  61. """
  62. def __init__(self, quant_config: AWQConfig):
  63. self.quant_config = quant_config
  64. def create_weights(self, input_size_per_partition: int,
  65. output_size_per_partition: int, input_size: int,
  66. output_size: int,
  67. params_dtype: torch.dtype) -> Dict[str, Any]:
  68. if input_size_per_partition % self.quant_config.group_size != 0:
  69. raise ValueError(
  70. "The input size is not aligned with the quantized "
  71. "weight shape. This can be caused by too large "
  72. "tensor parallel size.")
  73. if output_size_per_partition % self.quant_config.pack_factor != 0:
  74. raise ValueError(
  75. "The output size is not aligned with the quantized "
  76. "weight shape. This can be caused by too large "
  77. "tensor parallel size.")
  78. qweight = Parameter(
  79. torch.empty(
  80. input_size_per_partition,
  81. output_size_per_partition // self.quant_config.pack_factor,
  82. dtype=torch.int32,
  83. ),
  84. requires_grad=False,
  85. )
  86. set_weight_attrs(
  87. qweight, {
  88. "input_dim": 0,
  89. "output_dim": 1,
  90. "packed_dim": 1,
  91. "pack_factor": self.quant_config.pack_factor,
  92. })
  93. qzeros = Parameter(
  94. torch.empty(
  95. input_size_per_partition // self.quant_config.group_size,
  96. output_size_per_partition // self.quant_config.pack_factor,
  97. dtype=torch.int32,
  98. ),
  99. requires_grad=False,
  100. )
  101. set_weight_attrs(
  102. qzeros, {
  103. "input_dim": 0,
  104. "output_dim": 1,
  105. "packed_dim": 1,
  106. "pack_factor": self.quant_config.pack_factor,
  107. })
  108. scales = Parameter(
  109. torch.empty(
  110. input_size_per_partition // self.quant_config.group_size,
  111. output_size_per_partition,
  112. dtype=params_dtype,
  113. ),
  114. requires_grad=False,
  115. )
  116. set_weight_attrs(scales, {
  117. "input_dim": 0,
  118. "output_dim": 1,
  119. })
  120. return {
  121. "qweight": qweight,
  122. "qzeros": qzeros,
  123. "scales": scales,
  124. }
  125. def apply_weights(self,
  126. weights: Dict[str, Any],
  127. x: torch.Tensor,
  128. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  129. qweight = weights["qweight"]
  130. qzeros = weights["qzeros"]
  131. scales = weights["scales"]
  132. pack_factor = self.quant_config.pack_factor
  133. out_shape = (x.shape[:-1] + (qweight.shape[-1] * pack_factor, ))
  134. reshaped_x = x.reshape(-1, x.shape[-1])
  135. # num_tokens >= threshold
  136. FP16_MATMUL_HEURISTIC_CONDITION = x.shape[:-1].numel() >= 256
  137. if FP16_MATMUL_HEURISTIC_CONDITION:
  138. out = ops.awq_dequantize(qweight, scales, qzeros, 0, 0, 0)
  139. out = torch.matmul(reshaped_x, out)
  140. else:
  141. out = ops.awq_gemm(reshaped_x, qweight, scales, qzeros,
  142. pack_factor)
  143. if bias is not None:
  144. out = out + bias
  145. return out.reshape(out_shape)