Skip to content

Recurrent graph reuse and O(n) ESN output stacking - #6

Merged
drzo merged 2 commits into
masterfrom
claude/esn-implementation-docs-GoNIs
Oct 28, 2026
Merged

drzo merged 2 commits into
masterfrom
claude/esn-implementation-docs-GoNIs

Conversation

@drzo

@drzo drzo commented Oct 26, 2026

Copy link
Copy Markdown

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_rs never implemented can_reuse. Because the default is false, llama.cpp rebuilt and re-allocated the compute graph for every generated token of every recurrent architecture: Mamba, RWKV and ESN. build_rs and the builders' state-store views bake n_rs, the cell head and rs_z into view sizes and offsets. Everything else they use is either an input tensor or fixed for the context (get_size()). The input now records head and rs_z when 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_esn

Prompt processing stacked the per-token states with a balanced ggml_concat tree, 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 using ggml_set_rows. Every backend here supports GGML_OP_SET_ROWS; GGML_OP_SET was 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 small llm_graph_input_esn_steps input supplies the row indices.

3. test-esn-inference J on quantized reservoirs

J failed on Q4_0 models, on master too. Batched and stepwise decoding run W_in through 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 3 runs, comparing builds with and without the change.

R 256 1024 2048 8192
tg256 tok/s, rebuild → reuse 16578 → 25732 (+55%) 9182 → 11673 (+27%) 4437 → 5458 (+23%) 597 → 672 (+13%)
pp512 tok/s, concat tree → set_rows 66057 → 65988 11276 → 14196 (+26%) 5807 → 7494 (+29%) 729 → 723

Stacking makes no measurable difference at R=256, where everything stays in cache, or at R=8192, where reading W_res dominates.

Testing

  • Graph reuse: logits are bit-identical to LLAMA_GRAPH_REUSE_DISABLE=1 over 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.
  • Stacking: logits are bit-identical to the concat tree for single-sequence prefill (300 and 512 tokens), and for three interleaved sequences of different lengths at n_ubatch 512, 64 and 7. Tested on Q4_0 and F32 at R=2048, plus R=512. llama-perplexity gives the same PPL as before (10.1774).
  • Tests: ctest -R esn passes. test-esn-inference passes on F32, F16, Q8_0 and Q4_0 at R=2048, on Q8_0 and Q4_0 at R=8192, and on R=512.
  • I haven't tested Mamba or RWKV models; there are none in this environment. The reuse key covers everything their builders read from the recurrent context.

Generated by Claude Code

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
@github-actions github-actions Bot added documentation Improvements or additions to documentation testing labels Oct 26, 2026

drzo commented Oct 26, 2026 •

Copy link
Copy Markdown
Author

CI failures that are not from this PR (all also red on master):

  • editorconfig: trailing whitespace / final newline in docs/gpt-oss.md, examples/gpt-oss-README.md and examples/gpt-oss-example.sh, none of which this PR touches. Its own files pass.
  • server-windows, windows-latest-cmake (llvm-arm64), windows-latest-cmake-hip, windows-2022-cmake-cuda (12.4): the get_libcurl step fails before any build with tar.exe: Error opening archive: Unrecognized archive format.
  • android-build: sdkmanager exits 1 while setting up the SDK.
  • macOS-latest-cmake-arm64: -Werror warnings in vendored vendor/minja/minja.hpp (-Wmissing-noreturn) and the SDK's deprecated wstring_convert, while compiling common/.
  • ubuntu-22-cmake-sycl (and -fp16 when it finishes, same image): ggml-sycl/dpct/helper.hpp: 'syclcompat/math.hpp' file not found in the toolchain image.
  • ggml-ci-arm64-cpu-high-perf-sve: the rerank model check fails with rerank score 2 @ 0.040 (expected 0.10–0.30). The three scores (0.032 / 0.024 / 0.040) are exactly the same as on master, and that model is not recurrent, so the graph-reuse change does not reach it.

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

@drzo
drzo marked this pull request as ready for review October 28, 2026 10:31
Copilot AI balanced review requested due to automatic review settings October 28, 2026 10:31
@drzo
drzo merged commit 6e84f7d into master Oct 28, 2026
50 of 73 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 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

Comment thread src/llama-model.cpp
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) {
drzo pushed a commit that referenced this pull request Oct 28, 2026
drzo pushed a commit that referenced this pull request Oct 28, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants