Commit 7b74cb92d for llama.cpp
commit 7b74cb92d67384373e87512f4ffd2dbef756b944
Author: Lucius <37386791+luciusacarr@users.noreply.github.com>
Date: Fri Nov 27 03:15:29 2026 -0800
graph : read recurrent states in place instead of copying (#28841) (#30139)
* graph : read recurrent states in place instead of copying (#28841)
This is a graph only change that speeds up token output in the majority of cases and backends by removing state copy steps.
Where possible, kernels now read recurrent states directly from the cache instead of a copy from ggml_get_rows.
A change to RWKV6/7 makes it read its old state before overwriting.
A graph-reuse check condition is added to keep track of whether states are read in place.
Assisted-by: Claude Opus 5.5 + Sol 6.1
* graph : keep recurrent-state graph the same shape, both when read in place or for movement
Vulkan and Metal failed under GGML_SCHED_NO_REALLOC. The readers now always read the states from cache.
Graph shape is mainmtained throughout.
Assisted by: Opus 5.5
* Prevent any throughput regressions from caching clashing with speculative decoding rollback snapshots. Fix WebGPU CI error by skipping the fusion step when input states overlap with the cache it writes to.
* Refactor comment on rollback snapshots in llama-graph
Simplified comment.
* tests : add regression test for after memory clear
* graph : check rs_in_place when reusing the hybrid iswa rel input
* graph : document build_rs rules, read src0 directly in get_rs_in_place
* graph : expose the rs snapshot rule once via get_rs_snapshots
* graph : drop the repeated snapshot rule from the build_rs comment
* graph : clarify the build_rs snapshot comment
diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp
index ed7088ae2..56447c4e5 100644
--- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp
+++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp
@@ -3593,7 +3593,10 @@ static bool ggml_webgpu_can_fuse_rms_norm_mul(const struct ggml_cgraph * cgraph,
return true;
}
-static bool ggml_webgpu_can_fuse_gdn_cache(const struct ggml_cgraph * cgraph, int node_idx, int & num_encoded_ops) {
+static bool ggml_webgpu_can_fuse_gdn_cache(const webgpu_global_context & global_ctx,
+ const struct ggml_cgraph * cgraph,
+ int node_idx,
+ int & num_encoded_ops) {
const ggml_tensor * gdn = cgraph->nodes[node_idx];
// the kernel skips the snapshot tail, so the gdn output must not be a graph output
@@ -3649,6 +3652,12 @@ static bool ggml_webgpu_can_fuse_gdn_cache(const struct ggml_cgraph * cgraph, in
return false;
}
+ // the input state can be read straight from the cache the kernel writes to; webgpu rejects a
+ // writable binding that overlaps another binding of the same dispatch
+ if (ggml_webgpu_tensor_binding_overlap(global_ctx, gdn->src[5], cpy_dst)) {
+ return false;
+ }
+
num_encoded_ops = cpy_idx - node_idx + 1;
return true;
@@ -3797,7 +3806,7 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
case GGML_OP_GATED_DELTA_NET:
if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <=
ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage &&
- ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
+ ggml_webgpu_can_fuse_gdn_cache(ctx->global_ctx, cgraph, node_idx, num_encoded_ops)) {
ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
node, dst_fuse);
diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp
index a96577f11..a7cae138a 100644
--- a/src/llama-graph.cpp
+++ b/src/llama-graph.cpp
@@ -581,6 +581,7 @@ bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) {
res &= head == mctx->get_head();
res &= rs_z == mctx->get_rs_z();
+ res &= rs_in_place == mctx->get_rs_in_place();
return res;
}
@@ -1309,6 +1310,7 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) {
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
+ res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1356,6 +1358,7 @@ bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) {
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
+ res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1429,6 +1432,7 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params)
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
+ res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1516,6 +1520,7 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
+ res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -4167,7 +4172,9 @@ ggml_tensor * llm_graph_context::build_rs(
uint32_t rs_head,
uint32_t rs_size,
int32_t rs_zero,
- const llm_graph_get_rows_fn & get_state_rows) const {
+ const llm_graph_get_rows_fn & get_state_rows,
+ bool in_place,
+ bool from_cache) const {
GGML_UNUSED(rs_size);
ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, s->ne[1]);
@@ -4185,9 +4192,22 @@ ggml_tensor * llm_graph_context::build_rs(
ggml_tensor * states_all = ggml_get_rows(ctx0, states, state_copy);
- ggml_tensor * output_states = get_state_rows ?
- get_state_rows(ctx0, states, state_copy_main) :
- ggml_view_2d(ctx0, states_all, state_size, n_seqs, states_all->nb[1], 0);
+ ggml_tensor * output_states;
+ if (get_state_rows) {
+ output_states = get_state_rows(ctx0, states, state_copy_main);
+ } else if (!from_cache) {
+ // rollback snapshots: the states are never in place, so the readers read the gathered states directly
+ output_states = ggml_view_2d(ctx0, states_all, state_size, n_seqs, states_all->nb[1], 0);
+ } else {
+ // move the gathered states into their cells, the readers then read them from the cache
+ // when the states are already in place the gather and the move have no rows, so the graph only changes in size
+ const int64_t n_move = in_place ? 0 : n_seqs;
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0,
+ ggml_view_2d(ctx0, states_all, state_size, n_move, states_all->nb[1], 0),
+ ggml_view_2d(ctx0, states, state_size, n_move, states->nb[1], rs_head*states->nb[1])));
+ // view of the cache: all readers must run after the move and before the new states are stored over it
+ output_states = ggml_view_2d(ctx0, states, state_size, n_seqs, states->nb[1], rs_head*states->nb[1]);
+ }
ggml_build_forward_expand(gf, output_states);
// copy extra states which won't be changed further (between n_seqs and n_rs)
@@ -4222,6 +4242,9 @@ static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
inp->head = mctx_cur->get_head();
inp->rs_z = mctx_cur->get_rs_z();
+ inp->rs_in_place = mctx_cur->get_rs_in_place();
+ inp->s_copy_rows = ggml_view_1d(ctx0, inp->s_copy, inp->rs_in_place ? 0 : n_rs, 0);
+
inp->has_rep = mctx_cur->get_rs_replay();
if (inp->has_rep) {
// the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp)
@@ -4263,16 +4286,23 @@ ggml_tensor * llm_graph_context::build_rs(
ggml_tensor * s,
int32_t state_size,
int32_t n_seqs,
- const llm_graph_get_rows_fn & get_state_rows) const {
+ const llm_graph_get_rows_fn & get_state_rows,
+ bool gathered) const {
const auto * kv_state = inp->mctx;
+ const bool in_place = inp->rs_in_place && !get_state_rows && !gathered;
+
+ // the snapshot mode is fixed per context, so the graph shape is stable
+ const bool from_cache = !gathered && !kv_state->get_rs_snapshots();
+ GGML_ASSERT(get_state_rows || !from_cache || s->type == GGML_TYPE_F32); // the states are read from the cache, the gather is F32
+
// a custom getter reads the states of the ubatch straight from the cache, so the gather skips the first
// state: it still holds the n_rs - n_seqs extra states and copies no state of a single sequence ubatch
- ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : inp->s_copy;
+ ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : from_cache ? inp->s_copy_rows : inp->s_copy;
return build_rs(s, state_copy, inp->s_copy_main, state_size, n_seqs,
kv_state->get_n_rs(), kv_state->get_head(), kv_state->get_size(), kv_state->get_rs_z(),
- get_state_rows);
+ get_state_rows, in_place, from_cache);
}
void llm_graph_context::build_conv_state_store(
diff --git a/src/llama-graph.h b/src/llama-graph.h
index 508d05531..33b1df4ce 100644
--- a/src/llama-graph.h
+++ b/src/llama-graph.h
@@ -341,6 +341,12 @@ public:
// used in view offsets, need to match for valid graph reuse
uint32_t head;
int32_t rs_z;
+
+ // the states are read from the cache, see llama_memory_recurrent_context::get_rs_in_place
+ bool rs_in_place;
+
+ // rows to gather, shared by all layers; empty when rs_in_place
+ ggml_tensor * s_copy_rows; // I32 [n_rs] or [0]
};
class llm_graph_input_cross_embd : public llm_graph_input_i {
@@ -1496,6 +1502,7 @@ struct llm_graph_context {
// when moving, avoid passing `ggml_cgraph` - only pass `ggml_context`. would likely need to split the
// implementation in 2 separate methods. the goal is to avoid calling `ggml_build_forward_expand` in
// `llama_memory_recurrent`
+ // note: same rules as the build_rs overload below (readers before the store, one call per state tensor per graph)
ggml_tensor * build_rs(
ggml_tensor * s,
ggml_tensor * state_copy,
@@ -1506,16 +1513,22 @@ struct llm_graph_context {
uint32_t rs_head,
uint32_t rs_size,
int32_t rs_zero,
- const llm_graph_get_rows_fn & get_state_rows = nullptr) const;
+ const llm_graph_get_rows_fn & get_state_rows = nullptr,
+ bool in_place = false,
+ bool from_cache = true) const;
llm_graph_input_rs * build_rs_inp() const;
+ // the returned states can be a view of the cache, so callers must follow 2 rules:
+ // - expand every reader of the returned tensor before the store into s (the rwkv token shift gets this only from the expand order)
+ // - call it once per state tensor per graph: a second call would gather rows that the first already moved into [head, head + n_seqs)
ggml_tensor * build_rs(
llm_graph_input_rs * inp,
ggml_tensor * s,
int32_t state_size,
int32_t n_seqs,
- const llm_graph_get_rows_fn & get_state_rows = nullptr) const;
+ const llm_graph_get_rows_fn & get_state_rows = nullptr,
+ bool gathered = false) const; // gathered: always read a copy, never the cache
// store the conv history of the ubatch cells, the last n_cols columns of conv_x {n_cols + n_seq_tokens, channels, n_seqs},
// at byte offset offs of each row of s, and with n_rs_seq > 0 once per rollback slot of this ubatch
diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp
index bab6276f6..0af05571c 100644
--- a/src/llama-memory-recurrent.cpp
+++ b/src/llama-memory-recurrent.cpp
@@ -1461,6 +1461,22 @@ int32_t llama_memory_recurrent_context::get_rs_z() const {
return is_full ? 0 : mem->rs_z;
}
+bool llama_memory_recurrent_context::get_rs_in_place() const {
+ // rollback snapshots, zeroed states and extra states go through the gather
+ if (is_full || get_rs_snapshots() || mem->rs_z >= 0 || mem->n != get_ubatch().n_seqs) {
+ return false;
+ }
+
+ for (uint32_t i = 0; i < mem->n; ++i) {
+ // s_copy() would also reset the rollback idx, which set_input reads later
+ if (mem->cells[mem->head + i].src0 != (int32_t) (mem->head + i)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
uint32_t llama_memory_recurrent_context::get_size() const {
return mem->size;
}
@@ -1493,6 +1509,11 @@ bool llama_memory_recurrent_context::get_rs_replay() const {
return mem->rs_replay;
}
+bool llama_memory_recurrent_context::get_rs_snapshots() const {
+ // rs_replay keeps one state plane, so its states can be in place like without rollback
+ return mem->n_rs_seq != 0 && !mem->rs_replay;
+}
+
uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const {
return is_full ? 0 : mem->cells[i + mem->head].rs_rep;
}
diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h
index 5efe9c3b4..f444b9b8e 100644
--- a/src/llama-memory-recurrent.h
+++ b/src/llama-memory-recurrent.h
@@ -192,6 +192,7 @@ public:
uint32_t get_head() const;
int32_t get_rs_z() const;
uint32_t get_size() const;
+ bool get_rs_in_place() const; // every state of the ubatch is read from its own cell
ggml_tensor * get_r_l(int32_t il) const;
ggml_tensor * get_s_l(int32_t il) const;
@@ -203,6 +204,7 @@ public:
int32_t s_copy(int i) const;
bool get_rs_replay() const;
+ bool get_rs_snapshots() const; // rollback keeps per-seq snapshots: the states are never in place
uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i
private:
diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp
index f71e7fddd..4ea6fb757 100644
--- a/src/models/delta-net-base.cpp
+++ b/src/models/delta-net-base.cpp
@@ -235,7 +235,8 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay(
ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]);
const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) {
- return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs);
+ // the gdn op can store the new inputs into these rows while it replays them, so it reads a copy
+ return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs, nullptr, true), c->ne[0], c->ne[1], c->ne[2], n_seqs);
};
ggml_tensor * pk = gather(spk, ck);
diff --git a/src/models/rwkv6.cpp b/src/models/rwkv6.cpp
index 4cb5bce64..0b17ae40a 100644
--- a/src/models/rwkv6.cpp
+++ b/src/models/rwkv6.cpp
@@ -145,6 +145,8 @@ llama_model_rwkv6::graph::graph(const llm_graph_params & params) :
ggml_view_3d(ctx0, ffn_norm, n_embd, 1, n_seqs, ffn_norm->nb[1], ffn_norm->nb[2],
(n_seq_tokens - 1) * n_embd * ggml_element_size(ffn_norm)),
1);
+ // the shift state can be a view of the cache, read it before the store overwrites it
+ ggml_build_forward_expand(gf, x_prev);
ggml_build_forward_expand(gf, build_rwkv_token_shift_store(token_shift, ubatch, il));
ffn_inp = ggml_reshape_2d(ctx0, ffn_inp, n_embd, n_tokens);
diff --git a/src/models/rwkv7.cpp b/src/models/rwkv7.cpp
index 77c97f953..b1d525940 100644
--- a/src/models/rwkv7.cpp
+++ b/src/models/rwkv7.cpp
@@ -176,6 +176,8 @@ llama_model_rwkv7::graph::graph(const llm_graph_params & params) :
ggml_view_3d(ctx0, ffn_norm, n_embd, 1, n_seqs, ffn_norm->nb[1], ffn_norm->nb[2],
(n_seq_tokens - 1) * n_embd * ggml_element_size(ffn_norm)),
1);
+ // the shift state can be a view of the cache, read it before the store overwrites it
+ ggml_build_forward_expand(gf, x_prev);
ggml_build_forward_expand(gf, build_rwkv_token_shift_store(token_shift, ubatch, il));
ffn_inp = ggml_reshape_2d(ctx0, ffn_inp, n_embd, n_tokens);
diff --git a/tests/llama-context/cases-rs.cpp b/tests/llama-context/cases-rs.cpp
index ba4b71c7e..e5b20bab5 100644
--- a/tests/llama-context/cases-rs.cpp
+++ b/tests/llama-context/cases-rs.cpp
@@ -487,6 +487,54 @@ struct case_shared_seq_reserve : ctx_test {
}
};
+// decode, clear the memory without wiping it and decode again: the first ubatch after the clear reads zeroed states, the
+// next ones read the states in place. Compared token by token against a fresh context.
+struct case_clear : ctx_test {
+ test_group group() const override { return TEST_GROUP_RS; }
+
+ const char * name() const override { return "clear"; }
+
+ const char * description() const override {
+ return "decoding after a memory clear matches a fresh context";
+ }
+
+ case_result run(model_run & mr) const override {
+ const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(mr.model));
+
+ ctx_opts opts;
+ opts.n_ctx = 64;
+ opts.n_batch = 32;
+ opts.n_seq_max = 1;
+
+ llama_context_ptr ctx = mr.ctx(opts);
+ llama_context_ptr ctx_ref = mr.ctx(opts);
+ if (!ctx || !ctx_ref) {
+ return case_result::fail();
+ }
+
+ CTX_REQUIRE(decode_gen(ctx.get(), n_vocab, 0, 0, 16), "the prompt decode failed");
+
+ llama_memory_clear(llama_get_memory(ctx.get()), false);
+
+ for (llama_pos pos = 0; pos < 4; ++pos) {
+ const llama_token tok = gen_token(n_vocab, 0, pos);
+
+ std::vector<float> logits;
+ std::vector<float> logits_ref;
+ CTX_REQUIRE(decode_one(ctx.get(), tok, pos) && decode_one(ctx_ref.get(), tok, pos) &&
+ get_current_logits(ctx.get(), logits) && get_current_logits(ctx_ref.get(), logits_ref),
+ "the replay decode failed at pos " + std::to_string(pos));
+
+ const logits_diff diff = compare_logits(logits.data(), logits_ref.data(), logits.size());
+ CTX_REQUIRE(diff.nmse() <= NMSE_THRESHOLD,
+ "decoding after a clear differs from a fresh context at pos " + std::to_string(pos) +
+ " (nmse " + std::to_string(diff.nmse()) + ")");
+ }
+
+ return case_result::pass();
+ }
+};
+
std::vector<ctx_test_ptr> make_rs_cases() {
std::vector<ctx_test_ptr> cases;
@@ -494,6 +542,7 @@ std::vector<ctx_test_ptr> make_rs_cases() {
cases.push_back(std::make_unique<case_rollback_bound>());
cases.push_back(std::make_unique<case_multi_seq_split_replay>());
cases.push_back(std::make_unique<case_shared_seq_reserve>());
+ cases.push_back(std::make_unique<case_clear>());
return cases;
}