From 57c4e60fdf8f4c61cdc5b064422a43be266a3b16 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 18:04:45 +0000 Subject: [PATCH 1/3] graph : allow reusing graphs of recurrent models 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 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- src/llama-graph.cpp | 21 +++++++++++++++++++++ src/llama-graph.h | 6 ++++++ 2 files changed, 27 insertions(+) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 90cd885a60a4..242b8b4d0af2 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -251,6 +251,24 @@ void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { } } +bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) { + const auto * mctx = static_cast(params.mctx); + + this->mctx = mctx; + + bool res = true; + + res &= s_copy->ne[0] == mctx->get_n_rs(); + + res &= s_copy_main->ne[0] == params.ubatch.n_seqs; + res &= s_copy_extra->ne[0] == mctx->get_n_rs() - params.ubatch.n_seqs; + + res &= head == mctx->get_head(); + res &= rs_z == mctx->get_rs_z(); + + return res; +} + void llm_graph_input_cross_embd::set_input(const llama_ubatch * ubatch) { GGML_UNUSED(ubatch); @@ -1777,6 +1795,9 @@ static std::unique_ptr build_rs_inp_impl( inp->s_copy_main = ggml_view_1d(ctx0, inp->s_copy, n_seqs, 0); inp->s_copy_extra = ggml_view_1d(ctx0, inp->s_copy, n_rs - n_seqs, n_seqs * inp->s_copy->nb[0]); + inp->head = mctx_cur->get_head(); + inp->rs_z = mctx_cur->get_rs_z(); + return inp; } diff --git a/src/llama-graph.h b/src/llama-graph.h index 269428d6e1f2..5ae3364edbe3 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -225,6 +225,8 @@ class llm_graph_input_rs : public llm_graph_input_i { void set_input(const llama_ubatch * ubatch) override; + bool can_reuse(const llm_graph_params & params) override; + ggml_tensor * s_copy; // I32 [n_rs] // views of s_copy, computed once per graph @@ -233,6 +235,10 @@ class llm_graph_input_rs : public llm_graph_input_i { ggml_tensor * s_copy_extra; // I32 [n_rs - n_seqs] const llama_memory_recurrent_context * mctx; + + // used in view offsets and sizes, so the graph is only reusable when they match + uint32_t head; + int32_t rs_z; }; class llm_graph_input_cross_embd : public llm_graph_input_i { From 12c278435d08fc1e3cfa0ba8c26c6b597a48409b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 18:04:45 +0000 Subject: [PATCH 2/3] esn: stack per-token states in O(n) with ggml_set_rows 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 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- docs/esn.md | 41 +++++++++++++++-- src/llama-model.cpp | 87 ++++++++++++++++++++---------------- tests/test-esn-inference.cpp | 43 +++++++++++++----- 3 files changed, 119 insertions(+), 52 deletions(-) diff --git a/docs/esn.md b/docs/esn.md index e3247286c1ee..c6a63d3463f0 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -104,9 +104,11 @@ The ESN forward pass (`llm_build_esn` in `src/llama-model.cpp`) consists of: 6. **Leaky Integration**: `x(t+1) = (1-α)*x(t) + α*f(...)` (skipped when α = 1) 7. **State Storage**: `ggml_cpy` new state back to `esn_states_all` at `kv_head * reservoir_size` -8. **Output Stacking**: for multi-token batches, the per-token states are - concatenated in a balanced binary tree (O(n log n) bytes copied rather - than O(n²) for a left-to-right chain) +8. **Output Stacking**: for multi-token batches, each step's state is + written into its row of a `[reservoir_size, n_seq_tokens, n_seqs]` + buffer with `ggml_set_rows`, one row copy per step. Each write returns a + view of the whole buffer that depends on the previous one, so reading + the last sees them all 9. **Output Normalization & Projection**: RMS norm, then `W_out * reservoir_state → vocabulary_logits` @@ -486,6 +488,39 @@ script had not finished initializing it after 30 minutes. That this barely improves on R=8192 shows the ~67k-sample corpus, not the reservoir, is the limit at this scale. +### Graph Reuse and Output Stacking + +Two inference-side changes, each measured as an A/B on the same machine +(4-thread CPU, medians of five interleaved `llama-bench -r 3` runs, +untrained Q4_0 reservoirs at R ≤ 1024 and the trained Q4_0 models from +the table below at R = 2048 and 8192): + +- **Decode graph reuse.** The recurrent-state input never reported that a + graph could be reused, so llama.cpp rebuilt and re-allocated the graph + for every generated token of every recurrent architecture (Mamba and + RWKV as well as ESN). It now allows reuse when the state cells the graph + was built for (`head`, `rs_z`, `n_rs`) are unchanged, which is the case + for consecutive decode steps. +- **O(n) output stacking.** Prompt processing stacked the per-token + states in a balanced `ggml_concat` tree, copying each state log2(n) + times; it now writes each state once (step 8 above). + +| R | 256 | 1024 | 2048 | 8192 | +|---|---:|---:|---:|---:| +| tg256 (tok/s), rebuild every token → reuse | 16578 → 25732 | 9182 → 11673 | 4437 → 5458 | 597 → 672 | +| pp512 (tok/s), concat tree → `set_rows` | 66057 → 65988 | 11276 → 14196 | 5807 → 7494 | 729 → 723 | + +Both leave the logits bit-identical. Stacking costs nothing measurable when +the states stay in cache (R = 256) or when reading `W_res` dominates +(R = 8192). + +Batched and token-by-token decoding of the same text take different matmul +kernels for `W_in`, so their logits differ by rounding (~1e-5 with an F32 +reservoir). With a Q8_0 or Q4_0 reservoir that rounding can flip the +quantization of one state value, after which the later logits of that +sequence differ visibly (up to 0.1 relative to the largest logit in one +`test-esn-inference` sequence). + ### Quantized Reservoirs The same corpus and held-out file, with `--embedding-dim 64 --spectral-radius diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 3db88ccefafa..d062e459dd33 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -19392,6 +19392,26 @@ struct llm_build_apertus : public llm_graph_context { } }; +// Timestep indices 0..n_seq_tokens-1, used by llm_build_esn to write each +// step's reservoir state into its row of the per-token output buffer. +class llm_graph_input_esn_steps : public llm_graph_input_i { +public: + void set_input(const llama_ubatch * ubatch) override { + GGML_UNUSED(ubatch); + GGML_ASSERT(ggml_backend_buffer_is_host(steps->buffer)); + int32_t * data = (int32_t *) steps->data; + for (int64_t t = 0; t < steps->ne[0]; ++t) { + data[t] = (int32_t) t; + } + } + + bool can_reuse(const llm_graph_params & params) override { + return steps->ne[0] == (int64_t) params.ubatch.n_seq_tokens; + } + + ggml_tensor * steps = nullptr; // I32 [n_seq_tokens] +}; + // Echo State Network graph builder. // // Implements the ESN forward pass: @@ -19490,12 +19510,24 @@ struct llm_build_esn : public llm_graph_context_mamba { // x(t+1) = (1-α)·x(t) + α·f(W_res·x(t) + W_in·u(t) + W_fb·y(t-1) + b) // // We keep the (per-sequence) reservoir state current across the - // loop and collect each step's output so the final tensor has one - // reservoir vector per input token — matching what inp_out_ids - // indexes into and what the rest of llama.cpp expects for recurrent - // models. - std::vector per_token; - per_token.reserve(n_seq_tokens); + // loop. With more than one timestep, each step's state is also + // written into its row of `states`, laid out [reservoir_size, + // n_seq_tokens, n_seqs] so that it flattens to one reservoir vector + // per input token in the order inp_out_ids indexes. Every + // ggml_set_rows returns a view of the whole buffer that depends on + // the previous write, so reading the last one sees all of them, and + // the stacking costs one row copy per step. + ggml_tensor * states = nullptr; + ggml_tensor * steps = nullptr; + if (n_seq_tokens > 1) { + auto inp = std::make_unique(); + inp->steps = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seq_tokens); + ggml_set_input(inp->steps); + steps = inp->steps; + res->add_input(std::move(inp)); + + states = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, reservoir_size, n_seq_tokens, n_seqs); + } ggml_tensor * state = reservoir_state; // [reservoir_size, n_seqs] const size_t u_stride_t = reservoir_size * ggml_element_size(u); @@ -19525,7 +19557,11 @@ struct llm_build_esn : public llm_graph_context_mamba { state = ggml_add(ctx0, leaky_old, leaky_new); } - per_token.push_back(state); + 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))); + } } cb(state, "esn_reservoir_final", -1); @@ -19538,37 +19574,12 @@ struct llm_build_esn : public llm_graph_context_mamba { ggml_view_1d(ctx0, esn_states_all, reservoir_size * n_seqs, kv_head * reservoir_size * ggml_element_size(esn_states_all)))); - // Build the per-token output tensor expected by downstream layers: - // {reservoir_size, n_tokens}. Each column is the reservoir state at - // the time that token was processed. For n_seq_tokens == 1 (the - // common decode step) this is just the single state. - ggml_tensor * cur; - if (n_seq_tokens == 1) { - cur = ggml_reshape_2d(ctx0, per_token[0], reservoir_size, n_seqs); - } else { - // Stack timesteps along axis 1, then flatten (n_seq_tokens, n_seqs) - // down into the single n_tokens axis llama.cpp expects. Concatenate - // pairwise in a balanced tree: each state is copied log2(n) times, - // where a left-to-right chain re-copies the growing prefix at every - // step (O(n^2) bytes, which dominated long prompt prefill). - std::vector level; - level.reserve(n_seq_tokens); - for (ggml_tensor * s : per_token) { - level.push_back(ggml_reshape_3d(ctx0, s, reservoir_size, 1, n_seqs)); - } - while (level.size() > 1) { - std::vector next; - next.reserve((level.size() + 1) / 2); - for (size_t i = 0; i + 1 < level.size(); i += 2) { - next.push_back(ggml_concat(ctx0, level[i], level[i + 1], 1)); - } - if (level.size() % 2 == 1) { - next.push_back(level.back()); - } - level = std::move(next); - } - cur = ggml_reshape_2d(ctx0, level[0], reservoir_size, n_tokens); - } + // The per-token output expected downstream: {reservoir_size, n_tokens}, + // one column per input token. For the common single-token decode + // step this is just the state. + ggml_tensor * cur = states + ? ggml_reshape_2d(ctx0, states, reservoir_size, n_tokens) + : ggml_reshape_2d(ctx0, state, reservoir_size, n_seqs); cb(cur, "esn_reservoir_seq", -1); if (inp_out_ids) { diff --git a/tests/test-esn-inference.cpp b/tests/test-esn-inference.cpp index 7e75268aafe2..b9d0874fd076 100644 --- a/tests/test-esn-inference.cpp +++ b/tests/test-esn-inference.cpp @@ -121,7 +121,8 @@ static std::vector> stepwise_logits(llama_model * model, cons // Decode all sequences in one batch with every position as an output and // return the largest deviation from the stepwise reference, relative to the // reference's magnitude. -static double batched_rel_error(llama_model * model, const std::vector> & seqs, +// Per sequence, per position: max|Δ| / (1 + max|ref|). +static std::vector> batched_rel_errors(llama_model * model, const std::vector> & seqs, const std::vector>> & refs, int32_t n_vocab) { int32_t n_total = 0; for (const auto & s : seqs) n_total += (int32_t) s.size(); @@ -142,7 +143,7 @@ static double batched_rel_error(llama_model * model, const std::vector> errs(seqs.size()); int32_t i = 0; for (size_t s = 0; s < seqs.size(); ++s) { for (size_t t = 0; t < seqs[s].size(); ++t, ++i) { @@ -150,12 +151,34 @@ static double batched_rel_error(llama_model * model, const std::vector got(p, p + n_vocab); const auto & want = refs[s][t]; - worst = std::fmax(worst, max_abs_diff(got, want) / (1.0 + max_abs(want))); + errs[s].push_back(max_abs_diff(got, want) / (1.0 + max_abs(want))); } } llama_batch_free(batch); llama_free(ctx); - return worst; + return errs; +} + +// Batched and stepwise decodes may take different matmul kernels, so their +// logits differ by rounding: ~1e-5 for an F32 reservoir, ~1e-3 for an F16 one +// (its product rounds the state to F16). A Q8_0/Q4_0 reservoir quantizes the +// state at every step, and a rounding difference that flips one value starts +// at about one quantization step and then grows through the recurrence. A +// misplaced row instead jumps straight from a close match to O(1), since the +// readout does not feed back. Returns false on such a jump. +static bool batch_matches_stepwise(const std::vector> & errs, double & worst) { + worst = 0.0; + for (const auto & seq : errs) { + double prev = 0.0; + for (double e : seq) { + if (prev < 1e-3 && e >= 1e-2) { + return false; + } + worst = std::fmax(worst, e); + prev = e; + } + } + return true; } int main(int argc, char ** argv) { @@ -259,13 +282,11 @@ int main(int argc, char ** argv) { } const auto ref_p = stepwise_logits(model, seq_p, n_vocab); const auto ref_q = stepwise_logits(model, seq_q, n_vocab); - const double err_one = batched_rel_error(model, { seq_p }, { ref_p }, n_vocab); - const double err_two = batched_rel_error(model, { seq_p, seq_q }, { ref_p, ref_q }, n_vocab); - // Batched and stepwise decodes may take different matmul kernels, so - // allow rounding: ~1e-5 for an F32 reservoir, ~1e-3 for an F16 one - // (its product rounds the state to F16). A misplaced row is off by O(1). - assert(err_one < 1e-2 && "J: one-sequence batched logits must match stepwise decoding"); - assert(err_two < 1e-2 && "J: two-sequence batched logits must match stepwise decoding"); + double err_one = 0.0, err_two = 0.0; + const bool ok_one = batch_matches_stepwise(batched_rel_errors(model, { seq_p }, { ref_p }, n_vocab), err_one); + const bool ok_two = batch_matches_stepwise(batched_rel_errors(model, { seq_p, seq_q }, { ref_p, ref_q }, n_vocab), err_two); + assert(ok_one && "J: one-sequence batched logits must match stepwise decoding"); + assert(ok_two && "J: two-sequence batched logits must match stepwise decoding"); fprintf(stderr, "test-esn-inference: J OK (batched vs stepwise, rel. max|Δ|: 1 seq %.3g, 2 seqs %.3g)\n", err_one, err_two); From 3c1bf3c29ef151bed056d4707e3e6582753e3041 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 16:50:00 +0000 Subject: [PATCH 3/3] Vectorized tanh/sigmoid and a per-token ESN input table 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 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- CLAUDE.md | 6 ++ docs/esn.md | 58 +++++++++++++- ggml/src/ggml-cpu/unary-ops.cpp | 49 +++++++++++- scripts/esn_training.py | 26 ++++++- src/llama-arch.cpp | 2 + src/llama-arch.h | 1 + src/llama-model.cpp | 68 +++++++++++------ src/llama-model.h | 3 + tests/CMakeLists.txt | 4 + tests/test-esn-activations.cpp | 130 ++++++++++++++++++++++++++++++++ tests/test-esn.cpp | 5 ++ 11 files changed, 320 insertions(+), 32 deletions(-) create mode 100644 tests/test-esn-activations.cpp diff --git a/CLAUDE.md b/CLAUDE.md index b30fe4fea4fa..c59efe25eeb8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,6 +50,7 @@ esn_output_weights.weight [n_vocab, reservoir_size] esn_feedback_weights.weight [n_vocab, reservoir_size] (optional, row per fed-back token) esn_input_bias.weight [reservoir_size] (optional) esn_reservoir_bias.weight [reservoir_size] (optional) +esn_input_table.weight [n_vocab, reservoir_size] (optional, input drive per token) ``` ## Build Commands @@ -125,6 +126,11 @@ python scripts/esn_training.py --reservoir-size 8192 --reg-grid 1,10,100,1000 \ --outtype q4_0 --train-data corpus.txt --output model.gguf ``` +`esn_training.py` stores each token's whole input drive as `esn_input_table` +(`--no-input-table` to omit it); with token inputs the graph reads it instead +of computing W_in·E + biases + feedback. The CPU `tanh`/`sigmoid` are +branch-free so they vectorize (`tests/test-esn-activations.cpp` checks them). + Batch training holds out `--val-fraction` (default 10%) of the sequences to pick λ from `--reg-grid` and to fit a softmax temperature that is folded into `W_out` (disable with `--no-calibrate`). diff --git a/docs/esn.md b/docs/esn.md index c6a63d3463f0..d41ed63e7595 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -73,6 +73,7 @@ training and inference run the same recurrence. | `esn_feedback_weights` | `[n_vocab, reservoir_size]` | Output-to-reservoir feedback, one row per token (optional) | | `esn_input_bias` | `[reservoir_size]` | Input projection bias (optional) | | `esn_reservoir_bias` | `[reservoir_size]` | Reservoir activation bias (optional) | +| `esn_input_table` | `[n_vocab, reservoir_size]` | Whole input drive of each token, read instead of computing it from the tensors above (optional; see below) | ## Implementation Details @@ -96,6 +97,10 @@ The ESN forward pass (`llm_build_esn` in `src/llama-model.cpp`) consists of: `esn_feedback_weights` is loaded, add `esn_feedback_scaling` times the `W_fb` row of each input token (a `get_rows`, done for the whole batch before the recurrence because it does not depend on the state) + + With token inputs, steps 1 and 2 depend on the token alone. When the + model has `esn_input_table`, its row for each token replaces them (one + `get_rows`); embedding inputs still take steps 1 and 2 3. **State Retrieval**: Get previous reservoir state via `llama_memory_recurrent_context::get_s_l(0)` and `build_rs()` 4. **Recurrent Projection**: `W_res * x(t)`, added to the input drive @@ -367,11 +372,16 @@ build/bin/test-esn-inference /tmp/esn-smoke.gguf Static test coverage (`tests/test-esn.cpp`): - Architecture recognition and name mapping - Recurrent / hybrid / diffusion classification -- Tensor info mappings for all 6 ESN tensors (weights + biases + feedback) +- Tensor info mappings for all 7 ESN tensors (weights + biases + feedback + + input table) - Hyperparameter defaults (base + extended) - Tensor name generation - `n_embd_s()` returns `reservoir_size` for ESN models +Activation accuracy (`tests/test-esn-activations.cpp`, a CTest): the CPU +backend's `tanh` and `sigmoid` against double-precision references, special +values, and multi-row / multi-thread consistency. + End-to-end inference coverage (`tests/test-esn-inference.cpp`): - GGUF metadata & tensor-shape loading for `arch=esn` - `llama_memory_recurrent` allocation sized by `n_embd_s()` @@ -411,6 +421,7 @@ python scripts/esn_training.py --init-only --reservoir-size 2048 --output untrai | Validation split | `--val-fraction` | 0.1 | Sequences held out to pick lambda and fit the temperature | | Lambda search | `--reg-grid` | (off) | Comma-separated lambdas, chosen by held-out NLL | | No calibration | `--no-calibrate` | (off) | Export raw ridge outputs as logits | +| No input table | `--no-input-table` | (off) | Do not store `esn_input_table` (`n_vocab * reservoir_size` floats; inference then computes the input drive) | | Reservoir type | `--outtype` | `f32` | `f16`, `q8_0` or `q4_0` (16, 8.5 or 4.5 bits per weight) shrink the reservoir and its per-token read; the quantized types need a reservoir size that is a multiple of 32 | ### Training Process @@ -514,13 +525,54 @@ Both leave the logits bit-identical. Stacking costs nothing measurable when the states stay in cache (R = 256) or when reading `W_res` dominates (R = 8192). -Batched and token-by-token decoding of the same text take different matmul -kernels for `W_in`, so their logits differ by rounding (~1e-5 with an F32 +Without an input table, batched and token-by-token decoding of the same +text take different matmul kernels for `W_in`, so their logits differ by rounding (~1e-5 with an F32 reservoir). With a Q8_0 or Q4_0 reservoir that rounding can flip the quantization of one state value, after which the later logits of that sequence differ visibly (up to 0.1 relative to the largest logit in one `test-esn-inference` sequence). +### Vectorized Activations and the Input Table + +At small and medium reservoirs, a token's time went mostly to two things +other than reading `W_res`: + +- **The activation.** The CPU backend computed `tanh` with libm's scalar + `tanhf`, about 20 ns per element here: at R = 1024 it was 14 % of the + single-thread instructions, more than everything but the `W_res` matvec. + A state is one row, so the op also ran on one thread while the others + waited. `tanh` and `sigmoid` in `ggml/src/ggml-cpu/unary-ops.cpp` are now + branch-free (a minimax polynomial below |x| = 0.625, an inline `exp` + above), so the compiler vectorizes them: 0.8 ns per element with AVX2, + within 1.2 ulp of `tanh` and 2 ulp of the logistic function + (`tests/test-esn-activations.cpp`), like libm's. This applies to every + model that uses `ggml_tanh` or `ggml_sigmoid` on the CPU. +- **Graph nodes.** A decode step is a short chain of small ops, and each + op ends with a barrier across threads. The input drive took up to seven + of them (projection, scale, two bias adds, feedback lookup, scale, add) + although it depends on the token alone; `scripts/esn_training.py` now + stores it per token as `esn_input_table` (`--no-input-table` to omit it), + and the graph reads it with one `get_rows`. A scale by 1 is also no + longer emitted. For the default 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). + +Before (libm `tanhf`, no table) → after, on the same machine (4-thread CPU, +medians of eight interleaved `llama-bench -r 3` runs; `--use-bias +--leaking-rate 0.5` reservoirs, Q4_0 at R ≤ 1024, F32 at R = 2048, and the +R = 8192 Q4_0 model of the next table without a table): + +| R | 256 | 1024 | 2048 | 8192 | +|---|---:|---:|---:|---:| +| pp512 (tok/s) | 64846 → 123743 | 20361 → 37590 | 4784 → 6000 | 893 → 970 | +| tg256 (tok/s) | 25659 → 32764 | 11956 → 18560 | 3470 → 4440 | 766 → 852 | + +Most of this is the activation (pp512 +64 % and tg256 +27 % at R = 1024 +from it alone); the table adds 16-18 % to R = 1024 decoding and is within +this machine's noise at R = 256. Logits move by rounding only (≤ 1.1e-6 +relative to the largest logit for F32 reservoirs; held-out perplexity and +the C++/Python parity are unchanged). + ### Quantized Reservoirs The same corpus and held-out file, with `--embedding-dim 64 --spectral-radius diff --git a/ggml/src/ggml-cpu/unary-ops.cpp b/ggml/src/ggml-cpu/unary-ops.cpp index cf1a4615d042..a170c4325834 100644 --- a/ggml/src/ggml-cpu/unary-ops.cpp +++ b/ggml/src/ggml-cpu/unary-ops.cpp @@ -1,5 +1,8 @@ #include "unary-ops.h" +#include +#include + static inline float op_abs(float x) { return fabsf(x); } @@ -16,8 +19,49 @@ static inline float op_step(float x) { return (x > 0.f) ? 1.f : 0.f; } +// expf without a libm call, so that the loops in tanh and sigmoid below +// auto-vectorize: x = n*ln2 + r with |r| <= ln2/2, exp(r) by the Cephes +// polynomial and n added to the exponent bits. Within 1 ulp of exp on the +// clamped range [-86.6, 88.3], which keeps 2^n a normal float; NaN maps to +// the lower bound (callers that care propagate it themselves). +static inline float op_expf_poly(float x) { + x = x > -86.6f ? x : -86.6f; + x = x < 88.3f ? x : 88.3f; + const float n = (x * 1.44269504088896341f + 12582912.0f) - 12582912.0f; // round to nearest + const float r = (x - n * 0.693359375f) + n * 2.12194440e-4f; // x - n*ln2 in two parts + float p = 1.9875691500e-4f; + p = p * r + 1.3981999507e-3f; + p = p * r + 8.3334519073e-3f; + p = p * r + 4.1665795894e-2f; + p = p * r + 1.6666665459e-1f; + p = p * r + 5.0000001201e-1f; + p = (p * r) * r + r + 1.0f; + int32_t bits; + memcpy(&bits, &p, sizeof(bits)); + bits += (int32_t) n << 23; + memcpy(&p, &bits, sizeof(p)); + return p; +} + +// Branch-free tanh, within 1 ulp like libm's tanhf but vectorizable (scalar +// tanhf dominates small recurrent graphs, e.g. echo state networks). +// |x| < 0.625: x*P(x^2), a minimax fit of tanh(x)/x; above it +// 1 - 2/(exp(2|x|) + 1), whose cancellation is harmless there. |x| is capped +// at 10, past where tanh rounds to 1. static inline float op_tanh(float x) { - return tanhf(x); + const float ax = fabsf(x); + const float a = ax < 10.0f ? ax : 10.0f; + const float a2 = a * a; + float q = 2.1286243572831154e-3f; + q = q * a2 - 8.15926119685173e-3f; + q = q * a2 + 2.169189229607582e-2f; + q = q * a2 - 5.394471436738968e-2f; + q = q * a2 + 1.3333183526992798e-1f; + q = q * a2 - 3.33333283662796e-1f; + const float small = (q * a2) * a + a; + const float large = 1.0f - 2.0f / (op_expf_poly(2.0f * a) + 1.0f); + const float t = copysignf(a < 0.625f ? small : large, x); + return x != x ? x : t; } static inline float op_elu(float x) { @@ -29,7 +73,8 @@ static inline float op_relu(float x) { } 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)); + return x != x ? x : s; } static inline float op_hardsigmoid(float x) { diff --git a/scripts/esn_training.py b/scripts/esn_training.py index 10a8ed561544..9007ccb5d1d9 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -415,6 +415,16 @@ def _input_drive(self, embeddings: np.ndarray, tokens: Optional[np.ndarray]) -> drive += self.config.feedback_scaling * self.W_fb[tokens] return drive + def input_table(self) -> np.ndarray: + """ + The input drive of every token, [vocab_size, reservoir_size]. + + With token inputs, _input_drive depends on the token alone, so + save_gguf stores it per token and llm_build_esn reads each token's + drive with one row lookup instead of computing it. + """ + return self._input_drive(self.tok_embd.T, np.arange(self.config.vocab_size)) + def forward( self, embeddings: np.ndarray, @@ -851,7 +861,7 @@ def online_train_sequence( "final_state": state.copy(), } - def save_gguf(self, path: str) -> None: + def save_gguf(self, path: str, input_table: bool = True) -> None: """ Save the ESN model as a GGUF file compatible with esn.cpp's ``llm_build_esn`` graph builder. @@ -880,6 +890,8 @@ def save_gguf(self, path: str) -> None: - ``esn_feedback_weights.weight`` [reservoir_size, n_vocab] (optional) - ``esn_input_bias.weight`` (optional) - ``esn_reservoir_bias.weight`` (optional) + - ``esn_input_table.weight`` [reservoir_size, n_vocab] + (unless input_table=False; see input_table()) """ if not self._initialized: raise RuntimeError("ESN not initialized. Call initialize() first.") @@ -960,6 +972,8 @@ def save_gguf(self, path: str) -> None: # -> numpy (n_vocab, reservoir) [matches training layout] # esn_input_bias.weight C++ {reservoir} [1-D] # esn_reservoir_bias.weight C++ {reservoir} [1-D] + # esn_input_table.weight C++ {reservoir, n_vocab} + # -> numpy (n_vocab, reservoir) def _f32(x: np.ndarray) -> np.ndarray: return np.ascontiguousarray(x, dtype=np.float32) @@ -983,6 +997,10 @@ def _f32(x: np.ndarray) -> np.ndarray: writer.add_tensor("esn_input_bias.weight", _f32(self.b_in)) if self.b_res is not None: writer.add_tensor("esn_reservoir_bias.weight", _f32(self.b_res)) + if input_table: + # Read instead of W_in, the biases and W_fb for token inputs; those + # stay in the file for embedding inputs. + writer.add_tensor("esn_input_table.weight", _f32(self.input_table())) writer.write_header_to_file() writer.write_kv_data_to_file() @@ -1189,6 +1207,10 @@ def main(): "(picked by held-out NLL); default: --regularization only") parser.add_argument("--no-calibrate", action="store_true", help="Do not fit a softmax temperature (export raw ridge outputs as logits)") + parser.add_argument("--no-input-table", action="store_true", + help="Do not store the per-token input drive (vocab_size x " + "reservoir_size floats) that inference reads instead of " + "computing it") parser.add_argument("--outtype", choices=list(RESERVOIR_TYPES), default="f32", help="Storage type of the reservoir matrix in the GGUF. The readout " "is trained on the rounded reservoir; q8_0 and q4_0 need a " @@ -1352,7 +1374,7 @@ def main(): logger.info(f"Final training accuracy: {accuracy:.4f}") # Save to GGUF - esn.save_gguf(args.output) + esn.save_gguf(args.output, input_table=not args.no_input_table) logger.info(f"\nModel saved to {args.output}") logger.info("\nTo use with llama.cpp:") logger.info(f" ./llama-cli -m {args.output} -p \"Your prompt here\"") diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index c5de881cf6a1..9c9f61368dad 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -2184,6 +2184,7 @@ static const std::map> LLM_TENSOR_N { LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, "esn_feedback_weights" }, { LLM_TENSOR_ESN_INPUT_BIAS, "esn_input_bias" }, { LLM_TENSOR_ESN_RESERVOIR_BIAS, "esn_reservoir_bias" }, + { LLM_TENSOR_ESN_INPUT_TABLE, "esn_input_table" }, }, }, { @@ -2476,6 +2477,7 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}}, {LLM_TENSOR_ESN_INPUT_BIAS, {LLM_TENSOR_LAYER_INPUT, GGML_OP_ADD}}, {LLM_TENSOR_ESN_RESERVOIR_BIAS, {LLM_TENSOR_LAYER_INPUT, GGML_OP_ADD}}, + {LLM_TENSOR_ESN_INPUT_TABLE, {LLM_TENSOR_LAYER_INPUT, GGML_OP_GET_ROWS}}, }; LLM_KV::LLM_KV(llm_arch arch, const char * suffix) : arch(arch), suffix(suffix) {} diff --git a/src/llama-arch.h b/src/llama-arch.h index 90a005ac68a2..0a28953d05eb 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -483,6 +483,7 @@ enum llm_tensor { LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, // output-to-reservoir feedback LLM_TENSOR_ESN_INPUT_BIAS, // reservoir input bias LLM_TENSOR_ESN_RESERVOIR_BIAS, // reservoir bias + LLM_TENSOR_ESN_INPUT_TABLE, // precomputed per-token input drive }; enum llm_tensor_layer { diff --git a/src/llama-model.cpp b/src/llama-model.cpp index d062e459dd33..a222da284444 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -6065,6 +6065,11 @@ bool llama_model::load_tensors(llama_model_loader & ml) { // Optional: bias vectors (same length as reservoir). layers[0].bq = create_tensor(tn(LLM_TENSOR_ESN_INPUT_BIAS, "weight"), {reservoir_size}, TENSOR_NOT_REQUIRED); layers[0].bk = create_tensor(tn(LLM_TENSOR_ESN_RESERVOIR_BIAS, "weight"), {reservoir_size}, TENSOR_NOT_REQUIRED); + + // 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); } break; default: throw std::runtime_error("unknown architecture"); @@ -19470,32 +19475,45 @@ struct llm_build_esn : public llm_graph_context_mamba { reservoir_state = ggml_reshape_2d(ctx0, reservoir_state, reservoir_size, n_seqs); cb(reservoir_state, "esn_state", -1); - // W_in * inpL: {n_embd, reservoir_size} * {n_embd, n_tokens} - // -> {reservoir_size, n_tokens} - // (ggml_mul_mat contracts over ne[0]; see tensor-shape comments in - // the create_tensor block above.) - ggml_tensor * u = ggml_mul_mat(ctx0, model.layers[0].wq, inpL); - u = ggml_scale(ctx0, u, hparams.esn_input_scaling); - // Both biases are constant over time, so they are added to the input - // drive once per ubatch rather than once per timestep. - if (model.layers[0].bq) { - u = ggml_add(ctx0, u, model.layers[0].bq); - } - if (model.layers[0].bk) { - u = ggml_add(ctx0, u, model.layers[0].bk); - } - - // Output feedback W_fb·y(t-1). y(t-1) is the one-hot of the token - // emitted at t-1, i.e. this step's input token: the sampled token in - // generation and the true one in training (teacher forcing), so - // scripts/esn_training.py runs the same recurrence. Being a row lookup - // that does not depend on the state, it is added to the input drive - // for all timesteps at once. - if (model.layers[0].wv && feedback_scaling > 0.0f) { - GGML_ASSERT(res->t_tokens != nullptr && "ESN output feedback needs token inputs, not embeddings"); + // The input drive s_in·W_in·u(t) + b_in + b_res + s_fb·W_fb·y(t-1) + // does not depend on the state, so it is computed for all timesteps + // at once. y(t-1), the one-hot of the token emitted at t-1, is this + // step's input token: the sampled token in generation and the true + // one in training (teacher forcing), so scripts/esn_training.py runs + // the same recurrence. + // + // With token inputs the drive depends on the token alone, and a model + // may store it per token: one row lookup then replaces the projection, + // 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) { // {reservoir_size, n_vocab} rows -> {reservoir_size, n_tokens} - ggml_tensor * fb = ggml_get_rows(ctx0, model.layers[0].wv, res->t_tokens); - u = ggml_add(ctx0, u, ggml_scale(ctx0, fb, feedback_scaling)); + u = ggml_get_rows(ctx0, model.layers[0].esn_input_table, res->t_tokens); + } else { + // W_in * inpL: {n_embd, reservoir_size} * {n_embd, n_tokens} + // -> {reservoir_size, n_tokens} + // (ggml_mul_mat contracts over ne[0]; see tensor-shape comments in + // the create_tensor block above.) + u = ggml_mul_mat(ctx0, model.layers[0].wq, inpL); + if (hparams.esn_input_scaling != 1.0f) { + u = ggml_scale(ctx0, u, hparams.esn_input_scaling); + } + if (model.layers[0].bq) { + u = ggml_add(ctx0, u, model.layers[0].bq); + } + if (model.layers[0].bk) { + u = ggml_add(ctx0, u, model.layers[0].bk); + } + if (model.layers[0].wv && feedback_scaling > 0.0f) { + GGML_ASSERT(res->t_tokens != nullptr && "ESN output feedback needs token inputs, not embeddings"); + // {reservoir_size, n_vocab} rows -> {reservoir_size, n_tokens} + ggml_tensor * fb = ggml_get_rows(ctx0, model.layers[0].wv, res->t_tokens); + if (feedback_scaling != 1.0f) { + fb = ggml_scale(ctx0, fb, feedback_scaling); + } + u = ggml_add(ctx0, u, fb); + } } cb(u, "esn_input_proj", -1); diff --git a/src/llama-model.h b/src/llama-model.h index eec564e70b69..c99a0d48a202 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -302,6 +302,9 @@ struct llama_layer { struct ggml_tensor * ssm_conv1d_b = nullptr; struct ggml_tensor * ssm_dt_b = nullptr; + // esn + struct ggml_tensor * esn_input_table = nullptr; + // rwkv struct ggml_tensor * time_mix_w1 = nullptr; struct ggml_tensor * time_mix_w2 = nullptr; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f42506e5e1a8..25f762838f1d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -145,6 +145,10 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) 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) + # calls the CPU backend directly + llama_build_and_test(test-esn-activations.cpp) + endif() # These need model/text arguments at runtime, so build without a CTest: # bin/test-esn-inference # bin/test-esn-perplexity diff --git a/tests/test-esn-activations.cpp b/tests/test-esn-activations.cpp new file mode 100644 index 000000000000..dd1cb3515f0a --- /dev/null +++ b/tests/test-esn-activations.cpp @@ -0,0 +1,130 @@ +// Accuracy of the ESN reservoir activations on the CPU backend. +// +// ggml-cpu computes tanh and sigmoid branch-free (no libm call) so the loops +// vectorize; the reservoir applies one of them to every state element at +// every timestep. This checks them against double-precision references: +// +// A. tanh within 2 ulp over [-12, 12], and exact at the special values +// (±0, ±inf, NaN, tiny inputs). +// B. sigmoid within 4 ulp over [-80, 80], saturating at ±inf, NaN kept. +// C. The same results with several threads and rows, so the vectorized +// body and the scalar tail of each row agree. + +#ifdef NDEBUG +#undef NDEBUG +#endif + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include + +// Distance in units in the last place of `want` (rounded to float). +static double ulp_err(float got, double want) { + const float w = (float) want; + if (std::isnan(w)) { + return std::isnan(got) ? 0.0 : INFINITY; + } + if (std::isinf(w)) { + 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; +} + +enum class act { tanh, sigmoid }; + +// Apply the activation with ggml to x laid out as [ncols, nrows]. +static std::vector run(act a, const std::vector & x, int64_t ncols, int n_threads) { + const int64_t nrows = (int64_t) x.size() / ncols; + ggml_init_params ip = { /*mem_size*/ 2 * x.size() * sizeof(float) + 4 * ggml_tensor_overhead() + ggml_graph_overhead(), + /*mem_buffer*/ nullptr, /*no_alloc*/ false }; + ggml_context * ctx = ggml_init(ip); + ggml_tensor * in = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ncols, nrows); + memcpy(in->data, x.data(), x.size() * sizeof(float)); + ggml_tensor * out = a == act::tanh ? ggml_tanh(ctx, in) : ggml_sigmoid(ctx, in); + ggml_cgraph * gf = ggml_new_graph(ctx); + ggml_build_forward_expand(gf, out); + const ggml_status st = ggml_graph_compute_with_ctx(ctx, gf, n_threads); + assert(st == GGML_STATUS_SUCCESS); + std::vector y((const float *) out->data, (const float *) out->data + x.size()); + ggml_free(ctx); + return y; +} + +// Evenly spaced bit patterns of the non-negative floats up to `hi`, mirrored. +static std::vector sweep(float hi, int n) { + uint32_t top; + memcpy(&top, &hi, sizeof(top)); + std::vector x; + for (int i = 0; i < n; ++i) { + uint32_t b = (uint32_t) ((uint64_t) top * i / (n - 1)); + float v; + memcpy(&v, &b, sizeof(v)); + x.push_back(v); + x.push_back(-v); + } + return x; +} + +static double ref(act a, float x) { + return a == act::tanh ? std::tanh((double) x) : 1.0 / (1.0 + std::exp(-(double) x)); +} + +static void check(act a, const char * name, float hi, double max_ulp) { + const std::vector x = sweep(hi, 1 << 18); + const std::vector y = run(a, x, (int64_t) x.size(), 1); + double worst = 0.0; + float worst_x = 0.0f; + for (size_t i = 0; i < x.size(); ++i) { + const double e = ulp_err(y[i], ref(a, x[i])); + if (e > worst) { + worst = e; + worst_x = x[i]; + } + } + printf(" %-7s max error %.2f ulp (at x = %g, limit %.0f)\n", name, worst, worst_x, max_ulp); + assert(worst <= max_ulp); + + // C: several rows with an odd length, so each row has a scalar tail, and + // several threads; every element must match the single-row result. + const int64_t ncols = 1027; + const std::vector xs(x.begin(), x.begin() + ncols * 64); + const std::vector one = run(a, xs, (int64_t) xs.size(), 1); + const std::vector rows = run(a, xs, ncols, 4); + assert(memcmp(one.data(), rows.data(), one.size() * sizeof(float)) == 0); +} + +int main() { + printf("test-esn-activations:\n"); + + check(act::tanh, "tanh", 12.0f, 2.0); + { + const std::vector x = { 0.0f, -0.0f, INFINITY, -INFINITY, NAN, 1e-30f, -1e-30f, 1e-40f, 20.0f, -20.0f }; + const std::vector y = run(act::tanh, x, (int64_t) x.size(), 1); + assert(y[0] == 0.0f && !std::signbit(y[0])); + assert(y[1] == 0.0f && std::signbit(y[1])); + assert(y[2] == 1.0f && y[3] == -1.0f); + assert(std::isnan(y[4])); + assert(y[5] == 1e-30f && y[6] == -1e-30f && y[7] == 1e-40f); + assert(y[8] == 1.0f && y[9] == -1.0f); + } + + check(act::sigmoid, "sigmoid", 80.0f, 4.0); + { + const std::vector x = { 0.0f, INFINITY, -INFINITY, NAN, 100.0f }; + const std::vector y = run(act::sigmoid, x, (int64_t) x.size(), 1); + assert(y[0] == 0.5f); + assert(y[1] == 1.0f && y[2] >= 0.0f && y[2] < 1e-37f); + assert(std::isnan(y[3])); + assert(y[4] == 1.0f); + } + + printf("test-esn-activations: PASSED (A..C)\n"); + return 0; +} diff --git a/tests/test-esn.cpp b/tests/test-esn.cpp index 0e256f03d14f..6a08e3fa0de1 100644 --- a/tests/test-esn.cpp +++ b/tests/test-esn.cpp @@ -81,6 +81,9 @@ int main() { const llm_tensor_info & rb_info = llm_tensor_info_for(LLM_TENSOR_ESN_RESERVOIR_BIAS); assert(rb_info.layer == LLM_TENSOR_LAYER_INPUT); assert(rb_info.op == GGML_OP_ADD); + const llm_tensor_info & it_info = llm_tensor_info_for(LLM_TENSOR_ESN_INPUT_TABLE); + assert(it_info.layer == LLM_TENSOR_LAYER_INPUT); + assert(it_info.op == GGML_OP_GET_ROWS); // row per input token std::cout << "PASSED\n"; } @@ -148,6 +151,7 @@ int main() { std::string feedback_name = tn(LLM_TENSOR_ESN_FEEDBACK_WEIGHTS); std::string input_bias = tn(LLM_TENSOR_ESN_INPUT_BIAS); std::string reservoir_bias = tn(LLM_TENSOR_ESN_RESERVOIR_BIAS); + std::string input_table = tn(LLM_TENSOR_ESN_INPUT_TABLE); assert(input_name == "esn_input_weights"); assert(reservoir_name == "esn_reservoir_weights"); @@ -155,6 +159,7 @@ int main() { assert(feedback_name == "esn_feedback_weights"); assert(input_bias == "esn_input_bias"); assert(reservoir_bias == "esn_reservoir_bias"); + assert(input_table == "esn_input_table"); std::cout << "PASSED\n"; }