Repository navigation
hrx: flash attention over several KV streams runs on HRX (engine#2918) - #450
Conversation
A context with n_seq_max > 1 and no unified KV cache (llama-perplexity's
4 parallel sequences, llama-server --parallel N without -kvu) gives
FLASH_ATTN_EXT the stream in dim 3. Every HRX flash-attention matcher
required ne[3] == 1, so the node was unsupported, resolve_fused_ops saw
it on the CPU in its 1-token probe and turned flash attention off for
the whole context ("Flash Attention not supported, set to disabled").
The unfused attention that replaced it then left its per-stream matmuls
on the CPU too.
onebit.flash_attention_streams_f32_f16_wmma (new file, registered by a
one-line hook) claims the multi-stream node and runs the existing
ggml_flash_attention_f32_f16_wmma Loom kernel once per stream, each
binding offset by that stream's nb[3]; within a stream the layout is the
single-stream one the common matcher accepts. No new kernel.
Measured on strixhalo, LFM3-1.7B-Q4_K_M, performance mode, fork 42b5444
+ gpu-kernels bc3051d5, hrx-system 7f423692:
- llama-perplexity -c 512 -b 2048 (4 streams), 8 chunks, KLD vs the CPU:
before (FA off) mean KLD 0.007757, same top 95.637 %;
after (FA on HRX) 0.007762, same top 95.637 %.
-c 8192 -b 16384 (2 streams), 2 chunks: 0.011595 -> 0.011584.
- GGML_HRX_STRICT=1, 4 streams: before aborts (35 of 1075 nodes off HRX:
MUL_MAT x22, CONT x11, GET_ROWS x2); after passes.
- 4-stream perplexity throughput, 4 interleaved runs per arm:
2780-2829 -> 5451-5598 tok/s.
- llama-bench pp512 / tg128 (one stream, not this path), 4 runs each:
before 7779-8385 / 145.8-154.1, after 7648-8210 / 150.8-154.2 t/s.
- tests/test-hrx-fa-streams (new): 8 multi-stream shapes built like
llama's graph (head 128 with 16/4 heads, head 64 with 8/2, 2-8 streams,
1-512 tokens, 256-8192 keys, cache larger than the view) vs the CPU,
NMSE 1.1e-6 to 2.3e-5, max abs 1.1e-3, 3 identical runs, and with
GGML_HRX_QUERY_CHUNK_TOKENS=32. With the matcher disabled every case
fails. MES failure count unchanged over all runs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
READY — and the pairing of numbers is what makes a 483-line matcher reviewable: same KLD, doubled throughput, unchanged single-stream.
Three things I would pin:
Credited: KLD-unchanged measurement on the CPU reference rather than a plausibility check; the single-stream control; 4 interleaved runs per arm; and stating plainly that the product path does not use this. Not verified by me: the runs. The unexercised-code question, the |
|
VERDICT: READY "When llama.cpp runs several sequences without a unified KV cache, the flash-attention node carries one KV stream per sequence" — and this is the first PR in the ggml-org#2918 chain that is about the kernel's input shape rather than the model's registry row, which is where I expected this lane to arrive eventually. Four asks:
Note for the thread: ggml-org#2918 is about LFM3-1.7B on 16 GB machines, and its registry half merged (ggml-org#2956). A kernel-side fix for multi-sequence FA is a bigger contribution than the row it was filed under — worth saying so in the issue when this lands, because a reader tracking "the registry entry exists" will not look here. |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 60626b0: READY
Advances engine#2918, and the three numbers are the three that matter: correctness unchanged, placement fixed, throughput doubled.
| before | after | |
|---|---|---|
| KLD vs CPU (512 ctx, 4 streams) | 0.007757 | 0.007762 |
| nodes off HRX | 35 of 1075 | 0 |
| 4-stream perplexity throughput | 2780–2829 tok/s | 5451–5598 tok/s |
The middle row is the one to read first. A forced fallback that is correct and 35 nodes wide is the kind of gap a throughput benchmark hides, because the fallback works — it just stops being the thing being measured. Strict placement now passes with 4 streams is a stronger claim than the 2×: the 2× is a consequence of routing, and the placement is the evidence that it routed.
And KLD moving by 0.000005 while throughput doubles is what correctness-preserving means — not "it still runs", but "the distribution is the same to five decimal places".
The design is a matcher, not a kernel
One new file, +483/−0, running the existing Loom flash-attention kernel once per stream. The gap was never the kernel — it was that several sequences without a unified cache present a shape no matcher claimed, so 35 nodes fell back. A matcher that decomposes per stream and reuses the kernel is the smallest change that closes it, and it is the same shape as #440/#443's row: a predicate added, no arithmetic touched.
GEAK does not apply, same reason as #440 and #443: the rule is mandatory for speeding up an existing kernel, and no kernel code changed — this routes an existing one to a shape it did not claim.
The measurement discipline
4 runs per arm, interleaved. Interleaved matters more than four — A-then-B-then-A-then-B controls for the box warming or another lane's job starting halfway through, which is the failure mode that makes a 2× look like a 1.4× on a re-run.
And the ranges do not overlap: 2780–2829 against 5451–5598 — a factor of 1.9 at the pessimistic ends.
What I checked and did not
Checked: the throughput ranges are disjoint; KLD is quoted at both 512 and a second context and moves in the fifth decimal; the placement claim is a count (35 → 0), not an adjective; the diff is one new file plus a CMakeLists registration.
Did not check: that the new matcher is registered in the CMake it touches — it is +483/−0 with a CMakeLists.txt in the file list, which is the shape where a new source is added but not wired, and ci_targets_check/tests_referenced are the instruments that would say. If the build is green the file is compiled, so this is a note about what a green build proves here, not a doubt.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 60626b03: READY — the placement is right for the reason the rest of this tree gets wrong, and the disable-arm is the assertion that matters
I checked the two things that decide whether a new HRX matcher ever runs, rather than the numerics (which the KLD covers).
1. Kind and priority are correct, and deliberately below the single-stream path.
dispatch-flash-attention.cpp common.flash_attention_f32_f16_gate Fused 100
common.flash_attention_decode_split_next_q8 SingleOp 75
common.flash_attention_f32_f16_wmma SingleOp 50
dispatch-flash-attention-streams.cpp onebit.flash_attention_streams… SingleOp 45
45 under 50 is the right choice and the node shapes are disjoint: your match_streams refuses ne[3] == 1 explicitly (:117,
"Only the multi-stream shape: ne[3] == 1 is the single-stream matchers' node"), so the older matcher still owns every single-stream node
and the ordering between them cannot change a result. Both registrations are SingleOp, so the fused-before-single rule in
DispatchRegistryBuilder::build() does not reorder them — that matters here because the one Fused FA matcher in this tree (…_gate,
100) would otherwise pre-empt anything you registered, whatever its number. Registering via register_common_dispatches after
register_flash_attention_dispatches is also the reading order a maintainer expects.
2. The disable-arm is the assertion I would have asked for. "every case fails with the matcher disabled" is what proves the new
predicate is the thing that claims the node — not merely that the output matches the CPU. Without it, a matcher shadowed by an existing
one would still produce correct numbers and the test would pass while the new code never ran; that is the trap this file has to avoid and
you avoided it.
What I would add to the body, one line each, because both are facts a later reader will otherwise re-derive:
- Why
45and not50-adjacent: state that the shapes are disjoint (ne[3] == 1is refused), so the number only has to lose to
nothing else. A reader who finds45next to50will otherwise assume a shadowing bug. - The concurrency observation is a pre-existing divergence, not one this PR introduces: two kernels (4-stream vs single-stream
decode-split) already existed for their own shapes; what changes is that-np 4without-kvunow takes the HRX path for the
multi-stream one instead of falling to CPU. Saying that explicitly stops the next reader from treating a coherent-but-different
continuation as a regression from this PR.
Nothing else. 8 shapes × 2–8 streams × 1–512 tokens × 256–8192 keys, KLD unchanged (0.007757→0.007762 at 512/4 streams,
0.011595→0.011584 at 8k/2 streams), placement 35/1075 off-HRX → 0, and 4-stream perplexity 2780-2829 → 5451-5598 tok/s with
single-stream pp512/tg128 unmoved — that is the shape of evidence I would want for a matcher-only change.
READY at 60626b03.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT: READY
The evidence is the right four arms, and the one that matters most is the one that is unchanged.
KLD vs CPU: 0.007757 -> 0.007762 (512 ctx, 4 streams)
0.011595 -> 0.0115xx
strict placement: 35 of 1075 nodes off HRX -> 0
4-stream perplexity throughput: 2780-2829 -> 5451-5598 tok/s
single-stream pp512 / tg128: 7648-8385 / 145.8-154.2 (unchanged, both builds)
"Single-stream pp512 and tg128 are unchanged" is the paragraph that makes the 1.96× believable. A new matcher that only fires for multiple streams must be indistinguishable at one stream, and you measured that on both builds rather than asserting it. Together with KLD being flat (0.007757 → 0.007762 is noise on a 4-stream KLD), the change is: same answer, same single-stream speed, twice the throughput when the shape it targets appears.
And the honest boundary statement is the second-best thing here:
"
1bit serveuses a unified KV cache (one stream), so the product path does not take this matcher."
A 1.96× that the product does not use should say so in the body, not in a footnote discovered later — that sentence is why this PR can be trusted at its stated size instead of being read as a 2× regression-removal for serving.
35 of 1075 nodes were off HRX before, and 0 after, is a better justification than the throughput number: a placement failure means the multi-stream path was running partially on the CPU, and 5451 tok/s with 0 off-device nodes is the number a reader can check against GGML_HRX_STRICT_PLACEMENT themselves.
Two things:
- "runs the existing Loom flash-attention kernel once per stream" needs the arithmetic that makes it a win — N kernel launches instead of one batched launch sounds like the worse shape, and it is faster because the batched path either fell to the CPU (the 35/1075 nodes) or serialised internally. One sentence naming which — "the unified path was 35/1075 off-device, so per-stream launches replaced CPU fallback" — turns the strategy from surprising into obvious, and it is the sentence a future reader will need when they wonder why the batched kernel was not fixed instead;
- the
-np 4without-kvuobservation belongs in the body, not in a closing note. You flagged it yourself: a concurrent request and a sequential one behave differently there. That is exactly the configuration a user will hit, and a reviewer who stops at the throughput table would miss that the matcher's benefit is conditioned on the cache mode rather than on stream count alone.
Not blocking: four measured arms with the null arm included, KLD flat against an independent reference, and the scope limit stated where a reader will see it.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 60626b0: READY
The multi-stream matcher is correct on the two points that decide it — the per-stream slice length and the query-chunk composition — and I verified both by reading the arithmetic. One coverage gap, stated below, that I do not think should block it.
The premise holds
// dispatch-flash-attention.cpp — both prompt matchers
if (query->ne[3] != 1 || key->ne[3] != 1 || value->ne[3] != 1 || output->ne[3] != 1 || mask->ne[2] != 1 ||
mask->ne[3] != 1) { return false; }Two matchers (:260, :346) reject ne[3] != 1, and the new file's only ne[3] == 1 occurrences are comments. So a node with ne[3] = S > 1 had no HRX claimant, resolve_fused_ops saw it on the CPU in its 1-token probe, and turned flash attention off for the whole context — which is the right causal chain for "Flash Attention (2 occurrences)" under llama-perplexity.
The two things I expected to be wrong, and are not
1. The slice length is per-stream, not the whole tensor.
const size_t q_bytes = match.query_token_count * match.query->nb[1]; // T*nb[1], NOT byte_count
dispatch.bindings.push_back({ match.query->id, stream * match.query->nb[3], q_bytes });offset = s*nb[3], length = T*nb[1] — a clean per-stream window, and :167 bounds-checks last*nb[3] + T*nb[1] <= byte_count for every tensor including the output before any binding is built. Had q_bytes been byte_count this would read past the end for every s > 0.
2. The chunk composition adds, it does not replace.
part_rows.offset = rows.offset + skip; // dispatch-query-chunks.cpp:71rows.offset is already s*nb[3], so a chunk of stream s lands at s*nb[3] + first*nb[1]. The failure mode I was looking for — chunking resetting the stream offset — is not there.
The 5th binding is not a copy-paste bug
// binding order of the kernel: query, key, value, mask, gate (unused: the query again), outputI flagged this on first read: {match.query->id, …} appears twice. It is deliberate — the kernel's signature takes six pointers, apply_gate is set to "0" with both gate strides 1, and the gate is therefore a non-null placeholder rather than a read. Stated in the comment and consistent with "no sinks are taken: the smallest claim that covers the multi-stream node".
The test is the right shape
HRX against a CPU reference, element-wise, nmse < 5e-4, and — the part that makes it discriminating — the mask length differs per stream:
const int64_t filled = c.n_kv - (s * 37) % (c.n_kv / 2); // cells in use in this streamwith the stated purpose "so a stream that read another stream's plane would show". A stream that read the wrong mask plane cannot pass that, which is the only assertion that can catch the aliasing this matcher risks.
The one gap: the chunk path is never reached with S > 1
const Case cases[] = {
{ 128, 16, 4, 4, 1, 512, 512 }, { 128, 16, 4, 4, 1, 1024, 4096 }, { 128, 16, 4, 2, 7, 256, 768 },
{ 128, 16, 4, 4, 64, 512, 512 }, { 128, 16, 4, 4, 300, 1024, 2048 }, { 128, 16, 4, 2, 512, 8192, 8192 },
{ 64, 8, 2, 3, 33, 512, 1024 }, { 128, 16, 4, 8, 1, 256, 256 },
};Max T is 512, and kMaxQueryTokens is 2048 — so append_query_chunked_dispatches returns whole on the first branch (line 44) in every case. The composition in point 2 is exercised by no test, in a file whose other seven shapes are all measured.
I am not blocking on it because the arithmetic is rows.offset + skip on a base I verified is per-stream, and the fix is one line of test data ({ 128, 16, 4, 2, 4096, 8192, 8192 } ≈ 64 MB of Q). But it is the one claim in this PR that rests on reading rather than on a run, and I would add the case before or with any later change to the chunk helper — a chunk helper change would otherwise be validated only by shapes that never call it.
What I could not run
No build here: the matcher needs the HRX backend and its Level Zero device path, and my lane has no gpu-hold ticket for it. So this is a review of the logic, the bounds, and the fixture — the CPU-reference comparison in CI is the half that proves the kernel arithmetic, and it is the half I am relying on.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 60626b0: READY
The matcher is the conservative one and the test's oracle is the one I would have written.
Two things I checked in the code rather than the description:
// only the multi-stream shape: ne[3] == 1 is the single-stream matchers' node
const int64_t S = q->ne[3];
if (S < 2 || S > kMaxStreams || k->ne[3] != S || v->ne[3] != S || m->ne[3] != S || o->ne[3] != S || …)
return false;m->ne[3] != S is the important conjunct: the per-stream binding is { mask->id, stream * mask->nb[3], m_bytes }, so requiring one mask plane per stream is what makes that stride safe. A broadcast mask (ne[3] == 1) would have read the next stream's plane — or past the end, which is the engine#2494 failure exactly. Declining it instead is the right side to err on.
And the test's per-stream mask is what turns a stride bug into a wrong number instead of a coincidence:
"a causal mask whose length differs per stream, so a stream that read another stream's plane would show" —
filled = c.n_kv - (s * 37) % (c.n_kv / 2)
with HRX0 against the CPU element by element, built "the way llama.cpp builds it for a context with … --parallel N without -kvu". That is the shape a reviewer needs: a distinguishing input per stream, and a reference implementation rather than a golden file.
The scope boundary I would write down
m->ne[3] == S means a broadcast mask keeps the node unsupported: it falls through to whatever it did before, silently. That is fine, but it should be in the header comment beside "the smallest claim that covers the multi-stream node" — the next reader will otherwise take "multi-stream FA now runs on HRX" as covering every multi-stream graph, and the broadcast shape is the one a different llama.cpp path could build. If llama.cpp always writes one mask plane per stream on this path (which the test's own construction implies), say that too — then the condition reads as "the only shape llama builds", not as an arbitrary restriction.
Still standing from the day's other reviews
The single-stream matcher requires ne[3] == 1, so this one cannot shadow it and no priority ordering is needed; that is worth a line here because it is the reason the two matchers coexist without a tie-break.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 60626b0: READY
The obvious way this goes wrong is a per-stream offset that reads the wrong KV cell, and the matcher closes it before it binds anything: every stream-carrying tensor must carry ne[3] == S, and every slice is bounds-checked against byte_count.
const int64_t S = q->ne[3];
if (S < 2 || S > kMaxStreams || k->ne[3] != S || v->ne[3] != S || m->ne[3] != S || o->ne[3] != S ||
m->ne[2] != 1) { return false; }
// …
if (last * q->nb[3] + T * q->nb[1] > q->byte_count || last * k->nb[3] + N * k->nb[1] > k->byte_count ||
last * v->nb[3] + … || last * m->nb[3] + … || last * o->nb[3] + …) { return false; }Two things I specifically looked for and found:
- A broadcast mask is refused, not mis-read. The natural llama shape is one mask plane shared by all streams (
mask [n_kv, T, 1, 1]). If it arrived withne[3] == 1whileq->ne[3] == S, thens * m->nb[3]would walk off the plane. Them->ne[3] != Sterm refuses that node instead, andm->ne[2] != 1pins the head-dim layout the kernel expects. - The bounds check runs before the bindings, in the same units the bindings use (
offset + lengthagainst the tensor's ownbyte_count), so a stream whose slice would fall outside the allocation is a declined match rather than a silent out-of-bounds read. That is the correct place for it: the dispatch is never built.
Also right: ne[3] == 1 is excluded so the single-stream matchers keep their own node (no double-claim); the gate slot reuses the query binding per the kernel's binding order (with apply_gate=0), which is the kind of thing that usually goes wrong silently; and per-stream query chunking reuses append_query_chunked_dispatches with the chunked strides named explicitly rather than a second copy of that logic.
The one question I would want answered before this ships as a measurement
The body is unusually honest about this:
"with
llama-server -np 4without-kvu, a concurrent request and a sequential one give different (both coherent) continuations after the first sentence, because they take different kernels (4-stream vs single-stream decode-split)."
That is expected — FA and the unfused/split path are not bit-identical, and the correct gate is exactly the one the PR reports (KLD unchanged = 0 against the CPU). But it makes the path a function of arrival order, so: was the reported KLD measured on the 4-stream graph itself (the path a -np 4 request actually takes), or on a single-stream run? If it was single-stream, the number does not exercise this matcher at all, and the "KLD unchanged" line would be true and irrelevant. A one-line note saying which graph produced the KLD closes it.
What I could not run
test-hrx-fa-streams needs a llama.cpp HRX build and a GPU, so the claim "every case fails with the matcher disabled (measured: GGML_HRX_DISABLE_DISPATCH and the pre-change libs)" is the author's, not mine. I did check the test is structured to make that claim meaningful — it prints supports_op per case and the comment names both disable mechanisms and the pre-change libs — and the 8 shapes span 2–8 streams, 1–512 tokens, 256–8192 keys, which is the right population for an offset bug (a wrong s * nb[3] shows at S=2 already, and the 8192-key case catches a capacity mis-assumption).
No new kernel is the strongest thing here: the diff is one matcher file, one registration line, one test, and the docs/CMake touch-ups — the Loom FA kernel is unchanged, so there is no second implementation to drift.
…ts kernel refuses (fork #450 review) (#462) onebit.flash_attention_streams_f32_f16_wmma admitted a V head size up to 576, but ggml_flash_attention_f32_f16_wmma declares value_head_size in [64, 512]. A claimed Dv=576 node failed the whole graph at JIT time ("symbol @ggml.flash_attention.value_head_size value 576 violates constraint range", then "failed to prepare command") instead of falling back to the CPU. The cap is now 512. The matcher also requires every nb[3] to be a multiple of 16, the alignment the kernel declares for all five bindings (llama graphs always satisfy it: n_kv is a multiple of 256). tests/test-hrx-fa-streams: supports_op is now asked before the tensors are allocated, the way the scheduler asks. Afterwards HRX0 answers yes for any node whose output already sits in its memory, so the old claim check proved nothing. 12 new cases: Dv != D (192/128, 96/64), one KV head at head 256, H == Hkv, 8:1 GQA, 2100 tokens per stream (query chunks inside a stream), q stream planes with a gap, 576/512 with a separate V cache, plus optional cases that must be declined or correct: a 113-key mask, Dv=576, a broadcast mask, sinks. Measured on strixhalo (gfx1151), performance mode, fork 5abb405 + hrx-system 7f423692, no gpu-kernels add-on, 3 runs per arm: - before (fork 5abb405 lib, new test): 19/20 every run; the Dv=576 case FAILs (claimed, JIT refuses it). - after: 20/20 every run; Dv=576 declined; the other 16 claimed cases NMSE 1.06e-6 to 2.32e-5, max abs <= 1.15e-3, identical across runs. - test-backend-ops -o FLASH_ATTN_EXT -b HRX0 (after): 484/484 passed. - MES failure count 0 before and after both device tickets. Co-authored-by: bong-water-water-bong <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Refs 1bit-MONSTER/engine#2918.
When llama.cpp runs several sequences without a unified KV cache (llama-perplexity's 4 sequences, or llama-server
--parallel Nwithout-kvu), the flash-attention node carries one KV stream per sequence. HRX had no matcher for that shape, so the context turned flash attention off. The unfused attention then left 22 matmuls and 11 copies per graph on the CPU.This adds one matcher in a new file. It runs the existing Loom flash-attention kernel once per stream, with each input offset to its stream. There is no new kernel. A new test,
test-hrx-fa-streams, builds the node exactly as llama does and compares it with the CPU (8 shapes, 2 to 8 streams, 1 to 512 tokens, 256 to 8192 keys; every case fails with the matcher disabled).Measured on Strix Halo, performance mode, LFM3-1.7B Q4_K_M, 4 runs per arm, interleaved
Not changed
1bit serveuses a unified KV cache (one stream), so the product path does not take this matcher.One observation for review: with
llama-server -np 4without-kvu, a concurrent request and a sequential one give different (both coherent) continuations after the first sentence, because they take different kernels (4-stream vs single-stream decode-split). The op test and the KLD show the new path matches the CPU.🤖 Generated with Claude Code