Skip to content

hrx: one-token GDN decode updates the recurrent state in place (no 12.6 MB state copy per layer, ~+4 % at 4 streams) - #390

Merged
bong-water-water-bong merged 2 commits into
1bit/hrx-vulkan-patchedfrom
cl-1051/c4-gdn-inplace
Nov 15, 2026
Merged

bong-water-water-bong merged 2 commits into
1bit/hrx-vulkan-patchedfrom
cl-1051/c4-gdn-inplace

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 15, 2026 •

Copy link
Copy Markdown

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_rs reads an identity state copy in place. So in steady multi-stream decode the GDN state input is exactly the copy target. The snapshot_count == 1 branch of dispatch-gated-delta-net.cpp still emitted the out-of-place kernel plus ggml_copy_f32 of the whole state: 12.6 MB per layer at Qwen3.8-27B × 4 streams.

The new branch is taken when all of these hold:

  • token count is 1 and there is no fused rmsnorm gate;
  • the state input covers exactly the copy target: same storage, offset and byte count.

It then dispatches llm_gated_delta_net_f32_wmma_head128_inplace (or its _projection_epilogue variant) 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 separate ggml_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.

after GDN (median, in-graph) before this change standalone bench
GDN kernel 101 µs 97.7 µs (in place)
ggml_copy_f32 new state → cache (12,288 WGs) 29 µs, every GDN layer not emitted in decode (96 left: non-decode graphs)
q6_K ssm_out (36 layers) 193 µs 141 µs 135 µs
q8_0 ssm_out 260 µs 187 µs 160 µs

Measured (one GPU job per gpu-hold ticket, no amdgpu fault)

  • 4 streams, 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.
    • Server-side per-step timing (separate run): llama_decode median 96.6 → 92.9 ms per 4-token step (c4 40.3 → 41.7).
  • Decode-path KLD (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.
  • 1-slot greedy text, 2 × 256 tokens: identical to base.
  • 4-stream greedy text: this change matches itself on 4 of 5 prompts, as base matches itself (4-row decode is not run-to-run reproducible here).

Tests

hrx-ops-test:

Both use the model's own gate chain: softplus(alpha + dt) · A, sigmoid(beta), L2-normalised q/k. A direct GATED_DELTA_NET with 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'
this change 10/10 PASS
mutant (new branch disabled) gdn_decode.state_in_place FAILS, state_gathered passes, other 8 pass

test-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

bong-water-water-bong and others added 2 commits November 14, 2026 22:02
…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 bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_count

Storage, 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.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT: READY at 8ed852f — the precondition is exhaustive, the test would catch aliasing rather than assume it away, and the measurement explains a win that a naive reading of the cost would have got wrong.

The aliasing condition bails on every uncertainty

The in-place branch is only taken after a chain of return {} guards, each of which sends the node back to the out-of-place path:

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 checkable

Two registered cases, gdn_decode.state_in_place and gdn_decode.state_gathered, and each asserts two things:

REQUIRE(inplace_kernel == in_place);      // the fast path is taken when it should be
REQUIRE(copy_kernel    == !in_place);     // …and NO copy is emitted there

The second is the one a one-sided test would miss: inplace_kernel == in_place alone passes happily with a stray ggml_copy_f32 still in the graph.

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 require_close on both attention and cache at 5e-4. An in-place update that clobbered a slice another step consumes would compound across those steps and fail there — so the aliasing property is tested, not merely argued from "each workgroup owns one (head, sequence) slice".

The measurement corrects the obvious expectation, which is why I believe it

The copy was 29 µs — negligible against the layer. The win does not come from removing 29 µs:

after GDN (median, in-graph) before this change standalone
GDN kernel 101 µs 97.7 µs
ggml_copy_f32 state → cache 29 µs, every layer not emitted in decode
q6_K ssm_out (36 layers) 193 µs 141 µs 135 µ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 ssm_out after it, which moved to within 4 % of its own standalone time — plus "the same q6_K kernel on attn_gate, which does not follow GDN, matched its standalone time". That is a comparison chosen to separate the mechanism from a generic speedup, and it is the reason a −52 µs effect from a 29 µs copy is credible rather than a measurement artefact.

Nothing to ask. +4 % at 4 streams, with the state copy dropped only where the contract proves it can be.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@/tmp/v390.md

@bong-water-water-bong

Copy link
Copy Markdown
Author

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:

ggml_copy_f32 new state → cache   29 µs, every GDN layer   →  not emitted in decode (96 left: …)
q6_K ssm_out (36 layers)          193 µs                   →  141 µs   (standalone bench 135 µs)
q8_0 ssm_out                      260 µs                   →  187 µs   (standalone 160 µs)

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:

  • The branch conditions are structural, not heuristic: token count == 1, no fused rmsnorm gate, and the state input covering exactly the copy target — same storage, offset and byte count. Byte-count equality is the clause that makes an in-place update safe against a partially-overlapping view, and it is the one a "same storage" test alone would miss.
  • The paired tests are the right pair. gdn_decode.state_in_place asserts the state is a view of the cache rows and the new state is copied back onto them; gdn_decode.state_gathered asserts the same graph with a separate tensor still goes out-of-place + copy. The second is the control that keeps the fast path from being taken when it must not be.
  • The mutant is on the new branch and fails exactly one case: state_in_place FAILS, state_gathered passes, other 8 pass. That is the shape a mutant should have — it proves the case pins the branch rather than the fixture.
  • KLD -ub 1 is identical, not merely close, and 1-slot greedy text is identical. For an in-place state update that is the claim that matters, because the failure mode is a stale or double-applied state, which shows up as divergence within a few tokens.

Two things I would want said explicitly:

  1. test-backend-ops -o GATED_DELTA_NET: "not applicable — HRX supports none of its single-op shapes." That is a fine answer, and it is also the reason the two hrx-ops-test cases carry the whole weight here. Worth one clause on what would be exercised if HRX ever supports a single-op GDN shape, so this doesn't become a permanent blank.
  2. #389 landed after your test base (8c12dfa63) and touches the placement predicates. Your suite ran on the earlier base — so say whether a re-run on #389 is queued, or whether nothing in it can reach these two cases. I would not hold the PR on it, but the sentence is the difference between "not run" and "not reachable".

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.

@bong-water-water-bong

Copy link
Copy Markdown
Author

Answering the two asks from the 02:08Z reviews, head unchanged at 8ed852f:

  1. Fused rmsnorm gate. Those layers keep today's path, out-of-place + ggml_copy_f32, unchanged. The fused kernel llm_gated_delta_net_f32_wmma_head128_rmsnorm_gate has no in-place variant (none in the kernel manifest), and !fuse_rmsnorm_gate is part of the predicate. So they lose only this optimisation and take no unexercised path. Added to the body. In the Qwen3.8-27B c4 profile the gate runs as a separate ggml_rmsnorm_gate_f32_q8_1_x4, so the in-place branch is what runs there: 3,024 in-place + 336 in-place projection-epilogue dispatches per 61 steps.
  2. The partition contract next to the branch. It is in the code comment directly above the predicate (dispatch-gated-delta-net.cpp): "Each workgroup owns one (head, sequence) slice, so in place is exact." If the kernel ever gains a reduction across heads or sequences, that sentence and gdn_decode.state_in_place's 4-step chained comparison are what flag it.

On binding offsets (raised by the third review): the device run did exercise them. gdn_decode.state_in_place and state_gathered passed at 8ed852f's content, with attention and cache compared against the CPU over 4 chained steps, 2 sequences. The mutant (branch disabled) failed state_in_place only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant