Run a matrix-vector product on packed 4-bit weights with zero points

MediumQuantizationPro

Why it matters Weight-only 4-bit inference kernels do this unpack and dequantize inside the matmul, which is why 4-bit models decode fast on memory-bound GPUs.

4-bit weights are stored two per byte, with one scale and one zero point per group of input columns. A gemv kernel unpacks, dequantizes and multiplies on the fly.

Write int4_gemv(packed, scales, zeros, x, group). packed is a uint8 array of shape (N, K // 2): byte j of a row holds column 2j in its low 4 bits and column 2j + 1 in its high 4 bits. scales and zeros have shape (N, K // group); zeros are integers in [0, 15]. The weight is w[n, k] = (q[n, k] - zeros[n, k // group]) * scales[n, k // group]. x has length K. Return y = W x as a float array of length N.

Signaturedef int4_gemv(packed, scales, zeros, x, group)

Example

packed [[0x21, 0x43]] (codes 1, 2, 3, 4), scales [[0.5]], zeros [[2]], x [1, 1, 1, 1], group 4 gives [1.0].

Understand the idea

Packing two 4-bit numbers into one byte is like writing two single-digit numbers in one two-digit box: the right digit is one value, the left digit is the other. In binary, the low 4 bits are byte & 15 and the high 4 bits are byte >> 4. Worked example: byte 0x21 is 33. Low nibble 1 is column 0, high nibble 2 is column 1. With zero point 2 and scale 0.5, codes 1, 2, 3, 4 become -0.5, 0, 0.5, 1.0, and the sum with x of ones is 1.0. Rule: w = (q - z[group]) x s[group], y = sum_k w[k] x[k]. Real kernels never build the full float matrix: they unpack a few bytes into registers, dequantize and multiply, so memory traffic stays at 4 bits per weight.

Shapes and data flow

packed (N, K/2) -> q (N, K)  scales, zeros (N, K/group) -> broadcast (N, K)  y = W @ x (N,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleint4_gemv([[0x21, 0x43]], [[0.5]], [[2]], [1, 1, 1, 1], 4)
  • Sample 2: two groupsint4_gemv([[0x0F, 0x88], [0x10, 0xFF]], [[0.1, 1.0], [2.0, 0.5]], [[8, 8], [0, 15]], [1, 2, 3, 4], 2)