gptq.py 11 KB

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