1
0

quant_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """This file is used for /tests and /benchmarks"""
  2. from typing import List
  3. import numpy
  4. import torch
  5. from aphrodite.quantization.qqq import MARLIN_QQQ_SUPPORTED_NUM_BITS
  6. from aphrodite.scalar_type import ScalarType, scalar_types
  7. SUPPORTED_GPTQ_QUANT_TYPES = [scalar_types.uint4b8, scalar_types.uint8b128]
  8. SUPPORTED_GROUP_SIZES = [-1, 32, 64, 128]
  9. # NOTE: this is a hack. We should update each model to register the
  10. # stacked params and get it from there instead in a future PR.
  11. # fused_name: List[shard_name]
  12. FUSED_LAYER_NAME_MAPPING = {
  13. "qkv_proj": ["q_proj", "k_proj", "v_proj"],
  14. "gate_up_proj": ["gate_proj", "up_proj"]
  15. }
  16. def is_layer_skipped(prefix: str, ignored_layers: List[str]) -> bool:
  17. # prefix: model.layers.0.self_attn.q_proj
  18. # proj_name: q_proj
  19. proj_name = prefix.split(".")[-1]
  20. if proj_name in FUSED_LAYER_NAME_MAPPING:
  21. shard_prefixes = [
  22. prefix.replace(proj_name, shard_proj_name)
  23. for shard_proj_name in FUSED_LAYER_NAME_MAPPING[proj_name]
  24. ]
  25. is_skipped = None
  26. for shard_prefix in shard_prefixes:
  27. is_shard_skipped = shard_prefix in ignored_layers
  28. if is_skipped is None:
  29. is_skipped = is_shard_skipped
  30. elif is_shard_skipped != is_skipped:
  31. raise ValueError(
  32. f"Detected some but not all shards of {prefix} "
  33. "are quantized. All shards of fused layers "
  34. "to have the same precision.")
  35. else:
  36. is_skipped = prefix in ignored_layers
  37. assert is_skipped is not None
  38. return is_skipped
  39. def get_pack_factor(num_bits):
  40. assert 32 % num_bits == 0, f"Unsupported num_bits = {num_bits}"
  41. return 32 // num_bits
  42. def permute_rows(q_w: torch.Tensor, w_ref: torch.Tensor, group_size: int):
  43. assert q_w.shape == w_ref.shape
  44. orig_device = q_w.device
  45. k_size, _ = q_w.shape
  46. g_idx = torch.zeros((k_size, ), dtype=torch.int32)
  47. for i in range(k_size):
  48. g_idx[i] = i // group_size
  49. # Simulate act_order by doing a random permutation on K
  50. rand_perm = torch.randperm(k_size)
  51. g_idx = g_idx[rand_perm].contiguous()
  52. q_w = q_w[rand_perm, :].contiguous()
  53. w_ref = w_ref[rand_perm, :].contiguous()
  54. return (
  55. w_ref.to(device=orig_device),
  56. q_w.to(device=orig_device),
  57. g_idx.to(device=orig_device),
  58. rand_perm.to(device=orig_device),
  59. )
  60. def quantize_weights(w: torch.Tensor,
  61. quant_type: ScalarType,
  62. group_size: int,
  63. zero_points: bool = False):
  64. assert quant_type.is_integer(), \
  65. "Floating point quantization may work but has not been tested"
  66. orig_device = w.device
  67. orig_type = w.dtype
  68. size_k, size_n = w.shape
  69. assert w.is_floating_point(), "w must be float"
  70. if group_size == -1:
  71. group_size = size_k
  72. assert group_size <= size_k
  73. # Reshape to [groupsize, -1]
  74. if group_size < size_k:
  75. w = w.reshape((-1, group_size, size_n))
  76. w = w.permute(1, 0, 2)
  77. w = w.reshape((group_size, -1))
  78. # Compute scale for each group
  79. max_val = torch.max(w, 0, keepdim=True).values
  80. min_val = torch.min(w, 0, keepdim=True).values
  81. max_q_val = quant_type.max()
  82. min_q_val = quant_type.min()
  83. if zero_points:
  84. assert not quant_type.is_signed() and quant_type.max() > 0
  85. w_s = (max_val - min_val).clamp(min=1e-5) / quant_type.max()
  86. maybe_w_zp = torch.round(torch.abs(min_val / w_s)) \
  87. .clamp(min_q_val, max_q_val).int()
  88. else:
  89. # If the bias is such that there are no possible negative/positive
  90. # values, set the max value to inf to avoid divide by 0
  91. w_s = torch.max(
  92. abs(max_val / (max_q_val if max_q_val != 0 else torch.inf)),
  93. abs(min_val / (min_q_val if min_q_val != 0 else torch.inf)))
  94. maybe_w_zp = None
  95. # Quantize
  96. w_q = torch.round(w / w_s).int() + (maybe_w_zp if zero_points else 0)
  97. w_q = torch.clamp(w_q, min_q_val, max_q_val)
  98. # Compute ref (dequantized)
  99. w_ref = (w_q - (maybe_w_zp if zero_points else 0)).to(orig_type) * w_s
  100. if quant_type.has_bias():
  101. w_q += quant_type.bias
  102. # Restore original shapes
  103. if group_size < size_k:
  104. def reshape_w(w):
  105. w = w.reshape((group_size, -1, size_n))
  106. w = w.permute(1, 0, 2)
  107. w = w.reshape((size_k, size_n)).contiguous()
  108. return w
  109. w_q = reshape_w(w_q)
  110. w_ref = reshape_w(w_ref)
  111. w_s = w_s.reshape((-1, size_n)).contiguous()
  112. if zero_points:
  113. maybe_w_zp = maybe_w_zp.reshape((-1, size_n)).contiguous()
  114. maybe_w_zp = maybe_w_zp.to(device=orig_device)
  115. return (
  116. w_ref.to(device=orig_device),
  117. w_q.to(device=orig_device),
  118. w_s.to(device=orig_device),
  119. maybe_w_zp,
  120. )
  121. def gptq_quantize_weights(w: torch.Tensor, quant_type: ScalarType,
  122. group_size: int, act_order: bool):
  123. size_k, _ = w.shape
  124. assert w.is_floating_point(), "w must be float"
  125. assert quant_type in SUPPORTED_GPTQ_QUANT_TYPES, \
  126. f"Unsupported gptq type = {quant_type}"
  127. assert group_size in SUPPORTED_GROUP_SIZES + [
  128. size_k
  129. ], f"Unsupported groupsize = {group_size}"
  130. w_ref, w_q, w_s, _ = quantize_weights(w, quant_type, group_size)
  131. # Apply act_order
  132. g_idx = torch.empty(0, dtype=torch.int, device=w.device)
  133. rand_perm = torch.empty(0, dtype=torch.int, device=w.device)
  134. if act_order:
  135. assert (
  136. group_size < size_k
  137. ), "For act_order, groupsize = {} must be less than size_k = {}".format(
  138. group_size, size_k)
  139. w_ref, w_q, g_idx, rand_perm = permute_rows(w_q, w_ref, group_size)
  140. return w_ref, w_q, w_s, g_idx, rand_perm
  141. # QQQ employs different quant schemes for per-group and
  142. # per-channel quantization.
  143. def qqq_quantize_weights(w: torch.Tensor, num_bits: int, group_size: int):
  144. orig_device = w.device
  145. size_k, size_n = w.shape
  146. assert w.is_floating_point(), "w must be float"
  147. assert num_bits in MARLIN_QQQ_SUPPORTED_NUM_BITS, \
  148. f"Unsupported num_bits = {num_bits}"
  149. assert group_size in SUPPORTED_GROUP_SIZES + [
  150. size_k
  151. ], f"Unsupported groupsize = {group_size}"
  152. if group_size == -1:
  153. group_size = size_k
  154. assert group_size <= size_k
  155. if group_size < size_k:
  156. # Reshape to [groupsize, -1]
  157. w = w.reshape((-1, group_size, size_n))
  158. w = w.permute(1, 0, 2)
  159. w = w.reshape((group_size, -1))
  160. max_q_val = 2**num_bits - 1
  161. half_q_val = (max_q_val + 1) // 2
  162. # Compute scale for each group
  163. s_group = torch.max(torch.abs(w), 0, keepdim=True)[0]
  164. s_group *= 2 / max_q_val # 2 => symmetric
  165. # Quantize
  166. q_w = torch.round(w / s_group).int()
  167. q_w += half_q_val
  168. q_w = torch.clamp(q_w, 0, max_q_val)
  169. # Compute ref (dequantized)
  170. w_ref = (q_w - half_q_val).half() * s_group
  171. # Restore original shapes
  172. def reshape_w(w):
  173. w = w.reshape((group_size, -1, size_n))
  174. w = w.permute(1, 0, 2)
  175. w = w.reshape((size_k, size_n)).contiguous()
  176. return w
  177. q_w = reshape_w(q_w)
  178. w_ref = reshape_w(w_ref)
  179. # Compute int8 quantization scale for each channel
  180. s_channel = torch.max(torch.abs(w_ref), 0, keepdim=True)[0]
  181. s_channel /= 127.0
  182. t_int8 = (w_ref / s_channel).round().clamp(-128, 127).to(torch.int8)
  183. w_ref = t_int8.half() * s_channel
  184. s_channel = s_channel.reshape(1, -1).to(dtype=torch.float)
  185. # Fuse scales
  186. s_group = (s_group.reshape(-1, size_n).contiguous() /
  187. s_channel).to(dtype=torch.half)
  188. else:
  189. max_q_val = 2**(num_bits - 1) - 1
  190. # Compute scale for each channel
  191. s_channel = torch.max(torch.abs(w), 0, keepdim=True)[0]
  192. s_channel /= max_q_val
  193. # Quantize
  194. q_w = torch.round(w / s_channel).int()
  195. q_w = torch.clamp(q_w, -max_q_val, max_q_val)
  196. # Compute ref (dequantized)
  197. w_ref = q_w.half() * s_channel
  198. s_group = torch.tensor([], dtype=torch.half)
  199. # div 2 ** (8 - self.bits)) to offset right shift in unpacking
  200. s_channel /= (2**(8 - num_bits))
  201. s_channel = s_channel.reshape(-1, size_n).contiguous().to(torch.float)
  202. return (
  203. w_ref.to(device=orig_device),
  204. q_w.to(device=orig_device),
  205. s_group.to(device=orig_device),
  206. s_channel.to(device=orig_device),
  207. )
  208. def sort_weights(q_w: torch.Tensor, g_idx: torch.Tensor):
  209. orig_device = q_w.device
  210. sort_indices = torch.argsort(g_idx).to(
  211. dtype=torch.int32) # Sort based on g_idx
  212. g_idx = g_idx[sort_indices].contiguous()
  213. q_w = q_w[sort_indices, :].contiguous()
  214. return (
  215. q_w.to(device=orig_device),
  216. g_idx.to(device=orig_device),
  217. sort_indices.to(device=orig_device),
  218. )
  219. def pack_rows(
  220. q_w: torch.Tensor,
  221. num_bits: int,
  222. size_k: int,
  223. size_n: int,
  224. ):
  225. assert q_w.shape == (size_k, size_n)
  226. pack_factor = get_pack_factor(num_bits)
  227. assert size_k % pack_factor == 0
  228. orig_device = q_w.device
  229. q_w = q_w.cpu().numpy().astype(numpy.uint32)
  230. q_res = numpy.zeros((size_k // pack_factor, size_n), dtype=numpy.uint32)
  231. for i in range(pack_factor):
  232. q_res |= q_w[i::pack_factor, :] << num_bits * i
  233. q_res = torch.from_numpy(q_res.astype(numpy.int32)).to(orig_device)
  234. return q_res
  235. def pack_cols(
  236. q_w: torch.Tensor,
  237. num_bits: int,
  238. size_k: int,
  239. size_n: int,
  240. ):
  241. assert q_w.shape == (size_k, size_n)
  242. pack_factor = get_pack_factor(num_bits)
  243. assert size_n % pack_factor == 0
  244. orig_device = q_w.device
  245. q_w = q_w.cpu().numpy().astype(numpy.uint32)
  246. q_res = numpy.zeros((size_k, size_n // pack_factor), dtype=numpy.uint32)
  247. for i in range(pack_factor):
  248. q_res |= q_w[:, i::pack_factor] << num_bits * i
  249. q_res = torch.from_numpy(q_res.astype(numpy.int32)).to(orig_device)
  250. q_res = q_res.contiguous()
  251. return q_res
  252. def unpack_cols(
  253. packed_q_w: torch.Tensor,
  254. num_bits: int,
  255. size_k: int,
  256. size_n: int,
  257. ):
  258. pack_factor = get_pack_factor(num_bits)
  259. assert size_n % pack_factor == 0
  260. assert packed_q_w.shape == (
  261. size_k, size_n // pack_factor
  262. ), "packed_q_w.shape = {} size_k = {}, size_n = {} pack_Factor = {}".format(
  263. packed_q_w.shape, size_k, size_n, pack_factor)
  264. orig_device = packed_q_w.device
  265. packed_q_w_cpu = packed_q_w.cpu().numpy().astype(numpy.uint32)
  266. q_res = numpy.zeros((size_k, size_n), dtype=numpy.uint32)
  267. mask = (1 << num_bits) - 1
  268. for i in range(pack_factor):
  269. vals = packed_q_w_cpu & mask
  270. packed_q_w_cpu >>= num_bits
  271. q_res[:, i::pack_factor] = vals
  272. q_res = torch.from_numpy(q_res.astype(numpy.int32)).to(orig_device)
  273. q_res = q_res.contiguous()
  274. return q_res
  275. def gptq_pack(
  276. q_w: torch.Tensor,
  277. num_bits: int,
  278. size_k: int,
  279. size_n: int,
  280. ):
  281. return pack_rows(q_w, num_bits, size_k, size_n)
  282. def awq_pack(
  283. q_w: torch.Tensor,
  284. num_bits: int,
  285. size_k: int,
  286. size_n: int,
  287. ):
  288. assert q_w.shape == (size_k, size_n)
  289. # Interleave column dim (for the dequantize code) and pack it to int32
  290. if num_bits == 4:
  291. interleave = numpy.array([0, 2, 4, 6, 1, 3, 5, 7])
  292. elif num_bits == 8:
  293. interleave = numpy.array([0, 2, 1, 3])
  294. else:
  295. raise Exception("num_bits must be 4 or 8, got {}".format(num_bits))
  296. q_w = q_w.reshape((-1, len(interleave)))[:, interleave].ravel()
  297. q_w = q_w.reshape((-1, size_n)).contiguous()
  298. return pack_cols(q_w, num_bits, size_k, size_n)