gptq.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import enum
  2. from enum import Enum
  3. from fractions import Fraction
  4. from typing import Any, Dict, List, Optional
  5. import torch
  6. from torch.nn.parameter import Parameter
  7. from aphrodite._quant_C import quant_ops as ops
  8. from aphrodite.modeling.layers.linear import LinearBase, LinearMethodBase
  9. from aphrodite.modeling.utils import set_weight_attrs
  10. from aphrodite.quantization.base_config import QuantizationConfig
  11. class GPTQConfig(QuantizationConfig):
  12. """Config class for GPTQ.
  13. Reference: https://arxiv.org/abs/2210.17323
  14. """
  15. def __init__(
  16. self,
  17. weight_bits: int,
  18. group_size: int,
  19. desc_act: bool,
  20. ) -> None:
  21. self.weight_bits = weight_bits
  22. self.group_size = group_size
  23. self.desc_act = desc_act
  24. self.pack_factor = Fraction(32, self.weight_bits)
  25. if self.weight_bits not in [2, 3, 4, 8]:
  26. raise ValueError(
  27. "Currently, only 2/3/4/8-bit weight quantization is "
  28. f"supported for GPTQ, but got {self.weight_bits} bits.")
  29. def __repr__(self) -> str:
  30. return (f"GPTQConfig(weight_bits={self.weight_bits}, "
  31. f"group_size={self.group_size}, "
  32. f"desc_act={self.desc_act})")
  33. @classmethod
  34. def get_name(cls) -> str:
  35. return "gptq"
  36. @classmethod
  37. def get_supported_act_dtypes(cls) -> List[torch.dtype]:
  38. return [torch.half]
  39. @classmethod
  40. # Need to figure it out
  41. def get_min_capability(cls) -> int:
  42. return 60
  43. @classmethod
  44. def get_config_filenames(cls) -> List[str]:
  45. return ["quantize_config.json"]
  46. @classmethod
  47. def from_config(cls, config: Dict[str, Any]) -> "GPTQConfig":
  48. weight_bits = cls.get_from_keys(config, ["bits"])
  49. group_size = cls.get_from_keys(config, ["group_size"])
  50. desc_act = cls.get_from_keys(config, ["desc_act"])
  51. return cls(weight_bits, group_size, desc_act)
  52. def get_quant_method(
  53. self, layer: torch.nn.Module) -> Optional["GPTQLinearMethod"]:
  54. if isinstance(layer, LinearBase):
  55. return GPTQLinearMethod(self)
  56. return None
  57. def get_scaled_act_names(self) -> List[str]:
  58. return []
  59. class ExllamaState(Enum):
  60. UNUSED = enum.auto()
  61. UNINITIALIZED = enum.auto()
  62. READY = enum.auto()
  63. class GPTQLinearMethod(LinearMethodBase):
  64. """Linear method for GPTQ.
  65. Args:
  66. quant_config: The GPTQ quantization config.
  67. """
  68. def __init__(self, quant_config: GPTQConfig):
  69. self.quant_config = quant_config
  70. def create_weights(
  71. self,
  72. layer: torch.nn.Module,
  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. **extra_weight_attrs,
  79. ):
  80. del output_size # Unused.
  81. if input_size_per_partition % self.quant_config.group_size != 0:
  82. raise ValueError(
  83. "The input size is not aligned with the quantized "
  84. "weight shape. This can be caused by too large "
  85. "tensor parallel size.")
  86. output_size_per_partition = sum(output_partition_sizes)
  87. if (output_size_per_partition % self.quant_config.pack_factor.numerator
  88. != 0):
  89. raise ValueError(
  90. "The output size is not aligned with the quantized "
  91. "weight shape. This can be caused by too large "
  92. "tensor parallel size.")
  93. if self.quant_config.group_size != -1:
  94. group_size = self.quant_config.group_size
  95. else:
  96. group_size = input_size
  97. exllama_state = ExllamaState.UNINITIALIZED
  98. scale_and_zero_size = input_size // group_size
  99. scale_and_zero_input_dim = None
  100. if (input_size != input_size_per_partition
  101. and self.quant_config.group_size != -1):
  102. # For act-order models, we cannot use Exllama for row parallel layer
  103. if self.quant_config.desc_act:
  104. exllama_state = ExllamaState.UNUSED
  105. else:
  106. # we need to partition qzeros and scales for exllama kernel
  107. scale_and_zero_size = input_size_per_partition // group_size
  108. scale_and_zero_input_dim = 0
  109. qweight = Parameter(
  110. torch.empty(
  111. input_size_per_partition // self.quant_config.pack_factor,
  112. output_size_per_partition,
  113. dtype=torch.int32,
  114. ),
  115. requires_grad=False,
  116. )
  117. set_weight_attrs(
  118. qweight, {
  119. "input_dim": 0,
  120. "output_dim": 1,
  121. "packed_dim": 0,
  122. "pack_factor": self.quant_config.pack_factor,
  123. })
  124. g_idx = Parameter(
  125. torch.tensor(
  126. [
  127. i // self.quant_config.group_size
  128. for i in range(input_size_per_partition)
  129. ],
  130. dtype=torch.int32,
  131. ),
  132. requires_grad=False,
  133. )
  134. # Ignore warning from fused linear layers such as QKVParallelLinear.
  135. set_weight_attrs(g_idx, {"input_dim": 0, "ignore_warning": True})
  136. qzeros = Parameter(
  137. torch.empty(
  138. scale_and_zero_size,
  139. output_size_per_partition // self.quant_config.pack_factor,
  140. dtype=torch.int32,
  141. ),
  142. requires_grad=False,
  143. )
  144. set_weight_attrs(
  145. qzeros, {
  146. "input_dim": scale_and_zero_input_dim,
  147. "output_dim": 1,
  148. "packed_dim": 1,
  149. "pack_factor": self.quant_config.pack_factor,
  150. })
  151. scales = Parameter(
  152. torch.empty(
  153. scale_and_zero_size,
  154. output_size_per_partition,
  155. dtype=params_dtype,
  156. ),
  157. requires_grad=False,
  158. )
  159. set_weight_attrs(scales, {
  160. "input_dim": scale_and_zero_input_dim,
  161. "output_dim": 1,
  162. })
  163. layer.register_parameter("qweight", qweight)
  164. set_weight_attrs(qweight, extra_weight_attrs)
  165. layer.register_parameter("g_idx", g_idx)
  166. set_weight_attrs(g_idx, extra_weight_attrs)
  167. layer.register_parameter("qzeros", qzeros)
  168. set_weight_attrs(qzeros, extra_weight_attrs)
  169. layer.register_parameter("scales", scales)
  170. set_weight_attrs(scales, extra_weight_attrs)
  171. layer.exllama_state = exllama_state
  172. def apply(self,
  173. layer: torch.nn.Module,
  174. x: torch.Tensor,
  175. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  176. qweight = layer.qweight
  177. out_shape = x.shape[:-1] + (qweight.shape[-1], )
  178. reshaped_x = x.reshape(-1, x.shape[-1])
  179. # exllama needs to shuffle the weight after the weight is loaded
  180. # here we do the shuffle on first forward pass
  181. if layer.exllama_state == ExllamaState.UNINITIALIZED:
  182. if self.quant_config.desc_act:
  183. layer.g_idx.data = torch.argsort(layer.g_idx).to(torch.int)
  184. else:
  185. layer.g_idx.data = torch.empty((0, ),
  186. device=layer.g_idx.device)
  187. layer.exllama_state = ExllamaState.READY
  188. ops.gptq_shuffle(layer.qweight, layer.g_idx,
  189. self.quant_config.weight_bits)
  190. output = ops.gptq_gemm(reshaped_x, layer.qweight, layer.qzeros,
  191. layer.scales, layer.g_idx,
  192. layer.exllama_state == ExllamaState.READY,
  193. self.quant_config.weight_bits)
  194. if bias is not None:
  195. output.add_(bias)
  196. return output.reshape(out_shape)