OpenFlowLM-Next icon indicating copy to clipboard operation
OpenFlowLM-Next copied to clipboard

Open kernels: batched prefill -- amortize the weight stream across a token block

Open vegah opened this issue 2 months ago • 4 comments

Splitting item 1 of #16 out into its own issue so it has one owner and nobody starts it twice. #16 stays as the umbrella for the other two.

Before filing I checked everything open and everything merged since: #20 (linux build script), #24 (gguf), #25/#26/#27/#28 (the shapes → Qwen3.5 → native q8 → adapters stack), #31, and the merged #21/#22/#23. None of them touches prefill batching. #23's max_prefill_len change is a guard against log2 of a non-positive length, not a batch path. The four branches on this repo are main, staging, linux-clean-build and proposed-gguf-support. So this is unclaimed work.

Where it stands

Prompt tokens go through the decode step one at a time. From src/open_qwen36/README.md on main:

model prefill
Qwen3.6-35B-A3B 124 ms/token
Qwen3-4B 129 ms/token
Llama-3.1-8B 125 ms/token
Gemma3-4B 63 ms/token
Granite 4.2 3B (after #22) 58.6 ms/token

#22 also established the shape of the cost, which matters more than the column above: prefill costs about what a decode step costs at that position, so it is quadratic in the prompt length. On a short prompt that reads as a flat per-token rate and hides completely. On Granite it is 58.93 s of TTFT for a 1005-token prompt — and that is after a 20.6× improvement.

For scale, the closed FastFlowLM engine on the same SoC sustains ~320–350 tok/s of prefill (~3 ms/token) on a 9B, and stays flat from 1k to 32k context (the flm bench dump in ROCm/FastFlowLM#636). The open path is roughly 40× behind on the number a user feels first, and the gap is structural rather than a tuning deficit: every prompt token re-streams the model's whole weight set.

The experiment #16 is gated on, worked out on paper first

#16 phrases the open question as whether the q4_1 GEMV dataflow in open_kernels/designs/layer_x/ can become a GEMM that amortizes the weight stream across a token block. The arithmetic says yes, with a lot of room.

  • q4nx packs 8192 weights into a 5120 B chunk (512 B bf16 d, 512 B bf16 m, 4096 B nibbles) = 0.625 byte per weight. A projection at one token therefore runs at 2 / 0.625 = 3.2 FLOP/byte.
  • The array's DMA roof on this SoC is 45.5 GB/s, measured with four independent instruments, and a null kernel — DMA only, arithmetic short-circuited — reaches 46.3 GB/s. (T45, 0145)
  • Attainable bf16 GEMM on XDNA2 is 14.71 TOPS (arXiv:2512.13282).
  • Machine balance is therefore 14.71e12 / 45.5e9 = 323 FLOP/byte.

The crossover sits at T ≈ 100 tokens. Below it, prefill is purely bandwidth-bound, so every doubling of the block halves the per-token weight cost and the arithmetic does not notice. A block of 32 is still 3.2× inside the bandwidth-bound regime — comfortably clear of the wall, not near it.

Concretely on Granite, whose position-0 weight stream is 46.2 ms: at T = 32 the weight term becomes 1.44 ms/token. Add attention and activations back and the prediction lands in the same neighbourhood as the closed engine's measured prefill. That is the useful part of the result — it says there is no missing trick inside the closed batch kernels, only this one.

Note the direction of the conservatism: 14.71 TOPS is the plain-bf16 figure. A datapath with more arithmetic throughput raises the balance and moves the crossover further out, so T ≈ 100 is a floor, not a ceiling.

This paragraph is modelled, not measured. It assumes on-core dequantization does not dominate, which is risk 1 below.

The measurement that settles it

One projection shape. The existing q4_1 GEMV design turned into a T-row GEMM. Traced array time over T ∈ {1, 2, 4, 8, 16, 32}.

If array time is flat in T up to 32, the thing is proven and everything after it is engineering. If it is not flat, the slope names which risk below is the real one, which is worth almost as much.

Hardware traces, not wall clock — the NPU is shared, so wall clock measures how busy the machine is rather than how good the kernel is.

Risks, in the order I expect them to bite

  1. Dequantization instruction count. The q4 → bf16 unpack is per-weight work, and it only amortizes across T if the unpacked tile stays resident in L1 rather than being redone per row. On this core instruction count dominates far more than vector width does — measured on the attention kernel in #22, halving the MACs was free while deleting one scalar float was 18% of the step. This is the risk that decides the whole thing.
  2. Accumulator registers, before L1 bytes. aie2p has 5 × 2048-bit accumulator registers, not the 8 the AIE-ML v2 documentation states, which caps independent MMAC accumulators at 5 with bf16 and therefore caps the register-blocking factor. L1 itself is 63 KB usable, not 64 — 1 KB is program stack — and a T-row block needs T×K activations plus T×n_tile fp32 accumulators on top of the double-buffered weight tile.
  3. Program memory. 16 KB per core. #22's four-row attention body already had to roll the single-row path to fit, so there is not much headroom for a second templated body.
  4. Shim descriptors. 16 buffer descriptors per shim bound what the runtime sequence can keep in flight; the failure is loud at compile time. Task-group depth 2 is the maximum that runs on hardware — depth 3 compiles clean and then times out.
  5. Prefill attention is its own kernel. Within a block it is O(T²), plus O(T·P) against the cache. The GEMM alone does not deliver a batched prefill.

Why this pays twice

The remaining lever in #16 item 2 is to put the attention scores on the MMAC unit — with several rows resident the scores are an aie::mmul shape instead of a vector dot product. In decode that parallelism has to be manufactured out of KV rows, which is why it is expensive there. In prefill the query rows are simply there. So the block-attention kernel this issue needs is the same rewrite item 2 wants, and doing prefill first hands it to decode.

Done when

  • a multi-token prefill dispatch exists;
  • its logits match N sequential decode steps against the fp64 replica (open_kernels/model/replica.py), to the same bar the families were accepted against;
  • TTFT on a 500–1000 token prompt drops by a large constant factor, measured through flm bench with utilities/bench-configs/, quoted with the prompt length attached;
  • the T-sweep is recorded, including the T at which it stops being flat — that number is the reusable part.

vegah avatar Sep 08 '26 22:09 vegah

Gating experiment done, plus an end-to-end measurement that corrects this issue's own framing. Three results, one of which makes the headline smaller.

1. The mmul reading was right, and T ≤ 4 is free

Confirmed in the code and then on hardware. aie::mmul<4,8,8,int16_t,uint8_t>'s M=4 is the wasted axis — N=8 is already the real output-row axis and fully used — so four distinct tokens in the M rows cost the identical mmul.mac() count. GEMV_T is now a compile-time constant of open_kernels/designs/gemv_q4/, with the T=1 path physically unchanged behind #if GEMV_T > 1 and verified bit-identical.

Correctness on the standalone testbench, T distinct random activations per block (never T copies of one — that cannot detect cross-token mixing), each against its own fp64 reference: cosine 1.000000000, maxrel 2.6e-06–6.4e-06, every token, every shape, every buildable T. No cross-token mixing observed.

2. The ceiling is L1, not compute — and it lands one doubling early

region K T=1 T=2 T=4 T=8 T=16
qkv 8192×2048 2048 0.286 ms 0.280 0.329 unbuildable —
share_up 2048 0.092 0.098 0.127 unbuildable —
share_gate 2048 0.087 0.095 0.137 unbuildable —
z 2048 0.205 0.199 0.222 unbuildable —
share_down 512 0.114 0.099 0.104 0.140 0.188

Medians of 20 warm runs on a quiet box. The compute knee is between T=4 and T=8 (share_down: +37% at 8, +58% at 16). But for every K=2048 region T=8 does not build at all: 88,064 B against the 64,512 B L1 budget, at the smallest legal PER_CALL, confirmed by an explicit failing build rather than inferred. Per-token L1 cost is tab 4608 + x 4096 + y 512 = 9216 B, and eight of those exceed the budget however small the weight buffer gets.

So the practical answer to "the T at which it stops being flat" is T=4, set by L1 capacity, one full doubling below where the arithmetic would have stopped it.

That ceiling is not fundamental, and the lever is identified: x (4096 B/token, the raw bf16 activation) is dead after gemv_q4_prep builds the table — the tile entry points take (chunks, tab, y) and never read x again. Preparing the table host-side and streaming tab instead of x drops the per-token cost to 5120 B, which puts T=8 at 55,296 B and inside the budget. The shim pays +12.5% on a stream that is under 1% of qkv's weight traffic. Not built.

3. The correction: batching the projections is worth ~2.5×, not ~40×

The issue implies the closed engine's ~40× prefill advantage is this one mechanism. It is not, and the arithmetic is now measured rather than assumed.

Prefill cost per token at position i is step0 + s·i — the model in utilities/bench-configs/README.md. Ran flm bench granite:3b -i bench-4k.json (three stages from one invocation) and fitted it on the 1k and 4k endpoints only, holding 2k out:

stage prompt tokens TTFT
1k 1005 76.873 s
2k 1972 172.360 s
4k 3906 426.284 s
step0 = 65.178 ms      s = 0.022507 ms/position
held-out 2k: predicted 172.298 s   measured 172.360 s   -0.036%

A linear model through the same 1k point misses that held-out point by −12.5% and the 4k point by −29.9%. The quadratic term is real and confirmed out of sample. Which means:

weight term (batchable) attention term (not)
N = 1005 65.5 s 11.4 s
N = 3906 254.6 s 171.7 s

At the measured T=4 (3.48× per token — the epilogues cost, it is not 4×), batching the projections gives 2.5× at 1005 tokens and 1.7× at 3906. Even perfect batching (T→∞) leaves 171.7 s of the 4k run's 426.3 s untouched.

Block attention is not the second half of this work; past roughly 2k tokens it is the larger half. Item 2 of #16 and this issue are more coupled than either says.

A measurement trap worth recording

The 1k stage of that bench-4k run came back at 76.873 s against the 58.930 s the same binary and model measured on 2026-09-07 — 30% slower, on a quieter box. Cause: bench-4k runs hardest-first, so its 1k stage ran last, after ~10 minutes of sustained load, while the baseline's ran first on a cold device. Decode fell the same way, 13.33 → 10.61 tok/s.

A bench-4k 1k row is not comparable to a bench-1k run. utilities/bench-configs/README.md documents the hardest-first order and warns that a run killed early has measured nothing; it does not warn that the order makes every later stage slower than the same stage measured alone. Worth adding. Within-run comparisons are unaffected, which is why the fit above stands.

The same session also failed to reproduce harness/README.md's kernel table (0.92 ms published against 0.286 measured, with the DMA-only floor moving 0.45 → 0.29 ms) — when the floor moves it is the machine, not the kernel. Both are the same lesson about comparing numbers taken in different machine states.

What is still ahead

The dispatch itself. Engine::prefill() is still for (i) core_->step(ids[i], ...), and the fused layer design (designs/dense/dx.py, one dispatch per layer including attention) has not yet been threaded for T — that is in progress, and the open question there is whether the attention phase can be iterated inside one dispatch or whether the layer has to split into two. Nothing end-to-end is claimed yet.

vegah avatar Sep 08 '26 23:09 vegah

Thanks for taking this one -- and for the measurements, the T=4 ceiling and the out-of-sample fit on the attention term are both things I didn't have. One data point from our side that might save you some work, offered in case it's useful.

Before this issue went up I'd run the gating experiment by another route, so there's a second measurement to compare against. Instead of widening the GEMV to T rows, it's a whole-array bf16 matmul (mlir-aie's whole_array shape) with each core dequantizing the 5 KB pool chunk into mm.cc's B tile on the way in. The activation block streams through the memtile as 8 KB tiles, so L1 only holds one tile at a time -- which is why the per-token L1 cost that stops GEMV_T at 4 doesn't come up. It's in open_kernels/designs/gemm_q4/ on our fork, commit Cyronius/OpenFlowLM-Next@8d9e3eb7, with the fixture and comparison script beside it.

What it measured, Qwen3-4B's projection shapes, hardware through the harness, exact against the bf16-rounded reference (corr 1.00000000):

  • q projection, K 2560 / N 4096, 128 tokens: 2.35 ms, ~1.14 TFLOPS
  • same at 192 tokens: 3.07 ms, ~1.31 TFLOPS
  • the down projection's shape, K 9728 / N 2560, 128 tokens: 5.25 ms, ~1.21 TFLOPS

So on the first, untuned build it amortizes the weight stream over ~130 tokens rather than 4. If that holds up in a dispatch, the batchable term of a 1005-token prompt would come down to a couple of seconds. On your risk 1: the dequant here is ~2K vector ops per chunk and is redone by each core in a column, and the kernel still lands at 1.2 TFLOPS, so at least on this shape it didn't dominate.

On the attention half, agreed that it's the larger part past 2k. It has moved a little since you filed: the fast attention path is now on every family in our tree (Cyronius/OpenFlowLM-Next@a7516a1d -- the same kernel from #22 with the score scaling done on the vector unit for head dim 128 and the head vectors padded for cores owning 2-4 heads), so the O(T·P) part of prefill attention is the flat per-row kernel; what's left for a block is the O(T²) within-block part.

This is your issue, so entirely your call how (or whether) to use any of it: the projection kernel is there if you'd like it under your dispatch, and if it'd help I'm happy to write the block-mode dispatch on top of it -- but I won't start on that unless you'd like me to.

Cyronius avatar Sep 08 '26 23:09 Cyronius

Useful data — thanks for putting it up rather than letting me find out later. I recomputed your three points from the times and shapes and they're internally consistent (1.142 / 1.312 / 1.214 TFLOPS), so I'm treating them as measurements rather than as a claim.

Where the two routes stand

My GEMV-widening route caps on L1 because each token needs its own resident quantised table — tab 4608 + x 4096 + y 512 = 9216 B/token — so at K=2048 the token footprint alone exceeds the 63 KB budget by T=8, whatever the weight buffer does. Streaming the activation block through the memtile as 8 KB tiles means L1 holds one tile regardless of token count, which removes that constraint rather than routing around it.

On granite 3B at 1005 tokens, batchable term:

route
GEMV widened, T=4 (best I measured, standalone design) ~13.3 s
GEMV widened, T=2 (what actually builds in the fused layer) ~23 s
gemm_q4 at ~1.2 TFLOPS ~5.0 s

The structural point is worth more than the ratio, and I'd want anyone reading this issue later to take it: the arithmetic I opened with said batching stays free until T ≈ 100. My route died at T=4 for reasons that had nothing to do with that number — a per-token L1 residency I hadn't priced. A streamed activation block is the shape that actually reaches the regime this issue was about.

What I'm doing

Finishing my route to a working dispatch and measuring it end to end, then reassessing. The T-sweep is nearly done and a complete measured negative — "widening the GEMV caps at T=4, here is the mechanism, here is what it's worth" — is worth having as a result in its own right, not just as a step I skipped. The per-token L1 arithmetic and the mmul M-axis finding both generalise past this issue.

After that I'll write the block dispatch myself. Thanks for the offer, but this is the part I want to build rather than receive — and it's the half where the design decisions live. I'll post the comparison when my side lands.

Two findings from my side that are useful to you

A defect in c181a26 that anyone branching from it inherits. I forked there and spent a while chasing wrong q/k/v (q -0.041590 / k 0.214026 / v -0.059500) in the dense granite path — no error, dispatch completes. It is not caused by my changes: a clean worktree at c181a26 reproduces it bit for bit. Your #25–#28 stack repairs it, and the repair is #define GEMV_PER_CALL 1 → 2 in designs/dense/gemv_q4_{gy,gms}.cc. A build at 633606b is correct. So the window between #23 and #25 is poisoned for the dense path.

The insts.bin trap, which cost me the most time in that hunt. Across every build in it — correct and broken alike — insts.bin and insts.elf were byte-identical. The entire difference lived in final.xclbin. An inertness or regression check on the instruction streams therefore passes while measuring nothing; it has to be made on the artifact that carries the core programs.

Coordination: a7516a1d touches designs/dense/dx.py, which is the file I'm mid-merge on. Flagging it so we don't both rewrite the same function.

On the attention half: agreed it's the larger part past 2k, and good that the fast path is on every family now. That leaves the O(T²) within-block piece, which has to be designed against whatever the block dispatch looks like, so I'd expect it to come with that work.

vegah avatar Sep 09 '26 07:09 vegah

Result is in, and it is a negative. Posting it in full because the mechanism is the useful part and it settles which route this issue should take.

What was built, and it is correct

A T=2 batched prefill on the dense recipe, as three dispatches per layer:

  • A — batched over T: entry LayerNorm + q|k|v projections
  • B — attention: T single-token dispatches reusing the shipped T=1 machinery verbatim, position-patched via attnpos
  • C — batched over T: residual + o_proj + up|gate + down_proj

Wired into the engine behind an additive block: {t, program_a, program_b, program_c} manifest key — all five existing fixture manifests still pass manifest_test unmodified, so it is an extension, not a redesign. step() is untouched and the prompt tail falls back to it.

Correctness: bit-identical to sequential. Block vs N sequential single-token steps, three block boundaries through the full 40-layer model, distinct token ids: corr 1.00000000, maxrel 0.000e+00, argmax and top-5 identical at every point.

And it is 1.70× slower

bench-1k, 1005 prompt tokens, granite 3B, same box:

TTFT prefill
baseline, re-run same session 70.82 s 14.19 tok/s
block, T=2 120.09 s 8.37 tok/s

Reproduced at the isolated Core level (no app overhead) at 1.85–1.9×, at both 64 and 1005 tokens.

Mechanism. The fused dx runs a whole layer in one dispatch per token and reuses one xclbin for the entire prefill — zero design switches. The split runs 1(A) + T(B) + 1(C) per block, cycling three xclbin contexts every layer: at T=2 that is 2 dispatches/token/layer and ~60 context switches per token, measured at ~0.9 ms each.

I mispriced this before building it — I costed the extra dispatches at the ~200 µs dispatch floor, when the binding term is the design switch, which is the larger one at this granularity. Halving weight traffic does not pay for un-fusing.

Why a larger T cannot rescue it

The switch overhead falls as 1/T, so the re-priced crossover is T ≈ 4–8. Both doors are shut:

  • Dispatch C does not build at T=4: tab7 alone needs 73,728 B, total 102,400 B against the 64,512 B L1 budget. That is the same wall the fused design hit (101,632 B) — splitting did not move it, because C still reaches down-proj and TAB_K_MULTI = FF if stop > 3 depends on stop, not on which sections are skipped. T=3 overflows by 18,432 B.
  • T > 4 is not a legal build point at all. aie::mmul<4,8,8>'s M=4 is exactly what lets tokens share a weight-tile stream for free, and M is fixed at 4 in this hardware. Going past it is new kernel work, not configuration.

So the ceiling is T=2, bound by a per-token L1 term, and this route cannot reach the T where it would pay.

What that means for the issue

The two general results, which are the parts worth keeping:

  1. Un-fusing a design that was fused to minimise dispatch count only pays if the resulting halves can each reach a large enough T. Check each half's own L1 ceiling before trusting the weight-bandwidth argument — here both halves inherited the same binding constraint, so the split bought nothing it could spend.
  2. A per-token L1 term is what caps the widened-GEMV approach, and it is precisely what gemm_q4 does not have: streaming the activation block through the mem tile means L1 holds one tile regardless of token count.

@Cyronius — that is the comparison I said I would post. Your route is the one that can work, and this is now measured rather than argued: the thing that stops mine is structural and it is the thing yours removes. I still intend to write the block dispatch myself rather than take you up on the offer, but the kernel choice is settled and it is yours.

A separate bug, worth its own issue

Engine::find_kernels() prefers <model_dir>/open_kernels unconditionally over FLM_OPEN_KERNELS_DIR / FLM_XCLBIN_PATH whenever it exists and is complete, so any local kernel rebuild for an already-installed model is silently ignored. It produced a clean, false "no effect" TTFT reading here — two runs that were both secretly sequential — and was caught only by a diagnostic line added on purpose. I will file it separately.

One trap worth passing on

Across every build in the thirteen-stage investigation behind this, insts.bin and insts.elf were byte-identical between builds that gave correct and wrong answers. The whole difference lived in final.xclbin. An inertness or regression check on the instruction streams passes while measuring nothing.

vegah avatar Sep 09 '26 11:09 vegah