marlin_utils_test_24.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. """Utility functions used for tests and benchmarks"""
  2. import random
  3. from typing import List
  4. import numpy
  5. import torch
  6. from aphrodite.scalar_type import ScalarType
  7. from .marlin_utils_test import marlin_weights
  8. from .quant_utils import gptq_quantize_weights
  9. # This is PyTorch implementation of main part of reorder_meta()
  10. # function, from tools/util/include/cutlass/util/host_reorder.h file
  11. # of CUTLASS source tree. Furthermore, CUTLASS template for sparse
  12. # GEMM decides upon layout of this matrix, and at the moment for the
  13. # sparse GEMM executed on tensor cores, this is layout described by
  14. # ColumnMajorInterleaved<2> data structure, in
  15. # include/cutlass/layout/matrix.h of CUTLASS source tree. The
  16. # reordering of meta matrix into meta_reordered matrix calculated
  17. # according to these segments of CUTLASS code is re-implemented here.
  18. # Note that this calculation produces offsets for scattering metadata
  19. # matrix elements into reordered metadata matrix elements (or,
  20. # equivalently, for gathering reordered metadata matrix element back
  21. # into metadata matrix elements).
  22. def _calculate_meta_reordering_scatter_offsets(m, meta_ncols, meta_dtype,
  23. device):
  24. dst_rows = torch.arange(0, m, device=device)[:, None].repeat(1, meta_ncols)
  25. dst_cols = torch.arange(0, meta_ncols, device=device).repeat(m, 1)
  26. # Reorder the rows, then swizzle the 2x2 blocks.
  27. group_x = 64
  28. group_y = 32 if meta_dtype.itemsize == 2 else 16
  29. dst_rows = (dst_rows // group_x * group_x + (dst_rows % 2) * 2 +
  30. (dst_rows % 8) // 4 + ((dst_rows % group_y) % 4) // 2 * 32 +
  31. ((dst_rows % group_x) // 8) * 4)
  32. topright = ((dst_rows % 2 == 0) & (dst_cols % 2 == 1)).to(torch.int8)
  33. bottomleft = ((dst_rows % 2 == 1) & (dst_cols % 2 == 0)).to(torch.int8)
  34. dst_rows += topright - bottomleft
  35. dst_cols -= topright - bottomleft
  36. # Assumed that meta tensor is to be stored in CUTLASS
  37. # InterleavedColumnMajor layout, and reverse engineered
  38. # corresponding code to store values into this tensor.
  39. interleave = 2
  40. cols_maj = dst_cols // interleave
  41. cols_min = dst_cols % interleave
  42. return (cols_maj * m * interleave + dst_rows * interleave +
  43. cols_min).view(-1)
  44. # This function converts dense matrix into sparse semi-structured
  45. # representation, producing "compressed" matrix, in the layout used by
  46. # CUTLASS backend, and corresponding metadata matrix.
  47. def sparse_semi_structured_from_dense_cutlass(dense):
  48. if dense.dim() != 2:
  49. raise RuntimeError(
  50. f"Expected 2-dimensional dense tensor, got {dense.dim()}-dimensional tensor" # noqa: E501
  51. )
  52. m, k = dense.shape
  53. device = dense.device
  54. meta_dtype = torch.int8
  55. if dense.dtype == torch.int8:
  56. meta_dtype = torch.int32
  57. elif dense.dtype in [torch.half, torch.bfloat16, torch.float, torch.int32]:
  58. meta_dtype = torch.int16
  59. else:
  60. raise RuntimeError(f"Invalid datatype {dense.dtype} of dense matrix")
  61. quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4
  62. if quadbits_per_meta_elem not in (4, 8):
  63. raise RuntimeError(
  64. "Invalid number of elements per meta element calculated")
  65. if meta_dtype == torch.int32:
  66. if m % 16 != 0:
  67. raise RuntimeError(
  68. f"Number of rows of dense matrix {m} must be divisible by 16")
  69. else:
  70. if m % 32 != 0:
  71. raise RuntimeError(
  72. f"Number of rows of dense matrix {m} must be divisible by 32")
  73. if k % (4 * quadbits_per_meta_elem) != 0:
  74. raise RuntimeError(
  75. f"Number of columns of dense matrix {k} must be divisible by {4 * quadbits_per_meta_elem}" # noqa: E501
  76. )
  77. if dense.dtype != torch.float:
  78. ksparse = 4
  79. dense_4 = dense.view(-1, k // ksparse, ksparse)
  80. m0, m1, m2, m3 = (dense_4 != 0).unbind(-1)
  81. else:
  82. ksparse = 2
  83. dense_2 = dense.view(-1, k // ksparse, ksparse)
  84. m0, m2 = m1, m3 = (dense_2 != 0).unbind(-1)
  85. meta_ncols = k // (ksparse * quadbits_per_meta_elem)
  86. # Encoding quadruples of True/False values as follows:
  87. # [True, True, False, False] -> 0b0100
  88. # [True, False, True, False] -> 0b1000
  89. # [False, True, True, False] -> 0b1001
  90. # [True, False, False, True ] -> 0b1100
  91. # [False, True, False, True ] -> 0b1101
  92. # [False, False, True, True ] -> 0b1110
  93. # Thus, lower two bits in the encoding are index of the True value
  94. # at the lowest index in the quadruple, and the higher two bits in
  95. # the encoding are index of the other True value in the quadruple.
  96. # In case there are less than two True values, than False value or
  97. # values at some index or indices are considered True for the
  98. # encoding. In case there are more than two True values, then the
  99. # excess True value(s) at some indices are considered False for
  100. # the encoding. The exact encodings used for these cases are as
  101. # follows:
  102. # [False, False, False, False] -> 0b1110
  103. # [False, False, False, True ] -> 0b1110
  104. # [False, False, True, False] -> 0b1110
  105. # [False, True, False, False] -> 0b1001
  106. # [False, True, True, True ] -> 0b1101
  107. # [True, False, False, False] -> 0b1000
  108. # [True, False, True, True ] -> 0b1100
  109. # [True, True, False, True ] -> 0b0100
  110. # [True, True, True, False] -> 0b0100
  111. # [True, True, True, True ] -> 0b0100
  112. # These particular encodings are chosen, with the help of Espresso
  113. # logic minimizer software, for the purpose of minimization of
  114. # corresponding Boolean functions, that translate non-zero flags
  115. # into encoding bits. Note also possible choices for the first
  116. # and last of these encodings were limited only to (0b0100,
  117. # 0b1110), in order to produce valid encodings for 1:2 sparsity
  118. # case.
  119. expr0 = m0 & m1
  120. expr1 = ~m0 & m1
  121. expr2 = ~m0 & ~m1
  122. bit0 = expr1
  123. bit1 = expr2
  124. bit2 = expr0 | expr2 | m3
  125. bit3 = expr1 | ~m1
  126. idxs0 = bit0 | (bit1.to(torch.int64) << 1)
  127. idxs1 = bit2 | (bit3.to(torch.int64) << 1)
  128. if dense.dtype != torch.float:
  129. sparse0 = dense_4.gather(
  130. -1, idxs0.unsqueeze(-1)) # type: ignore[possibly-undefined]
  131. sparse1 = dense_4.gather(-1, idxs1.unsqueeze(-1))
  132. sparse = torch.stack((sparse0, sparse1), dim=-1).view(m, k // 2)
  133. else:
  134. sparse = dense_2.gather(-1,
  135. idxs0.unsqueeze(-1) // 2).view(
  136. m,
  137. k // 2) # type: ignore[possibly-undefined]
  138. meta_4 = idxs0 | (idxs1 << 2)
  139. meta_n = meta_4.view(
  140. (-1, meta_ncols, quadbits_per_meta_elem)).to(meta_dtype)
  141. if quadbits_per_meta_elem == 4:
  142. meta = (meta_n[:, :, 0]
  143. | (meta_n[:, :, 1] << 4)
  144. | (meta_n[:, :, 2] << 8)
  145. | (meta_n[:, :, 3] << 12))
  146. elif quadbits_per_meta_elem == 8:
  147. meta = (meta_n[:, :, 0]
  148. | (meta_n[:, :, 1] << 4)
  149. | (meta_n[:, :, 2] << 8)
  150. | (meta_n[:, :, 3] << 12)
  151. | (meta_n[:, :, 4] << 16)
  152. | (meta_n[:, :, 5] << 20)
  153. | (meta_n[:, :, 6] << 24)
  154. | (meta_n[:, :, 7] << 28))
  155. # Reorder meta tensor elements.
  156. meta_reordered = meta.new_empty(
  157. (m * meta_ncols, )) # type: ignore[possibly-undefined]
  158. meta_offsets = _calculate_meta_reordering_scatter_offsets(
  159. m, meta_ncols, meta_dtype, device)
  160. meta_reordered.scatter_(0, meta_offsets, meta.view(-1))
  161. return (sparse, meta_reordered.view(m, meta_ncols))
  162. # This function performs reverse of the function above - it
  163. # reconstructs dense matrix from a pair of "compressed" matrix, given
  164. # in the layout used by CUTLASS backend, and accompanying metadata
  165. # matrix.
  166. def sparse_semi_structured_to_dense_cutlass(sparse, meta_reordered):
  167. if sparse.dim() != 2:
  168. raise RuntimeError(
  169. f"Expected 2-dimensional sparse tensor, got {sparse.dim()}-dimensional tensor" # noqa: E501
  170. )
  171. m, k = sparse.shape
  172. device = sparse.device
  173. if meta_reordered.dim() != 2:
  174. raise RuntimeError(
  175. f"Expected 2-dimensional meta tensor, got {meta_reordered.dim()}-dimensional tensor" # noqa: E501
  176. )
  177. if meta_reordered.device != device:
  178. raise RuntimeError(
  179. f"Expected meta matrix to be on {device} device, got matrix on {meta_reordered.device} device" # noqa: E501
  180. )
  181. meta_dtype = meta_reordered.dtype
  182. if meta_dtype not in (torch.int16, torch.int32):
  183. raise RuntimeError(f"Invalid datatype {meta_dtype} of meta matrix")
  184. quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4
  185. ksparse = 4 if sparse.dtype != torch.float else 2
  186. meta_nrows, meta_ncols = meta_reordered.shape
  187. if meta_nrows != m:
  188. raise RuntimeError(
  189. f"Number of rows of meta matrix {meta_nrows} must be equal to number of columns of spase matrix {m}" # noqa: E501
  190. )
  191. if meta_ncols * ksparse * quadbits_per_meta_elem != 2 * k:
  192. raise RuntimeError(
  193. f"Number of columns of sparse matrix {k} different from the {meta_ncols * ksparse * quadbits_per_meta_elem // 2}, " # noqa: E501
  194. "expected according to the number of columns of meta matrix")
  195. # Undo meta tensor elements reordering.
  196. meta_offsets = _calculate_meta_reordering_scatter_offsets(
  197. m, meta_ncols, meta_dtype, device)
  198. meta = torch.gather(meta_reordered.view(-1), 0,
  199. meta_offsets).view(m, meta_ncols)
  200. # Unpack sparse tensor back to original dense tensor, using
  201. # information provided by meta tensor. Note that torch.float
  202. # datatype is handled pretty much the same as
  203. # torch.half/torch.bfloat16, as metadata for a pair of torch.float
  204. # value is encoded as if underlying 8 bytes contain four
  205. # torch.half/torch.bfloat16 values, where either first two or last
  206. # two are zeros.
  207. meta_2 = torch.empty(
  208. (m, meta_ncols, 2 * quadbits_per_meta_elem),
  209. dtype=meta_dtype,
  210. device=device,
  211. )
  212. if quadbits_per_meta_elem == 4:
  213. meta_2[:, :, 0] = meta & 0b11
  214. meta_2[:, :, 1] = (meta >> 2) & 0b11
  215. meta_2[:, :, 2] = (meta >> 4) & 0b11
  216. meta_2[:, :, 3] = (meta >> 6) & 0b11
  217. meta_2[:, :, 4] = (meta >> 8) & 0b11
  218. meta_2[:, :, 5] = (meta >> 10) & 0b11
  219. meta_2[:, :, 6] = (meta >> 12) & 0b11
  220. meta_2[:, :, 7] = (meta >> 14) & 0b11
  221. elif quadbits_per_meta_elem == 8:
  222. meta_2[:, :, 0] = meta & 0b11
  223. meta_2[:, :, 1] = (meta >> 2) & 0b11
  224. meta_2[:, :, 2] = (meta >> 4) & 0b11
  225. meta_2[:, :, 3] = (meta >> 6) & 0b11
  226. meta_2[:, :, 4] = (meta >> 8) & 0b11
  227. meta_2[:, :, 5] = (meta >> 10) & 0b11
  228. meta_2[:, :, 6] = (meta >> 12) & 0b11
  229. meta_2[:, :, 7] = (meta >> 14) & 0b11
  230. meta_2[:, :, 8] = (meta >> 16) & 0b11
  231. meta_2[:, :, 9] = (meta >> 18) & 0b11
  232. meta_2[:, :, 10] = (meta >> 20) & 0b11
  233. meta_2[:, :, 11] = (meta >> 22) & 0b11
  234. meta_2[:, :, 12] = (meta >> 24) & 0b11
  235. meta_2[:, :, 13] = (meta >> 26) & 0b11
  236. meta_2[:, :, 14] = (meta >> 28) & 0b11
  237. meta_2[:, :, 15] = (meta >> 30) & 0b11
  238. dense_offsets = meta_2.view(-1) + (
  239. torch.arange(0, 2 * m * k // ksparse, device=device) * 4).view(
  240. -1, 1).repeat(1, 2).view(-1)
  241. dense = torch.zeros((m * 2 * k, ), dtype=sparse.dtype, device=device)
  242. if sparse.dtype != torch.float:
  243. # dense.scatter_(0, dense_offsets, sparse.view(-1))
  244. dense.scatter_(0, dense_offsets, sparse.reshape(-1))
  245. else:
  246. dense.view(torch.half).scatter_(0, dense_offsets,
  247. sparse.view(torch.half).view(-1))
  248. return dense.view(m, 2 * k)
  249. def mask_creator(tensor):
  250. """
  251. Class for creating N:M sparsity masks.
  252. Masks will be created using the N:M ratio, where for every block of
  253. M weights, N will be pruned based on ranked weight value. Each mask
  254. will correspond to the given tensor.
  255. :param N: The number of weights in a group to keep
  256. :param M: The size of a weight group
  257. """
  258. N = 2
  259. M = 4
  260. mask = None
  261. # for i, tensor in enumerate(tensors):
  262. if tensor.numel() % M != 0:
  263. raise ValueError(
  264. f"Tensor of size {tensor.shape} can't be evenly divided into "
  265. f"{M} groups")
  266. num_groups = tensor.numel() // M
  267. # N:M sparsity for linear layers
  268. tensor_temp = tensor.detach().abs().reshape(num_groups, M)
  269. index = torch.argsort(tensor_temp, dim=1)[:, :int(M - N)]
  270. w_b = torch.ones(tensor_temp.shape, device=tensor_temp.device)
  271. mask = w_b.scatter_(dim=1, index=index, value=0).reshape(tensor.shape)
  272. return mask
  273. def inject_24(w, size_k, size_n):
  274. assert w.shape == (size_k, size_n)
  275. mask = mask_creator(w.t()).t().cuda().bool()
  276. return (mask * w).contiguous(), mask.contiguous()
  277. def check_24(w, num_rows_to_sample=50, _verbose=False):
  278. BLOCK_SIZE = 4
  279. MAX_NON_ZEROS = 2
  280. w = w.t().contiguous()
  281. print("check_24: w.shape = {}".format(w.shape))
  282. num_rows, num_cols = w.shape
  283. sampled_row_idxs = random.choices(range(num_rows), k=num_rows_to_sample)
  284. if _verbose:
  285. print(f"Sampled row idxs = {sampled_row_idxs}")
  286. total_segments = 0
  287. non_24_segments = 0
  288. for i in sampled_row_idxs:
  289. for j in range(0, num_cols - BLOCK_SIZE, BLOCK_SIZE):
  290. total_segments += 1
  291. block = w[i, j:j + BLOCK_SIZE]
  292. num_nonzero = torch.count_nonzero(block)
  293. if num_nonzero > MAX_NON_ZEROS:
  294. print("i = {} j = {} block = {}".format(i, j, block))
  295. non_24_segments += 1
  296. print(f"{non_24_segments} / {total_segments} do not have 2:4 structure.")
  297. def compress_quantized_24_weight(q_24, size_k, size_n, wtype: ScalarType):
  298. assert q_24.shape == (size_k, size_n)
  299. # Remove bias to normalize over 0
  300. q_24_no_zp = q_24 - wtype.bias
  301. # Compress
  302. q_24_no_zp = q_24_no_zp.t().contiguous()
  303. q_24_no_zp_comp, meta = sparse_semi_structured_from_dense_cutlass(
  304. q_24_no_zp)
  305. q_24_no_zp_comp = q_24_no_zp_comp.t().contiguous()
  306. # Restore bias
  307. q_24_comp = q_24_no_zp_comp + wtype.bias
  308. # Resize meta to its actual shape (without moving any data)
  309. meta = meta.resize_(meta.shape[1] // 2, meta.shape[0] * 2)
  310. return q_24_comp, meta
  311. def get_scale_perms_24():
  312. scale_perm: List[int] = []
  313. for i in range(8):
  314. scale_perm.extend([i * 8 + j for j in [0, 4, 1, 5, 2, 6, 3, 7]])
  315. scale_perm_single: List[int] = []
  316. for i in range(8):
  317. scale_perm_single.extend([8 * i + j for j in [0, 1, 2, 3, 4, 5, 6, 7]])
  318. return scale_perm, scale_perm_single
  319. def get_weight_perm_24(num_bits: int):
  320. perm_list: List[int] = []
  321. for i in range(32):
  322. perm1: List[int] = []
  323. col = i // 4
  324. col_o = col // 2
  325. for block in [0, 1]:
  326. for row in [
  327. 2 * (i % 4),
  328. 2 * (i % 4) + 1,
  329. 2 * (i % 4 + 4),
  330. 2 * (i % 4 + 4) + 1,
  331. ]:
  332. perm1.append(16 * row + col_o * 256 + 8 * (col % 2) +
  333. 4 * block)
  334. for j in range(4):
  335. perm_list.extend([p + 1 * j for p in perm1])
  336. perm = numpy.array(perm_list)
  337. if num_bits == 4:
  338. interleave = numpy.array([0, 2, 4, 6, 1, 3, 5, 7])
  339. elif num_bits == 8:
  340. interleave = numpy.array([0, 2, 1, 3])
  341. else:
  342. raise ValueError("num_bits must be 4 or 8, got {}".format(num_bits))
  343. perm = perm.reshape((-1, len(interleave)))[:, interleave].ravel()
  344. perm = torch.from_numpy(perm)
  345. return perm
  346. def marlin_permute_scales_24(s: torch.Tensor, size_k: int, size_n: int,
  347. group_size: int) -> torch.Tensor:
  348. scale_perm, scale_perm_single = get_scale_perms_24()
  349. if group_size < size_k and group_size != -1:
  350. s = s.reshape((-1, len(scale_perm)))[:, scale_perm]
  351. else:
  352. s = s.reshape((-1, len(scale_perm_single)))[:, scale_perm_single]
  353. s = s.reshape((-1, size_n)).contiguous()
  354. return s
  355. def marlin_24_quantize(
  356. w: torch.Tensor,
  357. quant_type: ScalarType,
  358. group_size: int,
  359. ):
  360. size_k, size_n = w.shape
  361. # Normalize group_size
  362. if group_size == -1:
  363. group_size = size_k
  364. assert group_size <= size_k
  365. # Inject 2:4 sparsity
  366. w_24, mask_24 = inject_24(w, size_k, size_n)
  367. # Quantize
  368. w_24_ref, q_w_24, s, g_idx, rand_perm = gptq_quantize_weights(
  369. w_24, quant_type, group_size, act_order=False)
  370. # Compress quantized weight
  371. q_w_24_comp, meta = compress_quantized_24_weight(q_w_24, size_k, size_n,
  372. quant_type)
  373. size_k_comp = size_k // 2
  374. # Reformat to marlin
  375. weight_perm = get_weight_perm_24(quant_type.size_bits)
  376. marlin_24_q_w_comp = marlin_weights(q_w_24_comp, size_k_comp, size_n,
  377. quant_type.size_bits, weight_perm)
  378. marlin_24_s = marlin_permute_scales_24(s, size_k, size_n, group_size)
  379. # Create result
  380. res_list = [w_24_ref, marlin_24_q_w_comp, meta, marlin_24_s]
  381. for i in range(len(res_list)):
  382. res_list[i] = res_list[i].to(w.device)
  383. return res_list