Repository navigation
Recurrent graph reuse and O(n) ESN output stacking - #6
Conversation
llm_graph_input_rs never implemented can_reuse, so the default (false) made llama.cpp rebuild and re-allocate the compute graph for every decoded token of every recurrent architecture (Mamba, RWKV, ESN). build_rs and the recurrent builders' state-store views bake n_rs, the cell head and rs_z into view sizes and offsets; everything else they use is an input tensor or fixed for the context. Record head and rs_z when the input is built and allow reuse while all three are unchanged, which holds for consecutive decode steps. ESN decode throughput (4 threads, Q4_0 reservoir): +55% at R=256, +27% at R=1024, +23% at R=2048, +13% at R=8192. Logits are bit-identical with LLAMA_GRAPH_REUSE_DISABLE=1, including with two sequences decoded in lockstep and one of them cleared and restarted mid-stream. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Prompt processing stacked the per-token reservoir states in a balanced ggml_concat tree, copying each state log2(n) times. Write each step's state into its row of one [reservoir_size, n_seq_tokens, n_seqs] buffer instead. Each ggml_set_rows returns a view of the whole buffer that depends on the previous write, so the readout sees every row, and the graph topology still does not depend on which tokens are outputs. pp512 (4 threads, Q4_0): +26% at R=1024, +29% at R=2048, unchanged at R=256 (all in cache) and R=8192 (bound by reading W_res). Logits are bit-identical to the concat tree for one and several sequences and for ubatch sizes 512, 64 and 7. test-esn-inference J failed on Q4_0 models, on master as well: batched and stepwise decoding use different W_in kernels, and a rounding difference that flips one Q8_0-quantized state value leaves the later positions of that sequence off by up to 0.1. Check for the signature of a misplaced row instead, a jump from a close match straight to O(1); an injected one-row shift in the stacking still fails it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
|
CI failures that are not from this PR (all also red on master):
None of these has a fix to port; they are runner/download problems rather than code. That is every failed check on this head. All other completed jobs pass, including the Ubuntu CPU builds, sanitizers, server tests, macOS x64 and pyright. The jobs still queued are self-hosted ggml-ci runners plus ppc64le/s390x/riscv64, which never pick up jobs in this repo. Generated by Claude Code |
There was a problem hiding this comment.
🟡 Changes recommended
The inference test can miss row corruption and removes nonquantized error bounds, while per-timestep CUDA transfers add graph splits and synchronization overhead to the optimized stacking path.
2 open issues
What changed in this PR
This PR targets recurrent inference performance in llama.cpp by enabling graph reuse and reducing ESN output-stacking copies.
Changes:
- Allow recurrent graphs to be reused when state dimensions and offsets remain unchanged.
- Replace ESN’s balanced concatenation tree with per-timestep writes into a shared output buffer.
- Adjust batched-versus-stepwise inference checks for quantization drift and document benchmark results.
| File | Description |
|---|---|
tests/test-esn-inference.cpp |
Track per-position errors and introduce a drift-tolerant comparison. |
src/llama-model.cpp |
Add timestep indices and stack ESN states with ggml_set_rows. |
src/llama-graph.h |
Declare recurrent-state reuse checks and cached offsets. |
src/llama-graph.cpp |
Implement reuse checks and capture graph-specific state offsets. |
docs/esn.md |
Describe the optimizations, benchmarks, and quantization drift. |
Review effort: Balanced
| if (states) { | ||
| states = ggml_set_rows(ctx0, states, | ||
| ggml_reshape_3d(ctx0, state, reservoir_size, 1, n_seqs), | ||
| ggml_view_1d(ctx0, steps, 1, t * ggml_element_size(steps))); |
| for (const auto & seq : errs) { | ||
| double prev = 0.0; | ||
| for (double e : seq) { | ||
| if (prev < 1e-3 && e >= 1e-2) { |
…ulkan ccache With a GPU backend, the ggml_set_rows stacking indexed each step by a view of a CPU input tensor, and the scheduler copies each view as a separate split input; a 128-token ubatch exceeded GGML_SCHED_MAX_SPLIT_INPUTS and aborted at context creation (test-esn-online on ubuntu-24-cmake-vulkan). set_rows is kept when the CPU is the only backend (it is ~13% faster at R=1024 there); otherwise the steps are concatenated in a balanced tree, as before #6. ubuntu-24-cmake-vulkan builds with GGML_NATIVE and shared ccache objects across runner CPUs (SIGILL in test-backend-ops and test-esn-activations); key its cache on the CPU fingerprint as the ggml-ci jobs already do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

Make sure to read the contributing guidelines before submitting a PR
Summary
Two inference speedups. Neither changes the logits: every comparison below is bit-identical. There is also a fix to a test that failed on Q4_0 models.
1. Graph reuse for recurrent models (
src/llama-graph.{h,cpp})llm_graph_input_rsnever implementedcan_reuse. Because the default isfalse, llama.cpp rebuilt and re-allocated the compute graph for every generated token of every recurrent architecture: Mamba, RWKV and ESN.build_rsand the builders' state-store views baken_rs, the cellheadandrs_zinto view sizes and offsets. Everything else they use is either an input tensor or fixed for the context (get_size()). The input now recordsheadandrs_zwhen it is built, and allows reuse while all three are unchanged. That holds for consecutive decode steps.2. O(n) output stacking in
llm_build_esnPrompt processing stacked the per-token states with a balanced
ggml_concattree, which copies each state log2(n) times. Now each step writes its state into its own row of a single[R, n_seq_tokens, n_seqs]buffer usingggml_set_rows. Every backend here supportsGGML_OP_SET_ROWS;GGML_OP_SETwas ruled out because no GPU backend implements it. Each write returns a view of the whole buffer that depends on the previous write, so the readout sees all rows. The graph topology still doesn't depend on which tokens are outputs, which upstream keeps for pipeline parallelism. A smallllm_graph_input_esn_stepsinput supplies the row indices.3.
test-esn-inferenceJ on quantized reservoirsJ failed on Q4_0 models, on master too. Batched and stepwise decoding run
W_inthrough different matmul kernels. With a Q8_0/Q4_0 reservoir, the state is re-quantized every step, so a ~1e-7 kernel difference can flip one rounding. After that, the rest of that sequence is off by up to 0.1 relative to the largest logit; in the failing case the error was ~1e-6 for 9 positions and then rose to 2.7e-3, 6.4e-3, 2e-2 and so on. J now checks for what a misplaced row looks like instead: a jump from a close match straight to ≥1e-2. I injected a one-row shift into the stacking and J still catches it on both the F32 and Q4_0 models.Results
4-thread CPU, Q4_0 reservoirs. Each number is the median of 5 interleaved
llama-bench -r 3runs, comparing builds with and without the change.set_rowsStacking makes no measurable difference at R=256, where everything stays in cache, or at R=8192, where reading
W_resdominates.Testing
LLAMA_GRAPH_REUSE_DISABLE=1over 360 stepwise decode steps (Q4_0, F16). They are also identical in a test that decodes two sequences in lockstep and clears and restarts one of them halfway, on F32, F16, Q4_0 and an R=256 model; 76/80 graphs were reused there. Greedy generation is unchanged as well.n_ubatch512, 64 and 7. Tested on Q4_0 and F32 at R=2048, plus R=512.llama-perplexitygives the same PPL as before (10.1774).ctest -R esnpasses.test-esn-inferencepasses on F32, F16, Q8_0 and Q4_0 at R=2048, on Q8_0 and Q4_0 at R=8192, and on R=512.Generated by Claude Code