gptq.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import enum
  2. from enum import Enum
  3. from typing import Any, Dict, List, Optional
  4. from fractions import Fraction
  5. import torch
  6. from torch.nn.parameter import Parameter
  7. from aphrodite._C import ops
  8. from aphrodite.modeling.layers.fused_moe import (fused_moe, fused_topk,
  9. moe_align_block_size)
  10. from aphrodite.modeling.layers.linear import LinearMethodBase, set_weight_attrs
  11. from aphrodite.modeling.layers.quantization.base_config import (
  12. QuantizationConfig, )
  13. class GPTQConfig(QuantizationConfig):
  14. """Config class for GPTQ.
  15. Reference: https://arxiv.org/abs/2210.17323
  16. """
  17. def __init__(
  18. self,
  19. weight_bits: int,
  20. group_size: int,
  21. desc_act: bool,
  22. ) -> None:
  23. self.weight_bits = weight_bits
  24. self.group_size = group_size
  25. self.desc_act = desc_act
  26. self.pack_factor = Fraction(32, self.weight_bits)
  27. if self.weight_bits not in [2, 3, 4, 8]:
  28. raise ValueError(
  29. "Currently, only 2/3/4/8-bit weight quantization is supported "
  30. f"for GPTQ, but got {self.weight_bits} bits.")
  31. def __repr__(self) -> str:
  32. return (f"GPTQConfig(weight_bits={self.weight_bits}, "
  33. f"group_size={self.group_size}, "
  34. f"desc_act={self.desc_act})")
  35. @classmethod
  36. def get_name(cls) -> str:
  37. return "gptq"
  38. @classmethod
  39. def get_supported_act_dtypes(cls) -> List[torch.dtype]:
  40. return [torch.half]
  41. @classmethod
  42. # Need to figure it out
  43. def get_min_capability(cls) -> int:
  44. return 60
  45. @classmethod
  46. def get_config_filenames(cls) -> List[str]:
  47. return ["quantize_config.json"]
  48. @classmethod
  49. def from_config(cls, config: Dict[str, Any]) -> "GPTQConfig":
  50. weight_bits = cls.get_from_keys(config, ["bits"])
  51. group_size = cls.get_from_keys(config, ["group_size"])
  52. desc_act = cls.get_from_keys(config, ["desc_act"])
  53. return cls(weight_bits, group_size, desc_act)
  54. def get_linear_method(self) -> "GPTQLinearMethod":
  55. return GPTQLinearMethod(self)
  56. def get_scaled_act_names(self) -> List[str]:
  57. return []
  58. def merge_weight(self) -> bool:
  59. return True
  60. def rope_style(self) -> Optional[bool]:
  61. return None
  62. def quant_vocab(self) -> List[bool]:
  63. return [False, False]
  64. def support_fused_moe(self) -> bool:
  65. return self.weight_bits == 4
  66. class ExllamaState(Enum):
  67. UNUSED = enum.auto()
  68. UNINITIALIZED = enum.auto()
  69. READY = enum.auto()
  70. class GPTQLinearMethod(LinearMethodBase):
  71. """Linear method for GPTQ.
  72. Args:
  73. quant_config: The GPTQ quantization config.
  74. """
  75. def __init__(self, quant_config: GPTQConfig):
  76. self.quant_config = quant_config
  77. def create_weights(
  78. self,
  79. input_size_per_partition: int,
  80. output_partition_sizes: List[int],
  81. input_size: int,
  82. output_size: int,
  83. params_dtype: torch.dtype,
  84. ) -> Dict[str, Any]:
  85. del output_size # Unused.
  86. if input_size_per_partition % self.quant_config.group_size != 0:
  87. raise ValueError(
  88. "The input size is not aligned with the quantized "
  89. "weight shape. This can be caused by too large "
  90. "tensor parallel size.")
  91. output_size_per_partition = sum(output_partition_sizes)
  92. if (output_size_per_partition % self.quant_config.pack_factor.numerator
  93. != 0):
  94. raise ValueError(
  95. "The output size is not aligned with the quantized "
  96. "weight shape. This can be caused by too large "
  97. "tensor parallel size.")
  98. if self.quant_config.group_size != -1:
  99. group_size = self.quant_config.group_size
  100. else:
  101. group_size = input_size
  102. exllama_state = ExllamaState.UNINITIALIZED
  103. scale_and_zero_size = input_size // group_size
  104. scale_and_zero_input_dim = None
  105. if (input_size != input_size_per_partition
  106. and self.quant_config.group_size != -1):
  107. # For act-order models, we cannot use Exllama for row parallel layer
  108. if self.quant_config.desc_act:
  109. exllama_state = ExllamaState.UNUSED
  110. else:
  111. # we need to partition qzeros and scales for exllama kernel
  112. scale_and_zero_size = input_size_per_partition // group_size
  113. scale_and_zero_input_dim = 0
  114. qweight = Parameter(
  115. torch.empty(
  116. input_size_per_partition // self.quant_config.pack_factor,
  117. output_size_per_partition,
  118. dtype=torch.int32,
  119. ),
  120. requires_grad=False,
  121. )
  122. set_weight_attrs(
  123. qweight,
  124. {
  125. "input_dim": 0,
  126. "output_dim": 1,
  127. "packed_dim": 0,
  128. "pack_factor": self.quant_config.pack_factor,
  129. },
  130. )
  131. g_idx = Parameter(
  132. torch.tensor(
  133. [
  134. i // self.quant_config.group_size
  135. for i in range(input_size_per_partition)
  136. ],
  137. dtype=torch.int32,
  138. ),
  139. requires_grad=False,
  140. )
  141. # Ignore warning from fused linear layers such as QKVParallelLinear.
  142. set_weight_attrs(g_idx, {"input_dim": 0, "ignore_warning": True})
  143. qzeros = Parameter(
  144. torch.empty(
  145. scale_and_zero_size,
  146. output_size_per_partition // self.quant_config.pack_factor,
  147. dtype=torch.int32,
  148. ),
  149. requires_grad=False,
  150. )
  151. set_weight_attrs(
  152. qzeros,
  153. {
  154. "input_dim": scale_and_zero_input_dim,
  155. "output_dim": 1,
  156. "packed_dim": 1,
  157. "pack_factor": self.quant_config.pack_factor,
  158. },
  159. )
  160. scales = Parameter(
  161. torch.empty(
  162. scale_and_zero_size,
  163. output_size_per_partition,
  164. dtype=params_dtype,
  165. ),
  166. requires_grad=False,
  167. )
  168. set_weight_attrs(
  169. scales,
  170. {
  171. "input_dim": scale_and_zero_input_dim,
  172. "output_dim": 1,
  173. },
  174. )
  175. return {
  176. "qweight": qweight,
  177. "g_idx": g_idx,
  178. "qzeros": qzeros,
  179. "scales": scales,
  180. "exllama_state": exllama_state,
  181. }
  182. def apply_weights(
  183. self,
  184. weights: Dict[str, Any],
  185. x: torch.Tensor,
  186. bias: Optional[torch.Tensor] = None,
  187. ) -> torch.Tensor:
  188. qweight = weights["qweight"]
  189. out_shape = x.shape[:-1] + (qweight.shape[-1], )
  190. reshaped_x = x.reshape(-1, x.shape[-1])
  191. # exllama needs to shuffle the weight after the weight is loaded
  192. # here we do the shuffle on first forward pass
  193. if weights["exllama_state"] == ExllamaState.UNINITIALIZED:
  194. if self.quant_config.desc_act:
  195. weights["g_idx"] = torch.argsort(weights["g_idx"]).to(
  196. torch.int)
  197. else:
  198. weights["g_idx"] = torch.empty((1, 1), device="meta")
  199. weights["exllama_state"] = ExllamaState.READY
  200. ops.gptq_shuffle(
  201. weights["qweight"],
  202. weights["g_idx"],
  203. self.quant_config.weight_bits,
  204. )
  205. output = ops.gptq_gemm(
  206. reshaped_x,
  207. weights["qweight"],
  208. weights["qzeros"],
  209. weights["scales"],
  210. weights["g_idx"],
  211. weights["exllama_state"] == ExllamaState.READY,
  212. self.quant_config.weight_bits,
  213. )
  214. if bias is not None:
  215. output = output + bias
  216. return output.reshape(out_shape)
  217. def apply_moe_weights(
  218. self,
  219. w1: Dict[str, torch.Tensor],
  220. w2: Dict[str, torch.Tensor],
  221. x: torch.Tensor,
  222. gating_output: torch.Tensor,
  223. topk: int,
  224. renormalize: bool,
  225. ) -> torch.Tensor:
  226. # shuffle weights for exllama
  227. # ignore marlin now which doesn't support fuse moe yet
  228. for w in [w1, w2]:
  229. if w["exllama_state"] == ExllamaState.UNINITIALIZED:
  230. if self.quant_config.desc_act:
  231. w["g_idx"] = torch.argsort(w["g_idx"],
  232. dim=-1).to(torch.int)
  233. else:
  234. w["g_idx"] = torch.empty((1, 1), device="meta")
  235. w["exllama_state"] = ExllamaState.READY
  236. ops.gptq_shuffle(w["qweight"], w["g_idx"],
  237. self.quant_config.weight_bits)
  238. if x.shape[0] >= 128:
  239. dequant_w1 = ops.dequant_gptq(
  240. w1["qweight"],
  241. w1["qzeros"],
  242. w1["scales"],
  243. w1["g_idx"],
  244. self.quant_config.weight_bits,
  245. w1["exllama_state"] == ExllamaState.READY,
  246. ).permute(0, 2, 1)
  247. dequant_w2 = ops.dequant_gptq(
  248. w2["qweight"],
  249. w2["qzeros"],
  250. w2["scales"],
  251. w2["g_idx"],
  252. self.quant_config.weight_bits,
  253. w2["exllama_state"] == ExllamaState.READY,
  254. ).permute(0, 2, 1)
  255. return fused_moe(x, dequant_w1, dequant_w2, gating_output, topk,
  256. renormalize)
  257. topk_weights, topk_ids = fused_topk(gating_output, topk, renormalize)
  258. (
  259. sorted_token_ids,
  260. expert_ids,
  261. num_tokens_post_padded,
  262. ) = moe_align_block_size(topk_ids, 8, w1["qweight"].shape[0])
  263. x = x.view(x.shape[0], 1, *x.shape[1:])
  264. gate_up = ops.group_gptq_gemm(
  265. x,
  266. w1["qweight"],
  267. w1["qzeros"],
  268. w1["scales"],
  269. w1["g_idx"],
  270. topk_weights,
  271. sorted_token_ids,
  272. expert_ids,
  273. num_tokens_post_padded,
  274. False,
  275. w1["exllama_state"] == ExllamaState.READY,
  276. )
  277. out = torch.empty(
  278. (gate_up.shape[:-1] + (gate_up.shape[-1] // 2, )),
  279. dtype=x.dtype,
  280. device=x.device,
  281. )
  282. ops.silu_and_mul(out, gate_up)
  283. out = ops.group_gptq_gemm(
  284. out,
  285. w2["qweight"],
  286. w2["qzeros"],
  287. w2["scales"],
  288. w2["g_idx"],
  289. topk_weights,
  290. sorted_token_ids,
  291. expert_ids,
  292. num_tokens_post_padded,
  293. True,
  294. w2["exllama_state"] == ExllamaState.READY,
  295. )
  296. return torch.sum(out, dim=1)