llm-decode-kernels

W4A16 matmul

Decode multiplies a few activation rows by every weight matrix in the model, so it is limited by how fast the weights stream from DRAM. Storing weights as 4-bit integers (8 per int32, fp16 scale and zero per group of 128) cuts those bytes ~3.6x. The kernel dequantizes in registers and feeds tensor cores. For decode, split-K spreads one small matmul over the whole GPU. A CUDA C++ version of the decode case is compared side by side.

Triton kernel

kernels/w4a16.py: _w4a16_kernel (67 lines, click to show)
@triton.jit
def _w4a16_kernel(
    a_ptr, q_ptr, s_ptr, z_ptr, bias_ptr, c_ptr,
    M, N, K,
    stride_am, stride_ak, stride_qk, stride_qn, stride_sg, stride_sn, stride_cm, stride_cn,
    M_KEY,  # only used as an autotune key (M rounded up to a power of 2)
    GROUP_SIZE: tl.constexpr,
    HAS_BIAS: tl.constexpr,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
    SPLIT_K: tl.constexpr, GROUP_M: tl.constexpr,
):
    # Grouped tile order so neighbouring programs share A rows / B columns in L2 (prefill).
    pid = tl.program_id(0)
    pid_k = tl.program_id(1)
    num_pid_m = tl.cdiv(M, BLOCK_M)
    num_pid_n = tl.cdiv(N, BLOCK_N)
    group_id = pid // (GROUP_M * num_pid_n)
    first_m = group_id * GROUP_M
    group_rows = min(num_pid_m - first_m, GROUP_M)
    pid_m = first_m + (pid % group_rows)
    pid_n = (pid % (GROUP_M * num_pid_n)) // group_rows

    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_m = offs_m < M
    mask_n = offs_n < N
    offs_pk = tl.arange(0, BLOCK_K // 8)  # packed rows in one K tile
    shifts = (tl.arange(0, 8) * 4)[None, :, None]

    # This program's K range, aligned to BLOCK_K (BLOCK_K divides GROUP_SIZE divides K).
    k_tiles = K // BLOCK_K
    tiles_per_split = tl.cdiv(k_tiles, SPLIT_K)
    t_start = pid_k * tiles_per_split
    t_end = min(t_start + tiles_per_split, k_tiles)

    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
    for t in range(t_start, t_end):
        k0 = t * BLOCK_K
        offs_k = k0 + tl.arange(0, BLOCK_K)
        a = tl.load(
            a_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak,
            mask=mask_m[:, None], other=0.0,
        )
        packed = tl.load(
            q_ptr + (k0 // 8 + offs_pk)[:, None] * stride_qk + offs_n[None, :] * stride_qn,
            mask=mask_n[None, :], other=0,
        )
        # [BK/8, BN] int32 -> [BK/8, 8, BN] nibbles -> [BK, BN], row k = 8 * packed_row + i
        q = (packed[:, None, :] >> shifts) & 0xF
        q = tl.reshape(q, (BLOCK_K, BLOCK_N))
        g = k0 // GROUP_SIZE
        s = tl.load(s_ptr + g * stride_sg + offs_n * stride_sn, mask=mask_n, other=0.0)
        z = tl.load(z_ptr + g * stride_sg + offs_n * stride_sn, mask=mask_n, other=0.0)
        b = (q.to(tl.float16) - z[None, :]) * s[None, :]
        acc = tl.dot(a, b, acc)

    if HAS_BIAS:
        if pid_k == 0:
            bias = tl.load(bias_ptr + offs_n, mask=mask_n, other=0.0)
            acc += bias.to(tl.float32)[None, :]

    c_ptrs = c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn
    c_mask = mask_m[:, None] & mask_n[None, :]
    if SPLIT_K == 1:
        tl.store(c_ptrs, acc.to(c_ptr.dtype.element_ty), mask=c_mask)
    else:
        tl.atomic_add(c_ptrs, acc, mask=c_mask, sem="relaxed")

CUDA C++ decode kernel (inner loop)

kernels/cuda/w4a16_decode.cu: w4a16_decode_kernel (70 lines, click to show)
__global__ void __launch_bounds__(kThreads) w4a16_decode_kernel(
    const half* __restrict__ x, const int* __restrict__ qweight, const half* __restrict__ scales,
    const half* __restrict__ zeros, const half* __restrict__ bias, half* __restrict__ out_f16,
    float* __restrict__ out_f32, int M, int N, int K, int group_size, int k_per_split) {
  __shared__ float xs[MT][kTileK];
  __shared__ float xsum8[MT][kTileK / 8];  // sum of each run of 8 activations (one packed row)
  __shared__ float red[MT][kColsPerBlock];

  const int lane = threadIdx.x % 32;
  const int warp = threadIdx.x / 32;
  const int n0 = blockIdx.x * kColsPerBlock + lane * kColsPerThread;
  const bool cols_ok = n0 < N;  // host checks N % 4 == 0, so a lane's 4 columns are all in or out
  const int k_begin = blockIdx.y * k_per_split;
  const int k_end = min(k_begin + k_per_split, K);

  for (int i = threadIdx.x; i < MT * kColsPerBlock; i += kThreads) (&red[0][0])[i] = 0.f;

  float acc[MT][kColsPerThread];
#pragma unroll
  for (int m = 0; m < MT; ++m)
#pragma unroll
    for (int c = 0; c < kColsPerThread; ++c) acc[m][c] = 0.f;

  for (int kt = k_begin; kt < k_end; kt += kTileK) {
    const int klen = min(kTileK, k_end - kt);  // multiple of 8
    __syncthreads();
    for (int i = threadIdx.x; i < MT * kTileK; i += kThreads) {
      const int m = i / kTileK, k = i % kTileK;
      xs[m][k] = (m < M && k < klen) ? __half2float(x[(size_t)m * K + kt + k]) : 0.f;
    }
    __syncthreads();
    for (int i = threadIdx.x; i < MT * (kTileK / 8); i += kThreads) {
      const int m = i / (kTileK / 8), r = i % (kTileK / 8);
      float sum = 0.f;
#pragma unroll
      for (int j = 0; j < 8; ++j) sum += xs[m][r * 8 + j];
      xsum8[m][r] = sum;
    }
    __syncthreads();
    if (!cols_ok) continue;

    for (int r = warp; r < klen / 8; r += kWarps) {
      const int krow = kt / 8 + r;
      const int4 q = *reinterpret_cast<const int4*>(qweight + (size_t)krow * N + n0);
      const int g = (kt + r * 8) / group_size;
      const uint2 s2 = *reinterpret_cast<const uint2*>(scales + (size_t)g * N + n0);
      const uint2 z2 = *reinterpret_cast<const uint2*>(zeros + (size_t)g * N + n0);
      const half* sh = reinterpret_cast<const half*>(&s2);
      const half* zh = reinterpret_cast<const half*>(&z2);
      const int qs[kColsPerThread] = {q.x, q.y, q.z, q.w};

#pragma unroll
      for (int c = 0; c < kColsPerThread; ++c) {
        const float s = __half2float(sh[c]);
        const float z = __half2float(zh[c]);
        float xq[MT];
#pragma unroll
        for (int m = 0; m < MT; ++m) xq[m] = 0.f;
#pragma unroll
        for (int i = 0; i < 8; ++i) {
          const float qv = static_cast<float>((qs[c] >> (4 * i)) & 0xF);
#pragma unroll
          for (int m = 0; m < MT; ++m) xq[m] += qv * xs[m][r * 8 + i];
        }
#pragma unroll
        for (int m = 0; m < MT; ++m) acc[m][c] += s * (xq[m] - z * xsum8[m][r]);
      }
    }
  }

Triton or CUDA?

Both kernels compute the same thing on the same weight format (int4 packed 8 per int32, fp16 scale and zero per group of 128), use the same factored dequantization, and pass the same tests. Numbers are from the final L4 runs (CUDA-graph timing, median of 3 sweeps); H100 numbers are on the site.

Speed. At batch 1 the Triton GEMV path reaches a median of 77% of peak bandwidth across six layer shapes, against 70% for the CUDA kernel (82% vs 74% on Qwen's gate_up layer). That was not true in the first round: the CUDA kernel led at batch 1 until both kernels got the factored dequantization and the Triton path picker stopped timing in eager mode (see DECISIONS). At batch 16 the gap is large: Triton holds 62% while CUDA drops to 29%. The CUDA kernel does its multiply-adds on CUDA cores, so 16 rows mean 16 times the arithmetic per weight and it becomes compute-bound; Triton switches to its tl.dot path on tensor cores. In the full model at batch 1: 118.2 tokens/s with Triton, 114.4 with the CUDA decode kernel. On the H100 the ranking is the same and the gap wider (batch 1: 25% vs 17% of peak, median; Qwen2.5 decode 398 vs 339 tokens/s): there, unpacking work rather than memory limits both kernels, and the CUDA kernel does more of it per byte.

Code. The Triton GEMM kernel is 58 lines and the batch-1 GEMV kernel 48. The CUDA kernel is 85 lines plus a 52-line host launcher with manual shape checks, alignment rules (N must be a multiple of 4 for 16-byte loads) and template dispatch on the batch size (scripts/loc.py). Triton's autotuner picked tile sizes, warps, pipeline depth, split-K and the dequant variant for every shape; for CUDA we tuned only split-K and hand-picked the rest. The Triton GEMM also covers prefill (batch 2048), which the CUDA kernel does not do at all.

When each is worth it. - Triton first: one kernel family for decode and prefill, autotuning for free, tensor cores without writing MMA code, and quick to iterate on. Here it ended up faster at every shape we measured. - CUDA C++ when you need control Triton does not give you: exact register tiling, vector widths, warp-level tricks, or a layout Triton cannot express. Our CUDA kernel would need a hand-written tensor-core (MMA) path to compete at batch 16, which is much more code. The CUDA version was still worth writing: an independent second implementation to check the numbers against, and for a while the faster one at batch 1, which is what pushed the Triton kernel to improve.

L4

speedup
roofline
triton vs cuda
shapetriton (us)cuda (us)fp16 (us)torchao (us)compile (us)naive (us)speedup vs fp16triton % peak bw
layer=qwen_qkv, M=110.311.926.412.736.3196.12.55x54%
layer=qwen_qkv, M=213.613.326.513.738.7200.91.95x41%
layer=qwen_qkv, M=413.816.026.614.039.1201.31.93x41%
layer=qwen_qkv, M=814.221.726.915.339.6201.41.89x41%
layer=qwen_qkv, M=1614.834.027.421.440.9202.61.85x40%
layer=qwen_o, M=18.910.121.310.18.5138.12.39x47%
layer=qwen_o, M=211.311.320.511.324.1144.71.82x37%
layer=qwen_o, M=411.413.720.611.527.2145.01.82x38%
layer=qwen_o, M=811.718.720.812.125.9145.61.78x37%
layer=qwen_o, M=1613.029.321.216.925.9150.41.64x35%
layer=qwen_gate_up, M=159.965.7207.878.582.64662.93.47x82%
layer=qwen_gate_up, M=273.769.1221.280.2461.64698.73.00x66%
layer=qwen_gate_up, M=470.877.1222.281.0464.94700.53.14x70%
layer=qwen_gate_up, M=874.3110.6223.791.7465.64699.63.01x67%
layer=qwen_gate_up, M=1679.2164.9226.5141.5443.34718.62.86x64%
layer=qwen_down, M=133.637.6102.834.144.32126.63.06x73%
layer=qwen_down, M=239.339.9109.134.7158.82136.22.77x62%
layer=qwen_down, M=439.945.5109.435.8195.92151.02.74x62%
layer=qwen_down, M=840.861.1109.841.2199.42150.12.69x61%
layer=qwen_down, M=1642.195.7111.281.9167.42141.22.64x61%
layer=8b_up, M=1123.9131.7429.9123.3144.210081.93.47x84%
layer=8b_up, M=2149.3136.1459.4124.01156.410203.13.08x70%
layer=8b_up, M=4154.0158.5454.3125.81139.710202.62.95x68%
layer=8b_up, M=8156.3207.1458.0161.21143.510209.02.93x67%
layer=8b_up, M=16160.9313.9464.4282.41152.510214.72.89x66%
layer=8b_down, M=1126.5131.1427.5129.6141.110111.73.38x82%
layer=8b_down, M=2142.6136.7450.8128.31125.110216.93.16x73%
layer=8b_down, M=4151.7157.6451.3135.41130.110220.02.98x69%
layer=8b_down, M=8155.4215.2452.8165.51135.910219.82.91x68%
layer=8b_down, M=16162.0329.5455.8291.31144.510222.22.81x65%
layer=qwen_qkv, M=12837.7-35.7110.554.1217.70.95x23%
layer=qwen_qkv, M=512103.4-93.2422.5112.1275.10.90x17%
layer=qwen_qkv, M=2048357.5-314.91661.8321.1486.30.88x15%
layer=qwen_o, M=12827.5-26.985.637.9159.30.98x25%
layer=qwen_o, M=51270.9-59.0326.867.3183.70.83x21%
layer=qwen_o, M=2048242.5-243.21277.8244.1357.31.00x19%
layer=qwen_gate_up, M=128223.8-300.4895.5569.34770.61.34x29%
layer=qwen_gate_up, M=512638.4-617.33516.4917.64913.30.97x18%
layer=qwen_gate_up, M=20482485.1-2083.714076.12372.46131.30.84x13%
layer=qwen_down, M=128144.2-146.8486.5213.22177.11.02x23%
layer=qwen_down, M=512389.6-316.51891.2410.92308.80.81x15%
layer=qwen_down, M=20481320.1-1284.17906.21435.32996.30.97x13%
layer=8b_up, M=128356.4-531.41806.91176.910299.11.49x34%
layer=8b_up, M=5121272.5-1337.77028.92045.110552.31.05x13%
layer=8b_up, M=20485025.5-4472.128082.25152.912973.10.89x7%
layer=8b_down, M=128541.5-567.81878.41264.810319.41.05x22%
layer=8b_down, M=5121714.5-1290.07467.32015.210581.60.75x10%
layer=8b_down, M=20485348.8-4674.929777.95393.913124.10.87x7%

Profile on L4

launchtime (ns)DRAM % peakSM % peakoccupancy %regs/thread
w4a16_triton_gate_up_M15990492.7418.3119.9161
w4a16_cuda_gate_up_M16057690.8432.9878.2848
w4a16_cuda_gate_up_M1240011.900.287.9630
w4a16_triton_gate_up_M166156890.3042.2139.4971
w4a16_cuda_gate_up_M1612905643.7445.4019.80152
w4a16_triton_down_M13104088.8320.0626.6664
w4a16_triton_down_M121121.990.078.2730
w4a16_cuda_down_M13388880.5528.6327.3848
w4a16_cuda_down_M121761.960.068.2730
w4a16_triton_down_M163462483.7836.8626.7571
w4a16_triton_down_M16243215.680.348.0830
w4a16_cuda_down_M168099236.4436.6913.75152
w4a16_cuda_down_M16262414.480.318.0730

Power on L4

Sustained decode matmuls hold the card at its power cap (reason 0x4 = software power cap) and the SM clock drops well below its maximum. That is why sustained numbers sit below single-launch Nsight Compute numbers, and why cutting ALU work in the dequantization (the factored GEMV) raised bandwidth.

kernel (gate_up, M=1)us per callSM clock (MHz)power (W)throttle reasons
triton60.3132872 / 720x0000000000000004
cuda66.6120072 / 720x0000000000000004
fp16209.0132872 / 720x0000000000000004

H100

speedup
roofline
triton vs cuda
shapetriton (us)cuda (us)fp16 (us)torchao (us)compile (us)naive (us)speedup vs fp16triton % peak bw
layer=qwen_qkv, M=16.68.45.47.45.065.60.82x8%
layer=qwen_qkv, M=27.39.55.58.110.565.60.75x7%
layer=qwen_qkv, M=47.411.75.58.410.665.60.74x7%
layer=qwen_qkv, M=87.416.65.59.210.565.70.74x7%
layer=qwen_qkv, M=167.626.85.611.710.665.40.73x7%
layer=qwen_o, M=16.68.25.27.35.054.00.78x6%
layer=qwen_o, M=27.19.45.28.09.454.20.73x5%
layer=qwen_o, M=47.111.65.28.39.454.20.73x5%
layer=qwen_o, M=87.216.65.29.19.454.20.72x5%
layer=qwen_o, M=167.326.75.211.79.454.30.72x6%
layer=qwen_gate_up, M=112.718.623.016.321.2534.31.80x34%
layer=qwen_gate_up, M=219.822.823.117.461.6534.51.17x22%
layer=qwen_gate_up, M=420.029.223.320.761.6533.31.16x22%
layer=qwen_gate_up, M=820.349.523.530.161.6534.51.16x22%
layer=qwen_gate_up, M=1620.475.823.846.661.7534.41.16x22%
layer=qwen_down, M=114.721.414.412.410.8279.80.98x15%
layer=qwen_down, M=214.723.114.513.443.2279.20.99x15%
layer=qwen_down, M=414.726.514.514.343.2279.20.99x15%
layer=qwen_down, M=814.735.314.719.043.3279.71.00x15%
layer=qwen_down, M=1614.854.114.928.043.6279.01.00x15%
layer=8b_up, M=120.830.442.420.333.51098.42.04x45%
layer=8b_up, M=232.036.442.421.1125.71098.31.33x29%
layer=8b_up, M=432.148.642.527.0125.71098.21.33x29%
layer=8b_up, M=832.473.342.642.5125.91098.51.32x29%
layer=8b_up, M=1633.0135.943.069.7126.11099.11.31x29%
layer=8b_down, M=124.635.644.520.831.31120.11.81x38%
layer=8b_down, M=234.640.243.121.5129.71119.81.25x27%
layer=8b_down, M=434.648.143.227.6129.61120.11.25x27%
layer=8b_down, M=834.668.143.542.9129.71120.21.26x27%
layer=8b_down, M=1635.0119.844.169.9129.61120.51.26x27%
layer=qwen_qkv, M=12817.2-5.944.612.466.40.34x5%
layer=qwen_qkv, M=51219.9-8.1154.913.969.90.41x8%
layer=qwen_qkv, M=204843.4-22.0591.526.281.60.51x11%
layer=qwen_o, M=12817.1-5.737.610.154.70.33x4%
layer=qwen_o, M=51219.7-7.3119.111.857.10.37x7%
layer=qwen_o, M=204842.8-17.1452.320.665.50.40x10%
layer=qwen_gate_up, M=12842.9-25.2324.264.2535.50.59x14%
layer=qwen_gate_up, M=512109.7-50.81264.289.4554.30.46x9%
layer=qwen_gate_up, M=2048345.8-177.05034.3219.6667.80.51x8%
layer=qwen_down, M=12887.7-16.7134.947.8283.00.19x3%
layer=qwen_down, M=51299.9-31.2505.660.8296.10.31x5%
layer=qwen_down, M=2048232.9-83.02002.5116.6340.60.36x6%
layer=8b_up, M=12865.4-45.3501.3124.41098.60.69x16%
layer=8b_up, M=512216.8-105.41994.7172.91137.70.49x7%
layer=8b_up, M=2048743.7-346.57909.4436.51360.70.47x4%
layer=8b_down, M=128140.4-51.4523.7134.71122.40.37x8%
layer=8b_down, M=512225.3-92.72031.4168.11151.10.41x7%
layer=8b_down, M=2048741.4-335.48068.2426.31368.10.45x4%

Profile on H100

launchtime (ns)DRAM % peakSM % peakoccupancy %regs/thread
w4a16_triton_gate_up_M11081640.6449.2938.9155
w4a16_triton_gate_up_M129120.800.155.7532
w4a16_cuda_gate_up_M11731225.4054.2842.5048
w4a16_cuda_gate_up_M128480.820.155.8932
w4a16_triton_gate_up_M162208019.8738.9624.5283
w4a16_cuda_gate_up_M16734086.4535.5112.99153
w4a16_cuda_gate_up_M16326410.721.8711.5032
w4a16_triton_down_M11334416.4533.3717.4782
w4a16_triton_down_M128480.120.035.9432
w4a16_cuda_down_M12016010.9021.549.1048
w4a16_cuda_down_M128480.120.036.0332
w4a16_triton_down_M161318417.4433.5317.4582
w4a16_triton_down_M1627521.130.195.5832
w4a16_cuda_down_M16531204.3426.329.15153
w4a16_cuda_down_M1628801.090.186.0932

Power on H100

Sustained decode matmuls hold the card at its power cap (reason 0x4 = software power cap) and the SM clock drops well below its maximum. That is why sustained numbers sit below single-launch Nsight Compute numbers, and why cutting ALU work in the dequantization (the factored GEMV) raised bandwidth.

kernel (gate_up, M=1)us per callSM clock (MHz)power (W)throttle reasons
triton11.61980468 / 7000x0000000000000000
cuda17.81980439 / 7000x0000000000000000
fp1622.21980485 / 7000x0000000000000000