llm-rs: The Two Biggest Single-GPU Wins, Up Close

Of everything I’ve done to make llm-rs fast on one GPU, two changes gave the most:

  1. Hand-written SIMT decode kernels. They doubled single-request decode on a small dense model, from 156 to 315 tokens/s on the same card.
  2. Grouping mixture-of-experts work by expert, on the GPU. It made batched decode on Qwen3-30B-A3B 2.8× faster and cut time to first token 2.7×.

Earlier posts gave the headline numbers. This one goes inside both: what each kernel does with its threads and bytes, what the profiler showed at each step, and the attempts that failed. It’s long and written to be read away from a screen. The code snippets are short, and the numbers that matter are repeated in the text.

Part 1: Decode kernels that read at full bandwidth

The ceiling

Decoding one token with Qwen2.5-0.5B in BF16 means reading every weight once: about 0.99 GB per token. The test card was an RTX A4000 with 448 GB/s of memory bandwidth, which gives:

448 GB/s ÷ 0.99 GB per token ≈ 453 tokens/s

That’s the speed of light for one request. Nothing can decode faster without reading fewer bytes. Every change below was judged by the share of that ceiling it reached.

The arithmetic is trivial by comparison. A matrix-vector product does two floating-point operations per weight, two bytes per weight in BF16. The A4000 can do about 40 floating-point operations in the time it takes to fetch one byte. So the only question is whether the memory system is kept busy.

Where cuTile stopped

The first CUDA backend used cuTile, which writes kernels as operations on tiles and leaves the thread mapping to the compiler. After tuning, it reached 156–162 tok/s, 34–36% of the ceiling.

Nsight Systems showed the GPU busy about 95% of decode wall time. Launch overhead wasn’t the problem; the kernels themselves were slow. The per-kernel profile:

Kernel Grid Avg Share
Q, output, down 14 blocks 30 µs 36%
gate+up+SiLU 76 blocks 53 µs 21%
lm_head 2,374 blocks 845 µs 14%
attention 2 blocks 26 µs 10%

Look at the first row. An 896×896 BF16 projection is 1.6 MB. At 448 GB/s it should take about 4 µs. It took 30. And it ran on 14 blocks, on a GPU with 48 streaming multiprocessors. Two-thirds of the SMs had nothing to do, and the ones that did couldn’t keep enough loads in flight to cover memory latency.

The large kernels (lm_head, gate/up) were at 72–74% of bandwidth. The small ones were far below it.

I tried the obvious fixes inside cuTile, and none helped:

  • 16-row blocks (more blocks): 102–104 tok/s, much worse.
  • 32-row blocks: no change.
  • Split-K with 7–38 splits, to spread one row over several blocks: 123–130 tok/s, worse.
  • Pipelining hints at several depths: no change, or worse.

The lesson was that the problem lies in how a row maps onto lanes and memory transactions, and that’s the one thing a tile abstraction hides on purpose.

One warp per output row

So the decode path moved to SIMT kernels: Rust compiled to PTX with explicit threads, warps and shuffles. The core matrix-vector kernel is short:

let row = warp_row();
if row >= rows { return; }
let words = k / 2;
let total = row_dot(
    w.add(row * words), x, words);
if lane_id() == 0 {
    y[row] = total + bias[row];
}

Each warp of 32 threads owns one output row. A block is 256 threads, so 8 warps and 8 rows. The 896-row projection becomes 112 blocks instead of 14, and lm_head (151,936 rows) becomes 18,992 blocks.

The inner loop, row_dot, treats the BF16 row as 32-bit words, two weights per word:

let mut acc = 0.0;
let mut j = lane;
while j < words {
    acc += word_dot(w_row[j], x, j);
    j += 32;
}
warp_sum(acc)

Lane 0 takes words 0, 32, 64…; lane 1 takes 1, 33, 65…; and so on. Three details make this fast.

1. Every weight load is perfectly coalesced. On each iteration the 32 lanes read 32 consecutive words, 128 contiguous bytes, one full cache line. Nothing fetched is wasted.

2. The input is read in pairs. Word j holds weights 2j and 2j+1, so the lane also needs input elements 2j and 2j+1. word_dot fetches both with one 64-bit load. Across the warp that’s 256 contiguous bytes in one instruction. Two separate 32-bit loads would each use only half of the bytes fetched, and would hit 2-way bank conflicts when the input sits in shared memory.

3. BF16 to float is free. A BF16 value is the top 16 bits of an f32. The low weight is f32::from_bits(word << 16), and the high one is f32::from_bits(word & 0xFFFF0000). That’s one shift or one AND, with no conversion instruction.

At the end, each lane holds a partial sum. warp_sum combines them in five shuffle steps (XOR distances 16, 8, 4, 2, 1), after which every lane holds the total. No shared memory, no second kernel, no atomics.

Why is this the right shape for decode? Because at one request, there’s no data reuse at all. Each weight is used exactly once. Tiling and shared memory exist to reuse data, so they add nothing here. What matters is having as many independent loads in flight as possible to hide memory latency, and a warp per row gives thousands of them.

Fusing launches: 15 to 9 per layer

The other half of the first step was fusion. Each launch has a fixed cost, and small kernels between projections each make a round trip to memory. The SIMT path fused:

  • Q, K and V into one kernel: one launch, three output ranges;
  • RoPE and the KV-cache write into one;
  • the residual add and RMSNorm into one;
  • gate, up and SiLU into one. Each warp computes a gate row and an up row against the same input and writes silu(g) · u directly. Neither intermediate touches memory.

Launches per layer went from 15 to 9. Decode reached 228–264 tok/s, 50–58% of the ceiling. The spread was large between runs, and the reason turned out to be the next problem.

Attention: lanes over positions

Decode attention reads the KV cache, not weights, and at short contexts it’s bound by latency, not bandwidth. Two changes helped:

  • Lane-per-position scoring. Each lane scores a different past position, with its loads unrolled. One attention_partial call went from 15.4 to 10.5 µs.
  • Split-sequence attention with small chunks. The context splits into chunks of positions, each handled by one warp with an online softmax, followed by a cheap merge kernel. More chunks mean more warps hiding latency, until the merge costs more than it saves.

The chunk size was swept, not guessed:

Positions per chunk tok/s
4 298
8 303.5–304.4
16 302.5
32 297.5

The surprise: the host was the bottleneck

Here’s the change that mattered most, and it didn’t touch a kernel.

With the kernels near bandwidth, Nsight Systems showed the GPU idle about a third of every step. The timeline was full of gaps between kernels. In those gaps the host was issuing 368 cuMemAllocAsync / cuMemFreeAsync pairs per token: every intermediate buffer of every layer was allocated and freed on each step.

Each call is cheap on its own, a few microseconds. But once a whole layer’s kernels run in tens of microseconds, a few microseconds of host work between launches is enough to starve the GPU. The host could no longer queue work faster than the GPU finished it.

The fix was a per-request decode workspace: every intermediate buffer is allocated once, when the request starts, and reused on every step. Results:

  • decode: ~250 → 297 tok/s (66% of the ceiling);
  • GPU busy: about 95% of decode;
  • run-to-run spread: nearly gone. The noise had been the host’s allocator, not the GPU.

This is the lesson I keep relearning: once the kernels are fast, profile the gaps between them, not just the kernels.

Folding RMSNorm into the projections

Two launches per layer were still standalone RMSNorms (before attention and before the MLP), at about 4 µs each. The idea: compute the norm inside the Q/K/V and gate/up kernels, in a prologue.

Every block of those kernels recomputes the norm of the 896-element residual into shared memory. That’s redundant work, but 896 floats is tiny next to the weights each block reads. Block 0 also writes the residual sum out, to the other of two ping-pong buffers, for the next layer. Launches per layer go from 9 to 7, and the outputs are bit-identical to the unfused kernels, because the summation order is unchanged. A test checks this.

The first version was slower. Here’s how each step went (decode tok/s, then the fused Q/K/V and gate/up kernel times):

Step tok/s QKV gate/up
separate norm 303 7.2 µs 46.0 µs
fused, naive 299 11.4 51.7
+ weight prefetch 300 11.0 52.4
+ 64-bit shared loads 300 10.9 52.3
+ loads 4 at a time 308 9.7 50.1
+ 4 rows per warp 315 9.7 47.0

The naive prologue cost about 4 µs per kernel, the same as the launch it removed. The reason: the prologue was a chain of dependent loads. Each thread loaded one residual element, added, squared, accumulated, then loaded the next one. Every load waited on an L2 round trip before the next could start.

I tried the usual fixes first:

  • Prefetching the weights before the prologue, so they’d be ready when it finished. No change.
  • Fixing shared-memory bank conflicts with 64-bit loads. No change.

Neither touched the actual problem, which was latency, not bandwidth or conflicts. What worked was issuing four independent loads at once, then doing the math. Four requests in flight, one wait instead of four. That took decode from 300 to 308 tok/s.

The last step attacked repetition. The gate/up kernel had 608 blocks, each repeating the prologue. Giving each warp 4 rows instead of 1 cut that to 152 blocks: a quarter as many prologues, and each warp’s input loads are shared across four rows. I swept rows per warp:

Rows per warp tok/s
1 307.4
2 311.1
3 305.3
4 314.5
6–16 313.4–314.2

Where it ended

Per decoded token, from Nsight:

Kernel Time Bandwidth
lm_head 0.68 ms 90%
gate/up/SiLU+norm 1.13 ms 83%
output + down 0.71 ms 78%
Q/K/V + norm 0.23 ms 48%
attention 0.23 ms latency
RoPE + KV write 0.05 ms latency

That’s 3.10 ms of kernel time against an ideal of 2.21 ms: about 71% of the ceiling, and 315 tok/s, double where cuTile stopped. Greedy output still matches the CPU reference token for token.

What’s left is easy to read off the table. Q/K/V is at 48% because its rows are narrow and there are too few warps to cover the prologue. Attention and RoPE are latency-bound, and only CUDA graphs or fusing them into neighbours would remove their cost.

Part 1 takeaways

  1. For batch-1 decode, the whole problem is the mapping of lanes to bytes. One warp per row, coalesced 128-byte loads, paired input loads, a shuffle reduction.
  2. The host becomes the bottleneck as soon as the kernels are good. The biggest single jump came from removing allocations, not from a kernel.
  3. Fusion that adds a dependent-load chain can be slower than the launch it saves. Issue independent loads together.
  4. Sweep the knobs (chunk size, rows per warp). The best values were not the ones I’d have guessed.

One more lesson from the same stretch, for the prefill kernels: the first batched matrix-vector kernel was 10× slower than expected. Its per-token accumulator array had spilled from registers to local memory. Unrolling the token loops (#[unroll]), so every index was a compile-time constant, kept it in registers. The same bug, and the same fix, came back later in the MoE kernels.

Part 2: Mixture-of-experts, grouped by expert

Why MoE breaks the dense kernels

Qwen3-30B-A3B has 48 layers, each with 128 experts: small gated MLPs, 2048 → 768 → 2048. A router picks 8 experts per token. The weights are INT4 with a scale and an offset per 128 weights (int4-g128), about 14.5 GB of experts in all.

The engine’s first version ran experts the simplest way. moe_gemv_q4 launched a grid of (row tiles × routed pairs), where a pair is one (token, expert) combination. Each pair read its expert’s full weights on its own.

At one request, that’s fine: 8 pairs, 8 different experts, nothing to share. But consider a decode step with 16 requests:

  • 16 tokens × 8 experts = 128 pairs per layer;
  • those 128 pairs hit only about 80 distinct experts;
  • so about 48 expert reads per layer are repeats of weights already read in the same step.

Prefill was worse. A 256-token prompt routes 2,048 pairs per layer, about 16 per expert, so each expert was read about 16 times over.

The first serving numbers showed it:

Load tok/s TTFT TPOT
1 at a time 53.3 1,274 ms 9.07 ms
16 at once 67.3 12.7 s 139 ms

Sixteen requests got barely more throughput than one. An Nsight profile put the expert products at 54% of GPU time. One decode call took 35 µs for 8 pairs: 6.3 MB of weights, about 180 GB/s on a 768 GB/s card.

The obvious fix is to sort the pairs by expert and read each expert once. But where do you sort?

Why the sort must stay on the GPU

The router runs on the GPU. Sorting on the host means copying the routing back, waiting for it, sorting, and launching per-expert work. That has two costs:

  1. A synchronization every layer. The host stalls until the GPU finishes the router, 48 times per step. The overlapped pipeline, where the host queues step N+1 while the GPU runs step N, stops working.
  2. No CUDA graphs. A graph replays a fixed sequence of launches. If the launches depend on routing that only the host knows after a readback, the step can’t be captured.

So the grouping had to happen on the device, and produce something a fixed-shape kernel launch could consume.

The grouping kernel: a counting sort in one block

moe_group_pairs is one block of 1,024 threads. It’s a counting sort with three phases.

Phase 1: count. Each thread takes pairs tid, tid + 1024, … and increments its expert’s counter, a shared-memory atomic:

let e = ids[p];
count[e].fetch_add(1, Relaxed);

With 128 experts and at most a few thousand pairs, this is a handful of atomics per thread, all in shared memory.

Phase 2: scan, in one warp. Warp 0 walks the 128 counters, 32 experts per pass. Each lane holds one expert’s count c, and the warp runs three prefix sums at once:

  • over the counts c, which gives each expert’s start in the sorted order;
  • over c > 0, which gives each used expert’s slot in a compact active list;
  • over ceil(c / 128), which gives the work items for the prefill GEMM.

Each prefix sum is five shuffle_up steps. Totals carry between passes by reading lane 31. The counter array then becomes a cursor array: each expert’s count is overwritten with its start position.

Phase 3: scatter. A second atomic pass over the pairs claims a slot in its expert’s range and writes the pair’s index there:

let at = count[e].fetch_add(1, Relaxed);
order[at] = p;

Within an expert, the pairs end up in no fixed order. That’s fine: each pair’s result is computed the same way wherever it sits and is written to the pair’s own output row.

The outputs:

  • starts[e]: where expert e’s pairs begin in order;
  • order: pair indices, grouped by expert;
  • active: the number of used experts, then their ids;
  • tiles (for prefill): (expert, first row, row count) per 128-row tile.

The whole thing is one launch of a few microseconds, with no host involvement.

The decode kernel: one block per (row tile, active expert)

moe_glu_q4 computes silu(gate · x) · (up · x) for every pair. Its grid is:

  • x: row tiles of the expert’s 768 output rows;
  • y: the maximum number of experts that could be active.

The grid size can’t depend on how many experts are actually active, because the host doesn’t know that (it never reads the routing back). So the grid is sized for the worst case, and blocks whose blockIdx.y is past the active count exit immediately:

let slot = blockIdx_y();
if slot >= active[0] { return; }
let e = active[1 + slot];
let (begin, end) =
    (starts[e], starts[e + 1]);

An exited block costs almost nothing, and the launch shape is fixed, so the step stays capturable as a CUDA graph.

The reuse. Each warp computes 2 output rows (ROWS = 2), and since gate and up are fused, that’s 4 weight rows. It walks its expert’s pairs 4 at a time (TOKENS = 4). For each weight word it loads, it applies that word to all 4 pairs before moving on. An expert with 1–4 pairs reads its weights once; one with 9 reads them three times. The per-pair kernel read them 9 times.

The accumulators are a small 2D array, gate[TOKENS][ROWS] and up[TOKENS][ROWS], 16 floats in all. Every loop over them is #[unroll]ed so they stay in registers. That’s the same lesson as the 10× prefill bug in Part 1.

When an expert has fewer than 4 pairs left, the spare slots repeat the first pair’s index (so loads stay in bounds) and are skipped with a branch on t < n. Since n is the same for the whole block, the branch is uniform: no divergence.

That detail mattered. My first attempt at grouping always computed 8 pairs per block. At one request, with 1 pair per expert, it did 8× the arithmetic for nothing and was slower than the per-pair kernel. The uniform skip fixed it.

Inside the INT4 dot product

Each 32-bit word holds 8 INT4 codes. A weight is:

w = scale · (code − 8) + offset

with one scale and offset per 128 weights. Expanding the dot product over a group:

Σ w·x = scale · Σ (code − 8)·x + offset · Σ x

So the kernel never builds dequantized weights. Per word it computes two things:

  • int4_dot8(word, xs): the sum of (code − 8) · x over the word’s 8 inputs;
  • sum8(xs): the plain sum of those 8 inputs.

Then one FMA each applies the scale and the offset. sum8 is computed once per word and shared by both rows and both projections.

The nibble decode avoids integer-to-float conversion entirely, with a bit trick:

f32::from_bits(
    0x4B00_0000 | ((word >> s) & 0xF)
) - 8_388_616.0

0x4B000000 is the float 2²³ = 8,388,608. At that magnitude the spacing between floats is exactly 1, so OR-ing a 4-bit code into the low mantissa bits gives exactly 2²³ + code. Subtracting 2²³ + 8 = 8,388,616 leaves exactly code − 8, as a float. One AND, one OR, one subtract, and no conversion instruction.

The load pattern. Lane l takes word l of four consecutive 32-word chunks per iteration (for j in 0..4, unrolled). So each lane has four weight loads, plus scale and offset loads, in flight at once. The 8 inputs a word needs come as two 16-byte loads (load8). The loop advances 128 words per iteration; for 2,048 columns that’s 256 words, two iterations.

At the end, each of the 16 accumulators gets a five-shuffle warp_sum, and lane 0 writes silu(g) · u to the pair’s output row.

The down projection (moe_down_q4) has the same structure, with 4 rows per warp and no gate.

Grouped prefill: one launch for every expert

Prefill had a separate problem. The intermediate version read the routing back to the host each layer, then launched one tensor-core GEMM per expert: about 256 launches per layer, each only 12–16 blocks wide on a 64-SM GPU. Most of the GPU idled during each.

With the grouping kernel on the device, prefill became:

  1. Group: moe_group_pairs also writes the tiles list: for each expert, its pairs split into tiles of up to 128 rows, each tile an (expert, first row, row count) item.
  2. Gather: moe_gather_bf16 copies each pair’s token row into a contiguous BF16 buffer, in expert order.
  3. One GEMM for all experts: the prefill GEMM gained a grouped mode. Block (b, i) reads work item i, finds its expert, and multiplies that tile’s rows against that expert’s slice of the stacked INT4 weights. Every expert’s gated MLP runs in one launch, and every down projection in one more.
  4. Combine: the weighted sum per token reads each pair’s row through the rows_of map the grouping wrote.

No readback, no per-expert launches, and the math for each row is unchanged, so the logits match the host-grouped path bit for bit.

Results

Qwen3-30B-A3B, int4-g128, one RTX A5000; 256-token prompts and 128-token outputs. Each row was measured in the same session as its baseline.

One request at a time:

Version tok/s TTFT TPOT
per-pair 78.7 519 ms 8.96 ms
grouped decode 97.2 522 ms 6.49 ms
+ grouped prefill 126.8 188 ms 6.70 ms
llama.cpp Q4_K_M 134.8 257 ms 6.19 ms

16 requests at once:

Version tok/s TTFT TPOT
per-pair 154.1 2.37 s 86.8 ms
grouped decode 354.2 1.55 s 33.6 ms
+ grouped prefill 439.1 718 ms 30.9 ms
llama.cpp Q4_K_M 424.3 621 ms 33.1 ms

Some arithmetic on why these numbers come out the way they do:

  • At 16 requests, decode is 2.8× faster (86.8 → 30.9 ms per token). Cutting 128 expert reads to about 80 is only 1.6×. The rest comes from the better loads: four chunks in flight per lane, 16-byte input loads, the shared sum8, and no conversion instructions. The two effects multiply.
  • At one request, decode is 1.4× faster (8.96 → 6.49 ms). With 8 pairs on 8 different experts there’s nothing to share, so this is the load pattern alone.
  • Time to first token fell 2.7× (519 → 188 ms), now ahead of llama.cpp. Almost all of it came from removing the per-layer readback and the ~256 launches.

The attempt that didn’t work

Even after grouping, the expert kernels ran at only 50–60% of bandwidth. My theory was a dependent-load chain at the start of every block: active count, then expert id, then pair range, then order, then the inputs, five round trips before any weight streams. At one request the kernels launch about four waves of blocks, so the theory said each wave paid that chain again.

The fix I tried: make each warp loop over row groups so the grid could be sized to exactly one wave, plus a variant with launch_bounds to raise occupancy. Every variant gave byte-identical logits, and every one was slower:

Variant TPOT, 1 req TPOT, 16
committed kernels 6.19 ms 31.0 ms
looping, same grid 6.85 35.8
one wave 6.75 100.8
launch bounds 9.62 47.9

One wave saved under 1 µs per call, so the chain wasn’t the problem. The loop itself cost about 5 µs per call: more registers, and loads the compiler could no longer hoist. And launch_bounds forced spills to local memory. Reverted.

The lesson I wrote in the notes: start from a per-kernel probe, not a theory. Remove the loads, then the math, then the token loop, one at a time, and see which one the time follows.

What the probe found, and what came after

The probe pointed somewhere else: the kernels were instruction-bound, not memory-bound. At 16 requests an expert serves about 2 pairs per step, and the kernel spent about 60 instructions per weight word and row. That’s roughly what the SMs can issue while the weights stream, so issue rate, not bandwidth, set the speed.

Two follow-up kernels cut the instruction count:

  • v3: codes placed into a float’s mantissa with a byte-permute instruction (prmt), and each pair’s 8-value dot product as one FMA chain. It was about 2% faster: cheaper decoding alone barely moved an issue-bound kernel.
  • q8: round the inputs to INT8, with a scale per 32 values, the way llama.cpp’s q8_1 does. Then each weight word and row is two dp4a instructions, each doing 4 multiply-adds on bytes. The offsets fold into (offset − 8·scale) · sum. The static instruction count dropped from 2,613 to 1,629 for the gate/up kernel, and registers dropped from 167 to 96.

q8 took 16-request decode from 31.5 to 25.2 ms per token (−20%) and throughput from 508 to 634 tokens/s. WikiText-2 perplexity was unchanged within noise (12.1777 → 12.1696, −0.07% ± 0.05%), so it became the default. With an INT8 LM head as well, one request now decodes at about 5.7 ms per token on the same card. That beats the 6.19 ms llama.cpp measured earlier, though in a different session, so I’d want a same-session rerun before claiming it.

Part 2 takeaways

  1. MoE speed is a scheduling problem as much as a kernel problem. Sorting pairs by expert, on the device, mattered as much as the matrix-vector kernel.
  2. Keep the host out of the per-layer loop. A fixed launch shape, with early-exit blocks for inactive experts, kept every step graph-capturable. The 2.7× TTFT win came from removing a readback and 256 launches, not from faster math.
  3. Factor out what doesn’t depend on the weight. The offset term became one sum8 per word, shared by four weight rows.
  4. Measure whether a kernel is memory-bound or instruction-bound before optimizing it. The one-wave attempt assumed latency. The real limit was instruction issue, and only cutting instructions (INT8 inputs, dp4a) moved it.

What’s next

Both stories have the same arc: an obvious kernel, a profile that pointed somewhere unexpected, and a fix that was often outside the kernel. What’s left on one GPU:

  • Q/K/V at 48% of bandwidth on the dense path: too few warps for narrow rows.
  • Expert paging when experts don’t fit on the GPU. It’s still PCIe-bound under load: 16 requests touch about 80 experts per layer, and grouping doesn’t change how many bytes cross the bus.
  • Admission under heavy load: an expected-growth reservation, so that 128 concurrent requests don’t preempt each other for KV-cache blocks.

All the measurements behind this post are in the llm-rs repo’s docs/PERF.md.

tags: rust - cuda - llm-inference - gpu-kernels - mixture-of-experts - simt - int4