Skip to content
Inference Academy

A 4-bit weight-only matmul (W4A16) in Triton

Write the kernel behind 4-bit quantised decode: weights stored as packed 4-bit integers with group-wise scales, dequantised in registers inside the matmul loop so they cross memory at a quarter of their float16 size. Covers the quantisation format, the packing layout and why it decides the kernel, small tiles for decode batch sizes, when weight-only quantisation stops paying (prefill), and how production kernels such as Marlin go further.

By

Key takeaways

  • At decode batch sizes a linear layer is bound by reading its weights, so storing them in 4 bits makes it up to about four times faster, if the kernel never writes the dequantised weights to memory.
  • Dequantise inside the K loop, in registers, right before the dot product. Dequantising the whole matrix first throws the saving away.
  • The packing layout decides the kernel. Packing two values per byte along N lets one load feed two dot products, one for even and one for odd columns.
  • Group-wise scales (one per 128 values of K) keep the error low; a K block must not straddle two groups.
  • At prefill sizes the matmul becomes compute bound and the dequantisation becomes overhead, so weight-only kernels can be slower than float16.
28 min · verified 2026-111 animated diagramHands-on labPro
Share

Goal: write a matmul that reads 4-bit weights and float16 activations, understand why it speeds up decode, and know where it stops helping.

You need: the Triton matmul lesson and quantisation in depth. The code is in gpu_kernels/w4a16_matmul.py in the companion repository, with tests in tests/test_gpu_kernels.py.

Honest limits. This is a teaching kernel, tested for correctness in the Triton interpreter on a CPU. Its format is a simplified symmetric scheme; real GPTQ and AWQ checkpoints add zero points, other packing orders and sometimes reordered rows, so you cannot load them with this kernel unchanged. Production kernels (Marlin and its successors in vLLM) reorder weights offline for the tensor-core layout and reach far closer to peak bandwidth.

#Why weight-only quantisation speeds up decode

At decode, a linear layer multiplies a few rows of activations (the batch, often 1 to 64) by a large weight matrix. Every weight is read once per step and used for only a few multiply-adds, so the time is the weight bytes divided by memory bandwidth. Store the weights in 4 bits and read a quarter of the bytes:

4096 × 11008 layer Bytes read Time at 320 GB/s (T4)
float16 weights 90.2 MB 0.28 ms
4-bit weights + float16 scales (group 128) 22.5 + 0.7 MB 0.073 ms

This only works if the 4-bit values are turned back into numbers in registers, right before they are used. Dequantising the whole matrix to float16 in memory first, then running a normal matmul, reads the 4-bit weights, writes 90 MB and reads 90 MB again: slower than not quantising at all. That is what the "eager" baseline in the benchmark harness does, on purpose.

#The format

Symmetric, group-wise along K: for each column and each group of 128 consecutive rows of K, one scale.

s=max⁡∣w∣7,q=clamp⁡(round⁡(w/s),−8,7),w^=q⋅ss = \frac{\max |w|}{7}, \qquad q = \operatorname{clamp}\left(\operatorname{round}(w / s), -8, 7\right), \qquad \hat w = q \cdot s

Stored as q+8q + 8, an unsigned value from 0 to 15. Rounding to the nearest step means the error is at most half a step, s/2s/2, which the first test checks. Smaller groups lower the error and add scale bytes; 128 is the usual compromise.

From float weights to packed 4-bit bytes and back
Animated
0.42-0.110.07-0.63
-0.250.31-0.020.55
0.18-0.470.29-0.08
-0.360.05-0.510.21

A 4 × 4 block of float weights

Rows are K (four rows of one quantisation group, which is 128 rows in the lesson), columns are N. Each weight is 16 bits.

Symmetric, group-wise along K, packed along N: the same format as the lesson's kernel, on a 4 × 4 block.

#The packing decides the kernel

Two 4-bit values fit in a byte, but which two is a design choice with consequences for the kernel:

  • Along K (rows kk and k+1k+1 of one column in a byte): natural for the dot product's K loop, but unpacking gives two half-tiles that must be interleaved back into one K tile before the dot.
  • Along N (columns 2j2j and 2j+12j+1 of one row in a byte): unpacking gives an even-column tile and an odd-column tile, each a full K tile. Each can go straight into its own dot product with the same activation tile.

This kernel packs along N. packed is [K, N/2] bytes; the low nibble is column 2j2j, the high nibble column 2j+12j+1.

gpu_kernels/w4a16_matmul.py · MIT licensed, on GitHub

python
"""Weight-only 4-bit matmul (W4A16) in Triton: y = x @ dequant(W).

Quantisation (symmetric, group-wise along K, as in GPTQ/AWQ-style formats without zero points):
  for each column n and each group of GROUP rows of K: scale = max|w| / 7,
  q = clamp(round(w / scale), -8, 7), stored as q + 8 in 4 bits.
Packing: two 4-bit values per byte along N. packed[k, j] holds column 2j in the low nibble
and column 2j + 1 in the high nibble, so packed is [K, N/2] uint8 and scales is [K/GROUP, N].

The kernel loads packed bytes, splits them into the even and odd columns, dequantises in
registers and runs two tensor-core dots per K step. Weights cross memory as 4 bits each,
which is the whole point for decode, where the matmul is bound by reading the weights.

Runs on a GPU, or on a CPU with TRITON_INTERPRET=1 set before importing triton.
"""
import torch
import triton
import triton.language as tl


def quantise_w4(w, group=128):
    """w: [K, N] float. Returns packed [K, N/2] uint8 and scales [K/group, N] float16."""
    K, N = w.shape
    assert K % group == 0 and N % 2 == 0
    wg = w.float().reshape(K // group, group, N)
    scales = (wg.abs().amax(dim=1) / 7.0).clamp(min=1e-8)              # [K/group, N]
    q = torch.clamp(torch.round(wg / scales[:, None, :]), -8, 7).to(torch.int16) + 8
    q = q.reshape(K, N).to(torch.uint8)
    packed = q[:, 0::2] | (q[:, 1::2] << 4)
    return packed.contiguous(), scales.to(torch.float16)


def dequantise_w4(packed, scales, group=128):
    lo = (packed & 0xF).to(torch.int16) - 8
    hi = (packed >> 4).to(torch.int16) - 8
    K = packed.shape[0]
    q = torch.stack([lo, hi], dim=-1).reshape(K, -1).float()             # [K, N], columns interleaved back
    return q * scales.float().repeat_interleave(group, dim=0)


def w4a16_reference(x, packed, scales, group=128):
    return (x.float() @ dequantise_w4(packed, scales, group)).to(x.dtype)


@triton.jit
def _w4a16_kernel(x_ptr, p_ptr, s_ptr, y_ptr, M, N, K,
                  stride_xm, stride_pk, stride_sk, stride_ym,
                  GROUP: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
                  BLOCK_K: tl.constexpr):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    HALF_N: tl.constexpr = BLOCK_N // 2

    rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    rj = pid_n * HALF_N + tl.arange(0, HALF_N)          # packed column index: covers columns 2j, 2j+1
    rk = tl.arange(0, BLOCK_K)

    acc_even = tl.zeros((BLOCK_M, HALF_N), dtype=tl.float32)
    acc_odd = tl.zeros((BLOCK_M, HALF_N), dtype=tl.float32)

    for k0 in range(0, K, BLOCK_K):
        kk = k0 + rk
        x = tl.load(x_ptr + rm[:, None] * stride_xm + kk[None, :],
                    mask=(rm[:, None] < M) & (kk[None, :] < K), other=0.0)
        p = tl.load(p_ptr + kk[:, None] * stride_pk + rj[None, :],
                    mask=(kk[:, None] < K) & (rj[None, :] < N // 2), other=0)
        # One scale row per group; BLOCK_K divides GROUP, so the whole K block shares it.
        g = k0 // GROUP
        s_even = tl.load(s_ptr + g * stride_sk + 2 * rj, mask=rj < N // 2, other=0.0)
        s_odd = tl.load(s_ptr + g * stride_sk + 2 * rj + 1, mask=rj < N // 2, other=0.0)

        w_even = ((p & 0xF).to(tl.int32) - 8).to(tl.float16) * s_even[None, :]
        w_odd = ((p >> 4).to(tl.int32) - 8).to(tl.float16) * s_odd[None, :]
        acc_even += tl.dot(x.to(tl.float16), w_even.to(tl.float16))
        acc_odd += tl.dot(x.to(tl.float16), w_odd.to(tl.float16))

    out_dtype = y_ptr.dtype.element_ty
    mask = (rm[:, None] < M) & (rj[None, :] < N // 2)
    tl.store(y_ptr + rm[:, None] * stride_ym + 2 * rj[None, :], acc_even.to(out_dtype), mask=mask)
    tl.store(y_ptr + rm[:, None] * stride_ym + 2 * rj[None, :] + 1, acc_odd.to(out_dtype), mask=mask)


def w4a16_matmul(x, packed, scales, group=128, block_m=16, block_n=64, block_k=64):
    """x: [M, K] float16. Small block_m suits decode (M is the batch size, often 1 to 64)."""
    M, K = x.shape
    N = packed.shape[1] * 2
    assert packed.shape[0] == K and group % block_k == 0
    x = x.contiguous()
    y = torch.empty((M, N), dtype=x.dtype, device=x.device)
    grid = (triton.cdiv(M, block_m), triton.cdiv(N, block_n))
    _w4a16_kernel[grid](x, packed, scales, y, M, N, K,
                        x.stride(0), packed.stride(0), scales.stride(0), y.stride(0),
                        GROUP=group, BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k)
    return y

The rest is Pro

Keep reading this full lab

Pro unlocks this full lab, every advanced lesson, the hands-on labs and completion certificates.

One year

$25

365 days, no auto-renewal

Lifetime Best value

$75

pay once, keep it forever

7-day refund, no questions asked. One payment, no auto-renewal.Compare plansHave a licence key?

Sandip MaityBuilt by Sandip Maity, who runs self-hosted LLM inference in production.

Not ready? Keep learning free

Or follow the free roadmap →

Not ready? Take the free 5-day email course

One short email a day for five days, each built on a free lesson, then the occasional new lesson or offer. Unsubscribe in one click.

Still to come in this lab

  1. Walking through the kernel
  2. Testing
  3. When it stops paying
  4. How production kernels go further
  5. What you can now do
  6. Common mistakes
  7. Exercise
  8. Going deeper

You will be able to answer

  • A 4096 by 11008 linear layer in float16 holds about 90 MB of weights. Roughly how many bytes does a W4A16 kernel read for it with group size 128?
  • Why does the kernel run two dot products per K step?
  • At a batch of 4,096 tokens (prefill), the W4A16 kernel is slower than a float16 matmul. Why?