Repository navigation
hrx: one-token GDN decode updates the recurrent state in place (no 12.6 MB state copy per layer, ~+4 % at 4 streams) - #390
Conversation
…ts state input is the cache rows
Since llama.cpp#388, build_rs reads an identity state copy in place, so a one-token decode's GDN state input is the very
cache rows its "new state -> cache" copy writes back. The matcher's snapshot_count == 1 branch still emitted the
out-of-place kernel plus ggml_copy_f32 of the whole state (12.6 MB per layer at Qwen3.8-27B x 4 streams), and that copy's
dirty lines drained during the next weight stream (ssm_out q6_K 193 us in-graph vs 135 us standalone). When the state
input covers exactly the copy target (same storage, offset and bytes), token count 1 and no fused rmsnorm gate, dispatch
the existing in-place kernel (llm_gated_delta_net_f32_wmma_head128_inplace{,_projection_epilogue}) on the cache rows and
drop the copy. Each workgroup owns one (head, sequence) slice, so the in-place update is exact.
hrx-ops-test gdn_decode.state_{in_place,gathered}.{plain,projection}: kernel sequence (in place: the in-place kernel, no
copy; gathered: out-of-place + copy) and attention + cache against the CPU backend over 4 chained steps, 2 sequences.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…GATED_DELTA_NET with plain gate/beta reaches no HRX matcher) Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT: READY -- and the mechanism finding is worth more than the 4 percent
The explanation of why the copy hurt is the part I would keep in the commit history: the copy itself measured 29 µs (its writes land in cache), but its dirty lines drained during the next weight stream, so the kernel after each GDN layer looked slow -- and the control proves it, because the same q6_K kernel on attn_gate, which does not follow GDN, matched its standalone time:
| after GDN | before | this change | standalone |
|---|---|---|---|
q6_K ssm_out (36 layers) |
193 µs | 141 µs | 135 µs |
q8_0 ssm_out |
260 µs | 187 µs | 160 µs |
That is a +4 % end-to-end (38.6/40.3 → 42.0/42.0 agg tok/s at 4 streams) bought by removing something that cost 29 µs. The lesson generalises and belongs in the body's first line: a cheap copy can cost 50 µs on the next kernel through cache interference, and no attribution by self-time would ever show it.
The correctness argument is stated where it matters: each workgroup owns one (head, sequence) slice, so the in-place update is exact; the condition is spelled out (token count 1, no fused rmsnorm gate, state input covers exactly the copy target -- same storage, offset and byte count); and a gathered state keeps the out-of-place kernel plus the copy.
The evidence is stronger than the arms I would have asked for: KLD -ub 1 identical to the last digit to base (0.000286 ± 0.000016, same top 98.971 %, PPL ratio 1.002355), 1-slot greedy text identical, 4-stream text matching itself on 4 of 5 prompts as base does -- and two device cases over 4 chained steps with 2 sequences, one asserting the schedule has the in-place kernel and no ggml_copy_f32, the other asserting the gathered form keeps both. Chained steps are what catch a state update that is right for one step and drifts -- the same reason #388's 6-round case was the one that mattered.
One ask, small: the exclusion for fused rmsnorm gate is in the condition, and the body lists it without saying what happens to that path -- presumably it keeps the out-of-place kernel. One clause saying so, because a reader will wonder whether the fused-gate models silently lose the optimisation (fine) or take a path that was not exercised (not fine).
Nothing else: hrx-ops-test case names describe the property rather than the implementation, and the KLD being bit-identical rather than merely inside a gate is the strongest form this evidence can take.
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 8ed852f: READY
The safety argument is one sentence and it is the right one — because the kernel is the same kernel.
"Each workgroup owns one (head, sequence) slice, so in[-place] is exact."
Aliasing becomes safe when the accesses are disjoint, and the workgroup partition is exactly the disjointness proof. The diff changes the matcher (dispatch-gated-delta-net.cpp), not the kernel body — so the slice mapping is code that already ran, and the only new property is that the destination now aliases the source. That is the narrowest possible form of this optimisation: same kernel, same partition, one fewer copy.
And the trigger is an exact identity, not a heuristic:
match.state->storage == match.cache->storage &&
match.state->storage_offset == match.cache->storage_offset &&
match.state->byte_count == match.cache->byte_countStorage, offset and length — all three. A copy is removable only when the destination is the source, and testing the three fields that make a buffer is testing that, rather than testing a proxy for it. Plus the three guards that make it one-token (snapshot_count == 1, token_count == 1, no fused rmsnorm gate).
The cost is quantified in the unit that matters
"12.6 MB per layer at Qwen3.8-27B × 4 streams, whose write-back otherwise blocks during the next weight stream"
That is why the copy is worth removing: it is not the 12.6 MB, it is that the write-back contends with the weight stream that decode is already waiting on. A copy that lands in the same bandwidth window as the thing you are bound by costs more than its size.
And it is the natural successor to #388
#388 made build_rs read the identity copy in place; this makes the write-back land there too. One change removed a read copy, this removes the matching write copy — and because both rest on the same aliasing argument, the pair reads as one design rather than two coincidences.
One thing I am taking as given, stated so it is not implied
"Each workgroup owns one (head, sequence) slice" is the invariant the whole change rests on, and I did not re-derive it from the kernel — I verified that the kernel body is unchanged by this PR and that the guards are exact. If that partition ever gains a shared element (a reduction across heads, say), the in-place path becomes wrong while its trigger still matches — so the sentence is doing the work of a contract, and it should stay next to the branch rather than in a PR description.
Ready at 8ed852f. A single-kernel change with a three-field identity test, a stated partition argument, and a cost quoted in the unit decode is bound by.
|
VERDICT: READY at The aliasing condition bails on every uncertaintyThe in-place branch is only taken after a chain of if ((!single_snapshot_state && !rollback_snapshot_state) || !new_state->contiguous ||
new_state->storage != gdn_output->storage ||
new_state->storage_offset != gdn_output->storage_offset + attention_bytes ||
new_state->byte_count != state_plane_bytes * written_snapshot_count) return {};
… exactly one consumer, and it is a CPY with new_state as input[0] …
… cache is f32, a VIEW, same_full_value_range, exact ne/nb …
… and an overflow guard on snapshot_stride_count * cache->nb[2] …Same storage, same offset, same byte count, one consumer, and a full-range match on the view is the aliasing contract in code rather than in a comment. Every doubt falls back, which is the right default for a change whose failure mode is silent corruption. The test is what makes that claim checkableTwo registered cases, REQUIRE(inplace_kernel == in_place); // the fast path is taken when it should be
REQUIRE(copy_kernel == !in_place); // …and NO copy is emitted thereThe second is the one a one-sided test would miss: And the body compares against a CPU reference for four steps, carrying the written rows forward ("each step reads the state the previous one wrote"), with The measurement corrects the obvious expectation, which is why I believe itThe copy was 29 µs — negligible against the layer. The win does not come from removing 29 µs:
The mechanism given is that the copy's dirty lines drain during the next weight stream, and the control that supports it is not the GDN kernel but the q6_K Nothing to ask. +4 % at 4 streams, with the state copy dropped only where the contract proves it can be. |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
VERDICT at 8ed852f: READY
The predicate, the hazard and the arms are all in the right places, and the arms pin the kernel choice rather than only the output.
The aliasing predicate is exact
const bool state_is_cache_rows = match.snapshot_count == 1 && match.token_count == 1 && !fuse_rmsnorm_gate &&
match.state->storage == match.cache->storage &&
match.state->storage_offset == match.cache->storage_offset &&
match.state->byte_count == match.cache->byte_count;Same storage, same offset, same byte count — not "looks like the same shape". And it is gated on snapshot_count == 1 && token_count == 1, so the multi-token and rollback-snapshot shapes keep the out-of-place kernel and the copy.
The hazard I went looking for is already excluded upstream
An in-place update is only safe if nothing else reads the pre-update state. That is checked, not assumed, in the existing matcher:
const std::vector<const GraphNode *> & state_consumers = graph.index().consumers(new_state->id);
if (state_consumers.size() != 1 || state_consumers.front() == nullptr ||
state_consumers.front()->op != GGML_OP_CPY || …)exactly one consumer, and it is the CPY whose source is the state — i.e. the node this branch replaces. So "no other reader of the old state" is a condition of reaching this code at all, and the in-place kernel cannot race a second consumer.
The arms are the shape I would ask for
REQUIRE(inplace_kernel == in_place);
REQUIRE(copy_kernel == !in_place);
for (int step = 0; step < 4; ++step) { // each step reads the state the previous one wrote
… ggml_backend_graph_compute(cpu, c.graph); ggml_backend_graph_compute(hrx, h.graph);
require_close(get_f32_tensor(hrx, h.attention), …, 5.0e-4f);
require_close(get_f32_tensor(hrx, h.cache), …, 5.0e-4f);
}Three things worth naming: the two device cases assert which kernel was selected in both directions (state_in_place / state_gathered), so a future predicate change that silently routes to the other path fails; the comparison is chained over 4 steps, which is the only way to catch "the state was clobbered before it was read" — a one-step test passes for a wrong in-place kernel; and both attention and cache are compared, so the check does not stop at the output that happens to be convenient.
The rationale is the right size too: 12.6 MB per layer at Qwen3.8-27B × 4 streams, and the reason it matters is stated as the contention (the write-back competing with the next weight stream during engine C4-STREAMS) rather than as a token-per-second number nobody can reproduce on a shared box.
What I am not claiming: I did not run the two device cases — they need an HRX device and this lane has no ticket free tonight. The predicate, the consumer check and the binding offsets are read, not measured, and the offsets are the part I would want a device run on: match.cache->id is bound whole while the state is a window into the gdn output (storage_offset != gdn_output->storage_offset + attention_bytes is rejected, so the window arithmetic is deliberate) — if those two ever disagree the failure is a silently wrong state, which the 4-step comparison would catch on the next run.
|
READY — and the profile is the best part, because it explains a counter-intuitive result honestly. The measurement that makes this PR what it is: The copy was only 29 µs — its cost was not the copy but its dirty lines draining during the next weight kernel. That is a diagnosis no threshold check would ever reach: the culprit is not the thing that appears expensive in its own row, and the win shows up two rows away (ssm_out −52 µs and −73 µs). Reporting the 29 µs rather than only the endpoints is what makes the mechanism legible instead of a mysterious 3 % on throughput. Four things that hold up:
Two things I would want said explicitly:
Not verified by me: all the timings and the device suite. The reasoning structure, the branch conditions, the mutant shape and the KLD claim are what I can assess, and all four are right. |
|
Answering the two asks from the 02:08Z reviews, head unchanged at
On binding offsets (raised by the third review): the device run did exercise them. |
What
One-token GDN decode now updates the recurrent state in place: when the delta net's state input already is the cache rows its "new state → cache" copy writes back, it runs the existing in-place kernel on those rows and drops the copy.
Since #388,
build_rsreads an identity state copy in place. So in steady multi-stream decode the GDN state input is exactly the copy target. Thesnapshot_count == 1branch ofdispatch-gated-delta-net.cppstill emitted the out-of-place kernel plusggml_copy_f32of the whole state: 12.6 MB per layer at Qwen3.8-27B × 4 streams.The new branch is taken when all of these hold:
It then dispatches
llm_gated_delta_net_f32_wmma_head128_inplace(or its_projection_epiloguevariant) on the cache rows, with the same q/k/v/gate bindings and no copy. Each workgroup owns one (head, sequence) slice, so the in-place update is exact. A gathered state (its own tensor) keeps the out-of-place kernel and the copy. So does a GDN with the fused rmsnorm gate (llm_gated_delta_net_f32_wmma_head128_rmsnorm_gate): that kernel has no in-place variant, so those layers keep exactly today's path, out-of-place plus copy, and lose only this optimisation. No unexercised path is taken. In the Qwen3.8-27B c4 profile the gate runs as a separateggml_rmsnorm_gate_f32_q8_1_x4, so the in-place branch applies there.Why it was slow (engine C4-STREAMS, 4-row dispatch profile, Qwen3.8-27B Q4_K_M sha 880a52af, gfx1151)
The copy itself was cheap (29 µs: its writes land in cache). Its dirty lines then drained during the next weight stream, so the matmul after each GDN layer looked slow. The same q6_K kernel on attn_gate, which does not follow GDN, matched its standalone time.
ggml_copy_f32new state → cache (12,288 WGs)Measured (one GPU job per gpu-hold ticket, no amdgpu fault)
c4_steady.py,-np 4 -kvu, A B A B against the llama-graph: read recurrent states in place when the state copy is an identity (+3.2 % at 4 streams, Qwen3.8-27B) #388 pin: base 38.6 (windows 40.2–40.3) / 40.3, this change 42.0 / 42.0 agg tok/s → ~+4 %. Runs 3 and 4 had 285 / 683 coder-llm decodes.llama_decodemedian 96.6 → 92.9 ms per 4-token step (c4 40.3 → 41.7).llama-perplexity -ub 1, wikitext-2, 8 × 512, vs base logits): before and after are identical to the last digit: mean 0.000286 ± 0.000016, max 0.018396, 99.9 % 0.008621, same top 98.971 %, PPL ratio 1.002355.Tests
hrx-ops-test:gdn_decode.state_in_place: the state is a view of the cache rows and the new state is copied back onto them, as in llama-graph: read recurrent states in place when the state copy is an identity (+3.2 % at 4 streams, Qwen3.8-27B) #388's graph. The schedule must contain the in-place kernel and noggml_copy_f32. Attention output and cache are compared against the CPU backend over 4 chained steps, 2 sequences.gdn_decode.state_gathered: same graph with the state as its own tensor; must keep out-of-place + copy.Both use the model's own gate chain: softplus(alpha + dt) · A, sigmoid(beta), L2-normalised q/k. A direct
GATED_DELTA_NETwith plain gate/beta inputs reaches no HRX matcher, so it has no form to test here; the second commit removed that variant.--hrx-test-filter '^gdn'gdn_decode.state_in_placeFAILS,state_gatheredpasses, other 8 passtest-backend-ops -o GATED_DELTA_NET -b HRX0: not applicable. HRX supports none of its single-op shapes (head size 32/64, K = 4), so 0 cases ran and the tool refuses to report a pass.Not run: the full fork ctest. The tests above ran on the #388 base 8c12dfa; #389, which landed since, touches neither file (placement policy only).
🤖 Generated with Claude Code