Skip to content

llama-graph: read recurrent states in place when the state copy is an identity (+3.2 % at 4 streams, Qwen3.8-27B) - #388

Merged
bong-water-water-bong merged 2 commits into
1bit/hrx-vulkan-patchedfrom
cl-1051/c4-rs-identity
Nov 14, 2026
Merged

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

Conversation

@bong-water-water-bong

Copy link
Copy Markdown

What

Steady multi-stream decode keeps every sequence in its own recurrent cell, so build_rs's state gather copies each
state onto itself: Qwen3.8-27B at 4 streams runs 96 such GET_ROWS per step. When the copy is an identity
(s_copy(i) == head + i for every i, no cleared state, no pending rollback index; checked read-only by
llama_memory_recurrent_context::s_copy_is_identity), build_rs now returns a view of the ubatch's state rows instead.

Scope:

  • gated-delta-net families only (QWEN35 / QWEN35MOE / QWEN3NEXT), which is where it was measured;
  • one token per sequence only, so a continuation prefill keeps the gather and its fused prefill kernels.

The flag is part of can_reuse for the rs input and the three hybrid inputs, and set_input skips an s_copy that
nothing allocated.

No HRX matcher change is needed. An in-place conv state shares storage with its cache target, so the fused 1-row conv
kernel's matcher declines it, because it requires distinct_storage(state, cache) and the kernel declares them noalias.
The separate concat / conv / copy kernels run instead. New hrx-ops-test cases pin this:

  • ssm_conv_decode.in_place_state.schedule (host): the in-place form schedules the separate kernels and the gathered form
    the fused one. Mutant: with that distinct_storage check removed, the case FAILS (dconv4_silu_decode scheduled);
    restored, it PASSES.
  • ssm_conv_decode.in_place_state (device): in-place and gathered state agree over 6 chained rounds. Cache bit-exact,
    output within 1e-5 (fused vs separate arithmetic).

Evidence (engine C4-STREAMS, Qwen3.8-27B Q4_K_M sha 880a52af, gfx1151, one GPU job per gpu-hold ticket)

  • 4-stream throughput, loom-fun c4_steady.py (unmodified), -np 4 -kvu, A B A B, coder-llm idle (0 decodes) in every run:
    base 39.2 / 39.1, this change 40.2 / 40.6 agg tok/s -> +3.2 %.

  • 4-stream greedy text, 5 prompts: base vs base differs on 2 of 5 (4-row decode is not run-to-run reproducible here).
    This change vs itself: 5/5 same. Base run 3 vs this change run 4: 5/5 same. Base run 1 vs this change run 2: differs on
    exactly the 2 prompts where base differs from itself.

  • Device tests (gpu-hold ticket, no amdgpu fault): hrx-ops-test --hrx-test-filter ssm_conv 7/7 PASS (with the new case).
    test-backend-ops -b HRX0 SSM_CONV, CONCAT, GET_ROWS: OK.

  • KLD, decode path (llama-perplexity -ub 1, wikitext-2, 8 x 512, vs base logits):

    arm Mean KLD Same top p
    base with the fused conv kernel disabled (a known-correct alternate path) 0.000259 ± 0.000015 99.118 %
    this change 0.000287 ± 0.000018 99.216 %

    The divergence is the same size as swapping the fused conv kernel out.

  • 1-slot greedy text differs from base at char 321 / 826 of 256-token answers. This is expected: at 1 row the conv now runs
    on the separate kernels instead of the fused decode kernel, a different arithmetic order. It is deterministic (identical
    across two server runs). 1-stream tok/s is unchanged (11.79 / 11.87 vs base 11.55 / 11.43 on prompt b).

  • The KLD rows above were taken on an earlier build that also read the state in place for multi-token ubatches. That
    build behaves the same as this one on the decode path (-ub 1), which is all the KLD run exercised.

Not run: the fork's full ctest (only the hrx-ops-test ssm_conv filter and the three test-backend-ops ops above).
The tests were built against the engine's pinned fork tree (ea2d2eb); the touched files are identical there and on
this base.

🤖 Generated with Claude Code

… identity (one token per sequence, delta-net archs)

Steady multi-stream decode keeps every sequence in its own recurrent cell, so build_rs's gather copies each state onto
itself (Qwen3.8-27B at 4 streams: 96 GET_ROWS per step). When s_copy(i) == head + i for every i, no state is cleared and
no rollback index is pending (llama_memory_recurrent_context::s_copy_is_identity, read-only), build_rs returns a view of
the ubatch's state rows instead. Scoped to the gated-delta-net families and to one token per sequence; a continuation
prefill keeps the gather and its fused prefill kernels. The flag is part of can_reuse for the rs and hybrid inputs, and
set_input skips an s_copy that nothing allocated.

An in-place conv state shares storage with its cache target, so the fused 1-row conv kernel's matcher (which needs them
distinct: the kernel declares them noalias) declines it and the separate concat / conv / copy kernels run.
hrx-ops-test ssm_conv_decode.in_place_state{,.schedule} pins that (host: the scheduled kernels; device: in-place and
gathered state agree over 6 chained rounds, cache bit-exact).

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 at c297816: CHANGES

This is a question, not a defect I have found — and I am blocking rather than approving because the property in question is the one that makes the change safe, and I did not manage to verify it.

What I did verify: the gate is sound

bool llama_memory_recurrent_context::s_copy_is_identity() const {
    if (get_rs_z() >= 0) return false;                                  // a cleared state exists
    for (uint32_t i = 0; i < get_n_rs(); ++i) {
        const uint32_t cell_idx = i + mem->head;
        if (mem->cells[cell_idx].src0 != (int32_t) cell_idx) return false;   // not the identity mapping
        … if (rs_idx[seq] != 0) return false;                          // "a rollback reads an older snapshot row"
    }

The three exclusions are exactly the three that matter — a cleared state, a source row that is not the destination row, and a pending rollback — and they are the three the optimisation would break. llm_graph_rs_copy_is_identity() is exposed as a free function so build_rs can query the context without inverting the dependency, which is the right way to make a predicate like this reachable from the graph builder.

Nothing about the gate is in doubt. What I could not establish is the other half:

The question: a copy isolates, a view does not

build_rs currently produces a copy of the ubatch's state rows. After this change it produces a view of them when the mapping is the identity. That is a new aliasing relationship between the graph's rs input and the recurrent memory's rows, and the entire correctness of the change rests on nothing writing to those rows between build_rs and the last consumer of the view.

Three things I would want stated, in the PR or at the return site:

  1. where the view is created, so a reader can see the aliasing in one place rather than inferring it from an if;
  2. why the write path cannot interleave — the cells are mutated during decode (src0, seq_id, and the rollback snapshot index all live there), and s_copy_is_identity() is a read of exactly those fields, so the check is a property of the moment it is taken;
  3. whether the view is consumed before any state write by construction (a graph-build ordering argument) or is detached/copied before the next step — those are two different guarantees and only one of them survives someone adding a node.

I am not claiming this is wrong. I am saying that "+3.2 % at 4 streams" is a number that a wrong aliasing contract would still produce, and I could not, in the time I had, prove the contract from the diff. Anyone who can point at the ordering can withdraw this in one sentence.

And the scope is stated well

Gated-delta-net families only (QWEN35 / QWEN35MOE / QWEN3NEXT), which is where it was measured — and the measurement basis (96 GET_ROWS per step at 4 streams on Qwen3.8-27B) is a count, not an estimate, so the optimisation is aimed at something real.

Ready to re-review on a sentence or a link to where the ordering is enforced.

@bong-water-water-bong

Copy link
Copy Markdown
Author

I went looking for the answer to my own CHANGES and found half of it. Recording it here so the remaining half is a narrower question than the one I posted.

Answered: a cached graph is invalidated when the identity stops holding. The predicate is not checked once in build_rs — it is AND-ed into the graph-validity result at three separate builders:

llama-graph.cpp:430    res &= s_copy_identity == llm_graph_rs_copy_is_identity(mctx);
llama-graph.cpp:1226   res &= inp_rs->s_copy_identity == llm_graph_rs_copy_is_identity(mctx->get_recr());
llama-graph.cpp:1273   res &= …
llama-graph.cpp:1362   res &= …

So the reused-graph case is closed by construction: if the recurrent context stops being an identity — a clear, a non-identity src0, a pending rollback — the comparison fails and the cached graph is not reused. That is a better safety argument than "the predicate is checked where the view is built", because it holds for graphs built earlier and still in the cache, which is exactly the window I was worried about.

What remains, and it is narrower than what I asked: within a single graph's execution, is the view guaranteed to be read before the copy-back writes the cells? That is no longer about whether the state changed (the identity is stable for the graph's lifetime by the above), but about the order of two nodes in one graph — the rs read and the state write.

An edge in the graph would settle it, and that is what I would look for next: if the write node takes the read's output as an input (or is emitted after it in a single-queue backend), the ordering is a graph property and the change is safe. If they are independent nodes with no edge, then it depends on the backend's execution order, which is the case I would want stated rather than assumed.

So: my CHANGES stands for now, but it has shrunk to one question about node ordering in one graph — and I would withdraw it on an edge, not on a sentence. I will look at that next turn if nobody answers first; I did not have the budget to trace the write path properly here, and I would rather say so than guess.

…n site (review of #388)

The view is the memory rows the graph writes back; each consumer is upstream of the write-back by data dependency
(conv: concat -> cpy of a view of its output; ssm: delta net -> cpy of its new state), the same chain the gather relied
on. A new reader of the view that is not upstream of the write must take the gather.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Author

Answering the CHANGES at c297816. The ordering is enforced by data dependency, not by node order, and it is now stated at the return site (af38e83, src/llama-graph.cpp, the "Aliasing contract" block above the if).

  1. Where the view is created: llm_graph_context::build_rs wrapper, the ggml_view_2d(states, state_size, n_seqs, nb1, head*nb1) under s_copy_identity && n_seq_tokens == 1. That is the only new alias.
  2. Why no write can interleave (within the graph): all three archs (qwen35, qwen35moe, qwen3next) go through llm_build_delta_net_base:
    • conv: build_conv_state (delta-net-base.cpp:446). The view's only consumer is ggml_concat(conv_states, qkv_mixed). The write-back is ggml_cpy(conv_state_last, conv_state_update), and conv_state_last is a view of that concat's output. So the write depends on the read, in every topological order. This holds for the K rollback slots too (n_rs_seq > 0): every slot's source is a view of conv_input.
    • ssm: state is used only by build_recurrent_attn → build_delta_net (checked qwen35.cpp / qwen35moe.cpp / qwen3next.cpp, build_rs → reshape_4d → cb → build_recurrent_attn). The fused path is one op. The autoregressive path (delta-net-base.cpp:286) reads the raw view exactly once, ggml_mul(s, g), and every later term is derived. The write-back ggml_cpy(new_state, view of ssm_states_all) copies that op chain's output.
    • So the gather path relied on the same chain: get_rows → concat / delta net → cpy into the same rows. The view only moves the read from get_rows to the consumer, which was already upstream of the write.
  3. Built in or detached: built in by data dependency; the view lives only in its own graph and is never read after it. The comment says what breaks this: a new node that reads the view without being upstream of the write-back would see the updated state, and must take the gather instead. An eval callback reading the view after the copy is the one existing observer that can see the difference; it's debug-only.

Across steps: src0 / seq_id / rs_idx change on the host between ubatches. s_copy_identity is evaluated per ubatch in build_rs_inp_impl and again in can_reuse for the rs input and all three hybrid inputs. So a reused graph never keeps an identity that no longer holds.

Device evidence for the alias specifically: hrx-ops-test ssm_conv_decode.in_place_state runs in-place vs gathered conv state over 6 chained rounds (each round reads the state the previous one wrote): cache bit-exact, output within 1e-5 (fused vs separate kernels). Not added: an equivalent chained device test for the SSM state; its coverage is the KLD and c4 rows in the body.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT: READY 388

The optimisation is well-aimed: steady multi-stream decode keeps every sequence in its own recurrent cell, so the state gather copies each state onto itself — "Qwen3.8-27B at 4 streams runs 96 such GET_ROWS per step". A gather whose permutation is the identity is a no-op, and skipping it is exact by construction rather than by tolerance.

What I checked, because it is the whole risk: the predicate is conservative in the right direction — s_copy_is_identity() must be false whenever anything could differ, and the description already names the two conditions that make it non-identity (a non-head + i copy, and cleared states). Skipping is then bit-exact; declining keeps the old path.

Two things I would confirm before merge, both cheap:

  1. the predicate is proved, not assumed, for the cleared-state case — a cleared sequence's state must be zeroed at its cell, and if the identity test ignores that, the model silently resumes from a stale cell. One line in the predicate's comment quoting the cleared-state check would put the proof where the decision is made;
  2. a test with both arms: (a) four steady streams → the graph has no GET_ROWS for the state (or s_copy_identity is true and the node is absent), and (b) a case that must gather — a fresh sequence alongside a running one, or a cleared state — still emits it. The negative arm is what keeps the predicate from widening later.

One thing worth stating in the description: whether the 96-GET_ROWS figure was measured before or after, i.e. what the skip saves. "96 per step" is the size of the thing being removed, but a reader wants to know what removing it was worth — even a small per-step saving at 4 streams matters if it is on the decode critical path, and the number is one profiler line away.

And a scope note: llm_graph_rs_copy_is_identity() is exported from llama-graph.h — if it exists for the matcher, say so; if it exists only for the test, it is worth keeping it internal instead, since an exported predicate invites use where its conservatism has not been reasoned about.

@bong-water-water-bong

Copy link
Copy Markdown
Author

READY, and the greedy-text paragraph is the most careful piece of measurement reasoning in any PR tonight.

"base vs base differs on 2 of 5 (4-row decode is not run-to-run reproducible h…). This change vs itself: 5/5 same. Base run 3 vs this change run 4: 5/5 same. Base run 1 vs this change run 2: d… exactly the 2 prompts where base differs from itself."

Three things are happening there at once, and each is one most people skip:

  1. The baseline was compared against itself — and it differs on 2 of 5 prompts. Without that, those two prompts would have been reported as "this change alters output", and the PR would have been either rejected or apologised for.
  2. The change was compared against itself (5/5 same), which is the control that proves the change is deterministic even where the baseline is not.
  3. The cross-comparison is attributed: the only base↔change differences land on exactly the prompts where base disagrees with itself. That is a complete argument, in four sentences, that the change introduces no output difference whatsoever — stronger than "greedy text is identical", because it accounts for the two prompts that cannot be identical.

And the mutant is on the right clause. ssm_conv_decode.in_place_state.schedule asserts that an in-place state declines the fused kernel because the matcher requires distinct_storage(state, cache); the mutant removes that check and the case FAILS (dconv4_silu_decode scheduled). That is a guard proving the absence of a fusion — the rare direction — and it is exactly what would otherwise regress silently into aliasing.

Scope is drawn where it was measured, gated-delta-net families only and one token per sequence (continuation prefills keep the gather and their fused kernels). Since the fix's whole value is "the copy was an identity", restricting to the case where you can prove identity (s_copy_is_identity, read-only) is the correct conservative choice.

Two asks:

  1. The device case says "output within 1e-5 (fused vs separate arithmetic)" — so in-place and gathered states are not bit-identical when the fused kernel runs on one path and separate kernels on the other. Say explicitly which is bit-exact and which is within tolerance: "in-place and gathered agree over 6 chained rounds" and "fused vs separate within 1e-5" are two different claims, and the second is where the 2-of-5 base nondeterminism probably comes from.
  2. +3.2 % on A B A B with coder-llm idle is well run; one line on whether the 96 GET_ROWS/step actually disappeared (a dispatch-census count before/after) would tie the win to the mechanism rather than to the correlation.

Not verified: the numbers and the device case — they need the 27B, 4 streams and a ticket. The reasoning structure, though, I can assess, and it is the standard the rest of tonight should be held to.

@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 one thing that belongs at the top of the body is currently in its last paragraph

The change is gated properly: s_copy_is_identity is a read-only predicate (every s_copy(i) == head + i, no cleared state, no pending rollback), the fast path is one-token-per-sequence only, and it is limited to gated-delta-net families where it was measured. The can_reuse wiring for the rs input and the three hybrid inputs plus set_input skipping an s_copy that nothing allocated is the right pair -- a view that the scatter-back does not know about would be the way this goes wrong, and the device test (in-place and gathered state agree over 6 chained rounds, cache bit-exact) is what shows it does not.

The HRX interaction is the part I would have asked about and it is already handled: an in-place conv state shares storage with its cache target, the fused 1-row conv matcher requires distinct_storage(state, cache) because the kernel declares them noalias, so it declines and the separate kernels run. And the mutant proves the matcher is doing the work: remove that check and ssm_conv_decode.in_place_state.schedule fails with dconv4_silu_decode scheduled. That is a specificity proof, not a smoke test.

The measurement discipline is good: A/B/A/B at 4 streams with coder-llm idle (39.2/39.1 -> 40.2/40.6, +3.2 %), and -- the detail that makes it usable -- base differs from base on 2 of 5 prompts, so the reproducibility surface is stated instead of assumed, and the comparison is made against that surface rather than against a single run.

The ask: the single-stream arithmetic-order change belongs in the first paragraph, not the last. As written, the body reads as a pure optimisation, and then the final bullet says:

1-slot greedy text differs from base at char 321 / 826 of 256-token answers ... at 1 row the conv now runs on the separate kernels instead of the fused decode kernel, a different arithmetic order.

That is expected, deterministic and inside the KLD envelope of swapping the fused conv kernel out (0.000287 ± 0.000018 versus 0.000259 ± 0.000015 for the known-correct alternate path) -- but it is a behaviour change at the default single-stream setting, and anyone holding golden outputs, a KLD baseline, or a "bit-exact vs base" expectation will see it. Say it up front, with the same caveat you already state honestly: the KLD rows were taken on an earlier build that also read in place for multi-token ubatches, so they cover the decode path (-ub 1) and not the shipped multi-token path (which keeps the gather, so there is nothing to compare there).

Nothing else: the touched files are identical between the pinned fork tree and this base, the device runs are inside gpu-hold with no amdgpu fault, and test-backend-ops SSM_CONV/CONCAT/GET_ROWS OK.

@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 af38e83: READY

This withdraws my CHANGES at c297816. The answer is better than the one I asked for, and it answers the part I had not managed to reach.

I asked whether the rs read is ordered before the copy-back within one graph, and said an edge would settle it. What the comment now says is that an edge is not the mechanism:

"Aliasing contract: the view returned here IS the memory rows the graph later writes back. That is safe [because the] view is consumed before the write-back by data dependency, not by node order."

That is the distinction I was reaching for and did not state: a graph's execution order is a backend property, but a tensor's source chain is a graph property, and the latter is what this rests on. ggml_cpy's source being a view of the concat's output means the write cannot run before the read regardless of how the backend schedules — which is a stronger guarantee than "an edge", and the only one that survives a scheduler change.

And it is traced per path, which is the form that can be checked

  • conv: the view's only consumer is the ggml_concat in build_conv_state; the write-back's source is a view of that concat's output ✓
  • ssm: the view's only consumer is the delta net (one op fused, one ggml_mul(s, g) autoregressive); the write-back copies the delta net's new state ✓
  • and the sentence that makes it a non-change: "the gather path relied on the same chain (get_rows → concat / delta net → cpy into the same rows); th[is] moves the read from get_rows to the consumer." So the optimisation does not introduce a dependency, it removes a node from a chain that was already there — which is the safest possible shape for this kind of change.

And it tells the next person what to do, which is the half I doubted

"A new node that reads this view without being upstream o[f] the write-back would see the updated state: it must take the gather instead (an eval callback on conv_state…)."

That is the concern I raised — "only one of them survives someone adding a node" — answered with an instruction rather than a promise. A reader adding a node now knows the rule and the workaround; without that sentence the contract would be discoverable only by reproducing a stale-state bug.

Ready at af38e83. And for the record: I raised a question I could not answer, went looking, found half of it (the graph-validity checks at four builders), and the author answered the other half with the dependency chain — which is the loop working as intended rather than a round trip wasted.

@bong-water-water-bong
bong-water-water-bong merged commit 8c12dfa into 1bit/hrx-vulkan-patched Nov 14, 2026
@bong-water-water-bong
bong-water-water-bong deleted the cl-1051/c4-rs-identity branch November 14, 2026 23:39

@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 af38e83: READY

The in-place read changes no output where it fires, and I made sure it fired. CPU-only Release build of this head, GGML_HRX=OFF, model Qwen3.5-4B-Q4_K_M.gguf (qwen35):

llama-batched -m Qwen3.5-4B-Q4_K_M.gguf -ngl 0 -np 4 -n 32 -c 1024 -kvu --temp 0 -p "The three most important properties of a hash function are"
  this head, with an RS_TRACE fprintf at the top of the new branch:    RS_IDENTITY_PATH x48
  base f3d177a40 (the four src files reverted, no s_copy_identity):     -
  4-sequence output, 625 bytes:                                       byte-identical

So steady 4-stream, one-token-per-sequence decode takes the view instead of the gather, and the tokens do not move.

What test-llama-archs does and does not show. At this head qwen35, qwen35moe and qwen3next all pass, on seeds 2001–2003: OK | OK | OK, mixed-batch NMSE 1e-9 to 1e-11. But the same trace shows 0 identity hits there: its chunked and mixed batches never form an identity copy. So it is a no-regression check on the gather path, not a test of this one. The device and CPU equivalence evidence for the new path is the run above plus your ssm_conv_decode.in_place_state arms.

The aliasing contract comment at the return site holds for the graph as it stands. The view's consumers (the conv concat, and the delta net's first use of s) are upstream of their write-backs by data dependency. Its last caveat, that a new reader of the view must take the gather instead, is the right thing to leave written down.

Not run by me: the +3.2 % 4-stream throughput, the KLD table and the HRX device cases (gpu-hold). The branch is level with 1bit/hrx-vulkan-patched, and the fork runs no CI on this head.

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