Skip to content

ESN: vectorized tanh/sigmoid and a per-token input table - #7

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

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

Conversation

@drzo

@drzo drzo commented Oct 28, 2026

Copy link
Copy Markdown

Make sure to read the contributing guidelines before submitting a PR

Summary

Two more ESN inference speedups. The prompt runs up to 1.9× faster and decoding up to 1.55× faster at small and medium reservoir sizes. Logits change by float rounding only.

4-thread CPU, medians of eight interleaved llama-bench -r 3 runs. Before = libm tanhf, no table; after = this PR:

Reservoir 256 (Q4_0) 1024 (Q4_0) 2048 (F32) 8192 (Q4_0, no table)
pp512 (tok/s) 64846 → 123743 20361 → 37590 4784 → 6000 893 → 970
tg256 (tok/s) 25659 → 32764 11956 → 18560 3470 → 4440 766 → 852

Changes

1. Vectorized tanh and sigmoid on CPU (ggml/src/ggml-cpu/unary-ops.cpp)

  • Profiling showed the CPU backend's tanh was libm's scalar tanhf, about 20 ns per element. At R=1024 it was 14% of single-thread instructions, more than anything except the W_res matvec.
  • The reservoir state is a single row, so the op also ran on one thread while the others waited.
  • Both functions are now branch-free, so GCC vectorizes the loop (checked with -fopt-info-vec): a minimax polynomial for |x| < 0.625, and an inline exp above that.
  • Speed: 0.8 ns per element with AVX2.
  • Accuracy: worst error 1.13 ulp for tanh and 1.98 ulp for sigmoid. That is as accurate as libm by the same measure.
  • On its own this gives pp512 +64% and tg256 +27% at R=1024, and about +20% at R=2048.
  • This affects every model that uses ggml_tanh or ggml_sigmoid on the CPU. Upstream ggml still uses scalar tanhf.
  • The round-to-nearest trick it uses is already in repack.cpp, and IntelLLVM builds get -fno-associative-math.

2. Per-token input table

  • With token inputs, the input drive s_in·W_in·E[tok] + b_in + b_res + s_fb·W_fb[tok] depends on the token alone.
  • scripts/esn_training.py now stores it as esn_input_table ([n_vocab, reservoir_size]); --no-input-table omits it.
  • llm_build_esn reads it with one get_rows, replacing up to seven graph nodes. Each node ends with a thread barrier, which dominates small decode graphs.
  • Embedding inputs still compute the drive the old way.
  • Scales by 1.0 are no longer emitted.
  • Gain: tg +16–18% at R=1024. At R=256 it is within this VM's ±15% timing noise, though instruction counts drop.
  • Cost: for the 256-token byte vocabulary the table adds 1 KiB per reservoir unit to the GGUF (+60% at R=256 Q4_0, +11% at R=2048 F32).

Verification

  • New CTest test-esn-activations: checks tanh and sigmoid against double references over 2^19 points, plus ±0, ±inf, NaN and tiny inputs, and multi-row/multi-thread consistency. Writing it caught tanh(inf) returning 0.99999994; that is fixed by capping |x| at 10 instead of 9.
  • test-esn: now covers the new tensor.
  • C++ vs Python parity (f32/f16/q8_0/q4_0, all three activations, feedback): unchanged with and without the table. Worst relative error 3.4e-4 (F16 reservoir), ~1e-6 for the others; argmax agreement 100%.
  • test-esn-inference A..J: passes on table and no-table models, including Q4_0, F16, feedback and sigmoid.
  • Held-out perplexity: identical to 4 decimals for F32 (27.32). Q4_0 moves within its usual rounding jitter (bits/byte 4.7827 → 4.7832).
  • Logits: F32 reservoirs move by ≤1.1e-6 relative to the largest logit.

Notes


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
The CPU backend computed tanh with scalar libm tanhf (~20 ns/element),
14% of single-thread work at R=1024, and a one-row reservoir state left
the other threads waiting on it. tanh and sigmoid in unary-ops.cpp are
now branch-free (minimax polynomial below |x|=0.625, inline exp above),
so they auto-vectorize: 0.8 ns/element with AVX2, within 1.2 and 2 ulp.
tests/test-esn-activations.cpp checks them against double references.

With token inputs the ESN input drive (s_in*W_in*E + biases +
s_fb*W_fb) depends on the token alone. esn_training.py now stores it as
esn_input_table (--no-input-table to omit), and llm_build_esn reads it
with one get_rows instead of up to seven nodes. Scales by 1 are skipped.

4-thread medians, before -> after: pp512 R=1024 20361 -> 37590 tok/s,
tg256 R=1024 11956 -> 18560, R=2048 3470 -> 4440. Logits change by
rounding only; held-out perplexity and C++/Python parity are unchanged.

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 ggml labels Oct 28, 2026

drzo commented Oct 28, 2026 •

Copy link
Copy Markdown
Author

These CI failures are not caused by this PR. They fail the same way on master, and no fix exists yet:

  • editorconfig: 7 errors in docs/gpt-oss.md and examples/gpt-oss-README.md. This PR does not touch either file.
  • windows-latest-cmake (cpu-x64 static), windows-latest-cmake-hip, windows-2022-cmake-cuda (12.4) and server-windows: the libcurl download step fails before any build in all four jobs (tar.exe: Error opening archive: Unrecognized archive format).
  • android-build: the runner's preinstalled sdkmanager is the wrong version, so sdkmanager tools fails with "Failed to find package 'tools'" before any build.
  • macOS-latest-cmake-arm64: -Werror errors in vendored vendor/minja/minja.hpp (-Wmissing-noreturn) and in the SDK's wstring_convert deprecation. This PR's unary-ops.cpp compiles there without warnings.
  • pyright type-check (both runs): 9 errors, all in examples/json_schema_pydantic_example.py and gguf-py/gguf/vocab.py, which this PR does not touch. They come from newer pydantic and sentencepiece type stubs. scripts/esn_training.py, the one Python file this PR changes, has no findings.
  • ubuntu-22-cmake-sycl and ubuntu-22-cmake-sycl-fp16: the installed oneAPI toolkit no longer ships syclcompat/math.hpp, which ggml-sycl/dpct/helper.hpp includes, so the build fails with file not found. This PR does not touch the SYCL backend.
  • ggml-ci-arm64-cpu-high-perf-sve: every ctest passes (37/37 and 39/39), including the new test-esn-activations on ARM. The job then fails its rerank check, rerank score 2 @ 0.040 (FAIL: score not in range [0.10, 0.30]). The scores are 0.032 / 0.024 / 0.040, exactly the same as master's run of this job. That check fails on master too, and this PR's tanh change does not move the scores.

I did not re-run them, because each fails deterministically in setup and would fail the same way again.


Generated by Claude Code

@drzo
drzo marked this pull request as ready for review October 28, 2026 17:04
Copilot AI balanced review requested due to automatic review settings October 28, 2026 17:04
@drzo
drzo merged commit 7783b9c into master Oct 28, 2026
48 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 change introduces undefined behavior in normal sigmoid execution and a test link failure when GGML_CPU=OFF, alongside accuracy regressions and ignored embedding adapters and scale overrides.

6 open issues
What changed in this PR

This PR speeds up ESN inference through vectorizable CPU activations and an optional precomputed per-token input table. The activation changes also affect other models using CPU tanh or sigmoid.

Changes:

  • Replace scalar activation calls with polynomial-based implementations.
  • Export and load input tables to replace repeated input-drive calculations, while retaining the embedding-input fallback.
  • Add activation accuracy tests, tensor checks, and documentation.
File Description
tests/​test-esn.cpp Check input-table tensor metadata and naming.
tests/​test-esn-activations.cpp Test activation accuracy, special values, and threading consistency.
tests/​CMakeLists.txt Register the CPU activation test.
src/​llama-model.h Add storage for the input-table tensor.
src/​llama-model.cpp Load and use input tables; skip identity scaling operations.
src/​llama-arch.h Declare the input-table tensor identifier.
src/​llama-arch.cpp Register its name and operation metadata.
scripts/​esn_training.py Export input tables by default with an opt-out flag.
ggml/​src/​ggml-cpu/​unary-ops.cpp Implement vectorizable tanh and sigmoid.
docs/​esn.md Document the optimizations, tests, and benchmark results.
CLAUDE.md Update ESN development guidance for input tables and activations.

Review effort: Balanced

p = (p * r) * r + r + 1.0f;
int32_t bits;
memcpy(&bits, &p, sizeof(bits));
bits += (int32_t) n << 23;
Comment thread tests/CMakeLists.txt
llama_build_and_test(test-grammar-integration.cpp)
llama_build_and_test(test-llama-grammar.cpp)
llama_build_and_test(test-esn.cpp)
if (NOT GGML_BACKEND_DL)

static inline float op_sigmoid(float x) {
return 1.f / (1.f + expf(-x));
const float s = 1.f / (1.f + op_expf_poly(-x));
Comment thread src/llama-model.cpp
// Optional: the whole input drive of each token,
// s_in·W_in·E[tok] + b_in + b_res + s_fb·W_fb[tok], which
// depends on the token alone. A row lookup like W_fb.
layers[0].esn_input_table = create_tensor(tn(LLM_TENSOR_ESN_INPUT_TABLE, "weight"), {reservoir_size, n_vocab}, TENSOR_NOT_REQUIRED);
Comment thread src/llama-model.cpp
// scales and adds, which matters most for single-token decoding, whose
// cost at small reservoirs is in the number of graph nodes.
ggml_tensor * u = nullptr;
if (model.layers[0].esn_input_table && res->t_tokens) {
return got == w ? 0.0 : INFINITY;
}
const float up = std::nextafter(std::fabs(w), INFINITY) - std::fabs(w);
return std::fabs((double) got - want) / up;
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 ggml testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants