Repository navigation
ESN: vectorized tanh/sigmoid and a per-token input table - #7
Merged
Merged
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
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
# Conflicts: # docs/esn.md
Author
|
These CI failures are not caused by this PR. They fail the same way on master, and no fix exists yet:
I did not re-run them, because each fails deterministically in setup and would fail the same way again. Generated by Claude Code |
There was a problem hiding this comment.
🟡 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
Avoid undefined left-shift of negative sigmoid exponent · New Require GGML_CPU before building the backend-dependent test · New Preserve sigmoid's negative tail instead of clamping it · New Bypass the table when input scales are overridden · New Do not discard adapted token embeddings · New Treat unexpected NaN activation results as infinite error · New
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; |
| 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)); |
| // 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); |
| // 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


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 3runs. Before = libmtanhf, no table; after = this PR:Changes
1. Vectorized
tanhandsigmoidon CPU (ggml/src/ggml-cpu/unary-ops.cpp)tanhwas libm's scalartanhf, about 20 ns per element. At R=1024 it was 14% of single-thread instructions, more than anything except theW_resmatvec.-fopt-info-vec): a minimax polynomial for |x| < 0.625, and an inlineexpabove that.ggml_tanhorggml_sigmoidon the CPU. Upstream ggml still uses scalartanhf.repack.cpp, and IntelLLVM builds get-fno-associative-math.2. Per-token input table
s_in·W_in·E[tok] + b_in + b_res + s_fb·W_fb[tok]depends on the token alone.scripts/esn_training.pynow stores it asesn_input_table([n_vocab, reservoir_size]);--no-input-tableomits it.llm_build_esnreads it with oneget_rows, replacing up to seven graph nodes. Each node ends with a thread barrier, which dominates small decode graphs.Verification
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 caughttanh(inf)returning 0.99999994; that is fixed by capping |x| at 10 instead of 9.test-esn: now covers the new tensor.test-esn-inferenceA..J: passes on table and no-table models, including Q4_0, F16, feedback and sigmoid.Notes
Generated by Claude Code