From 57c4e60fdf8f4c61cdc5b064422a43be266a3b16 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 18:04:45 +0000 Subject: [PATCH 01/10] 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 02/10] 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 03/10] 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"; } From b3f1d5ef742b5421a108599d1679096d61fe171a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 17:33:12 +0000 Subject: [PATCH 04/10] ESN: implement the online readout API; refuse unsupported configs The llama_esn_* functions declared in llama.h had no definitions. They now retrain a per-context copy of W_out from feedback: - Contexts on models exported with esn.online_learning.enabled record the readout input (result_norm) of every output position, keyed by (seq_id, pos), bounded by esn.replay_window. - llama_esn_submit_feedback turns corrections, tool results, rewards and confidences into weighted samples (all-or-nothing, bounded by esn.online_learning.buf_size); latency events are rejected. - llama_esn_update_readout fits the context's F32 readout by ridge (Woodbury, refit from the checkpoint over the replay window), RLS or SGD. The graph uses it instead of the model tensor; other contexts and the model are unchanged. llama_esn_reset_adaptation returns to the checkpoint. - New esn.output_temperature records the scale the exported readout was fit to, so least-squares updates keep it; new llama_esn_model_online_params returns the exported settings. Silent degradations removed: the loader refuses esn.bidirectional, hierarchical keys and an unfrozen reservoir instead of warning or ignoring them; esn_training.py requires --train-data (no random-token fallback), errors on a byte tokenizer with vocab != 256 instead of overriding it, and writes online metadata with the correct mode for any trained model. tests/test-esn-online.cpp checks each mode against its closed form, reset, per-context isolation, graph reuse and the error codes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- CLAUDE.md | 17 +- docs/esllm-roadmap.md | 29 +- docs/esn-completion.md | 3 +- docs/esn.md | 93 ++++-- include/llama.h | 127 ++++---- scripts/esn_training.py | 143 +++++---- src/CMakeLists.txt | 1 + src/llama-arch.cpp | 1 + src/llama-arch.h | 1 + src/llama-context.cpp | 23 ++ src/llama-context.h | 9 + src/llama-esn.cpp | 606 ++++++++++++++++++++++++++++++++++++++ src/llama-esn.h | 101 +++++++ src/llama-graph.cpp | 2 + src/llama-graph.h | 12 + src/llama-hparams.cpp | 31 +- src/llama-hparams.h | 7 +- src/llama-model.cpp | 15 +- tests/CMakeLists.txt | 2 + tests/test-esn-online.cpp | 398 +++++++++++++++++++++++++ 20 files changed, 1441 insertions(+), 180 deletions(-) create mode 100644 src/llama-esn.cpp create mode 100644 src/llama-esn.h create mode 100644 tests/test-esn-online.cpp diff --git a/CLAUDE.md b/CLAUDE.md index c59efe25eeb8..e89e895ebbba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,9 @@ x(t+1) = (1-α) * x(t) + α * tanh(W_res * x(t) + W_in * u(t)) - `src/llama-hparams.h` - ESN hyperparameters (reservoir_size, spectral_radius, etc.) - `src/llama-model.cpp` - Model loading and forward pass (`llm_build_esn`) - `docs/esn.md` - Comprehensive ESN documentation +- `src/llama-esn.{h,cpp}` - Online readout adaptation (`llama_esn_*` API) - `tests/test-esn.cpp` - ESN architecture tests +- `tests/test-esn-online.cpp` - Online adaptation tests (ridge/RLS/SGD, reset) - `scripts/esn_training.py` - Python utility for ESN training and GGUF creation ### ESN Hyperparameters @@ -37,7 +39,8 @@ x(t+1) = (1-α) * x(t) + α * tanh(W_res * x(t) + W_in * u(t)) | `esn_feedback_scaling` | 0.0 | Output-to-reservoir feedback (0 = disabled) | | `esn_noise_level` | 0.0 | Noise injection for regularization | | `esn_activation_type` | 0 | Activation: 0=tanh, 1=sigmoid, 2=leaky_relu | -| `esn_bidirectional` | false | Not supported (inference is forward-only) | +| `esn_bidirectional` | false | Not supported; the loader refuses it | +| `esn_output_temperature` | 0 | Scale W_out was fit to (T·one-hot); 0 = not recorded | ### Tensor Layout @@ -111,8 +114,8 @@ assert(info.layer == LLM_TENSOR_LAYER_INPUT); Use the Python training utility: ```bash -# Basic training -python scripts/esn_training.py --reservoir-size 1024 --output model.gguf +# Basic training (--train-data is required unless --init-only) +python scripts/esn_training.py --reservoir-size 1024 --train-data corpus.txt --output model.gguf # With custom config python scripts/esn_training.py --config config.json @@ -131,6 +134,10 @@ python scripts/esn_training.py --reservoir-size 8192 --reg-grid 1,10,100,1000 \ of computing W_in·E + biases + feedback. The CPU `tanh`/`sigmoid` are branch-free so they vectorize (`tests/test-esn-activations.cpp` checks them). +`--save-online-metadata` enables the runtime `llama_esn_*` online readout +adaptation for the exported model; least-squares readouts also record +`esn.output_temperature`, which the C++ ridge/RLS updates need. + 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`). @@ -164,8 +171,8 @@ ESN is recognized as recurrent via `llm_arch_is_recurrent()`. To add similar: Current limitations and planned improvements: -1. **Training Support** - Ridge regression training (see `scripts/esn_training.py`) -2. **Hierarchical ESNs** - Multi-layer reservoir architectures +1. **Infer-train loop in CLI/server** - The `llama_esn_*` API exists; no tool drives it yet +2. **Hierarchical ESNs** - Multi-layer reservoir architectures (keys reserved; refused at load) 3. **Adaptive Parameters** - Dynamic leaking rate and spectral radius 4. **Sparse Operations** - Optimized sparse matrix ops for reservoir diff --git a/docs/esllm-roadmap.md b/docs/esllm-roadmap.md index 0a310baa5a69..72e9da7b7ffd 100644 --- a/docs/esllm-roadmap.md +++ b/docs/esllm-roadmap.md @@ -43,8 +43,8 @@ Proprioceptive signals are routed through the `llama_esn_feedback_event` API and | **Bounded latency** | Online train step is O(R²) and must complete in < 1 ms for R ≤ 4096 on CPU | | **Stable reservoir dynamics** | Spectral radius is validated at load time to be in (0, 1) | | **Non-destructive continual updates** | Only `W_out` is adapted; `W_res`, `W_in` are read-only after model load | -| **Reproducible checkpoints** | State + readout weights can be serialised via `llama_state_*` APIs at any point | -| **Safe online updates** | All updates are bounded by L2 regularisation; a drift detector can trigger rollback | +| **Reversible updates** | The model's `W_out` is never modified; `llama_esn_reset_adaptation` returns a context to it (the adapted readout is not yet part of `llama_state_*` data) | +| **Regularized online updates** | Ridge and RLS updates are anchored to the checkpoint by λ‖W − W₀‖²; drift detection is Phase 8 | ### 1.3 ESN/ESLLM Capability Matrix @@ -52,18 +52,17 @@ Proprioceptive signals are routed through the `llama_esn_feedback_event` API and |-----------|---------------|----------------| | Single-layer ESN inference | ✅ Implemented | ✅ Keep | | Batch ridge regression training | ✅ Python utility | ✅ Keep | -| Online RLS adaptation | ✅ Python utility | ✅ Runtime (C++) | -| Online SGD adaptation | ✅ Python utility | ✅ Runtime (C++) | +| Online ridge / RLS / SGD readout adaptation | ✅ Python utility and C++ runtime (`llama_esn_update_readout`) | ✅ Keep | | Parameter validation at load | ✅ Implemented | ✅ Keep | -| Proprioceptive feedback API | ✅ Header-defined stubs | 🔄 Full implementation | -| Synchronous infer-train loop | ❌ Not yet | 🎯 Phase 4 | -| Hierarchical reservoir (DTE) | ❌ Config only | 🎯 Phase 6 | +| Proprioceptive feedback API | ✅ Implemented (`src/llama-esn.cpp`, `tests/test-esn-online.cpp`) | ✅ Keep | +| Synchronous infer-train loop in CLI/server | ❌ Not yet (the API supports it) | 🎯 Phase 4 | +| Hierarchical reservoir (DTE) | ❌ Keys reserved; models that set them are refused at load | 🎯 Phase 6 | | ESN–Transformer hybrid | ❌ Not yet | 🎯 Phase 7 | | Drift detection + rollback | ❌ Not yet | 🎯 Phase 8 | | Online learning GGUF metadata | ✅ Implemented | ✅ Keep | | Safety/policy gates | ❌ Not yet | 🎯 Phase 8 | | Research benchmark suite | ❌ Not yet | 🎯 Phase 9 | -| Full API surface in llama.h | ✅ Stubs implemented | 🔄 Phase 10 | +| Full API surface in llama.h | ✅ Implemented for online adaptation | 🔄 Phase 10 | --- @@ -129,11 +128,11 @@ All of the following are loaded from GGUF metadata and fall back to safe default ```bash # RLS online training (efficient for sequential adaptation) -python scripts/esn_training.py --reservoir-size 1024 --online --online-mode rls \ +python scripts/esn_training.py --reservoir-size 1024 --train-data corpus.txt --online --online-mode rls \ --forgetting-factor 0.999 --save-online-metadata --output esllm.gguf # SGD online training (standard gradient descent) -python scripts/esn_training.py --reservoir-size 1024 --online --online-mode sgd \ +python scripts/esn_training.py --reservoir-size 1024 --train-data corpus.txt --online --online-mode sgd \ --online-lr 1e-4 --weight-decay 1e-5 --output esllm_sgd.gguf ``` @@ -143,9 +142,11 @@ Key classes: - `ESN.sgd_update(state, target)` — one online SGD step (O(V·R)) - `ESN.online_train_sequence(...)` — process a complete token sequence online -### 3.3 C++ API Stubs +### 3.3 C++ API -Declared in `include/llama.h`: +Declared in `include/llama.h`, implemented in `src/llama-esn.cpp` (see +`docs/esn.md`, "Online readout adaptation"), tested by +`tests/test-esn-online.cpp`: ```c struct llama_esn_online_params { ... }; @@ -334,8 +335,8 @@ When drift exceeds threshold, the monitor: ### 8.2 Rollback Checkpoints - A "golden" checkpoint (the static GGUF weights) is always held in memory. -- `llama_esn_reset_adaptation()` restores `W_out` to the golden checkpoint weights instantly. -- Periodic automatic checkpoints can be saved with `llama_state_save_file()`. +- `llama_esn_reset_adaptation()` returns a context to the golden checkpoint `W_out` (implemented). +- Periodic checkpoints of the adapted readout need it in `llama_state_*` data (not yet). ### 8.3 Policy Controls diff --git a/docs/esn-completion.md b/docs/esn-completion.md index 07e89aefd47a..7db1a2195418 100644 --- a/docs/esn-completion.md +++ b/docs/esn-completion.md @@ -55,7 +55,7 @@ sign off on criteria 1–4, 6, 7 by inspection of the file set; criterion | Requirement | Satisfied by | Evidence | |---|---|---| -| Hyperparameters load from GGUF | `src/llama-model.cpp` (`llm_load_hparams` ESN branch) | reservoir size, spectral radius, sparsity, leaking rate, input scaling, feedback scaling, noise, activation, bidirectional | +| Hyperparameters load from GGUF | `src/llama-model.cpp` (`llm_load_hparams` ESN branch) | reservoir size, spectral radius, sparsity, leaking rate, input scaling, feedback scaling, noise, activation, output temperature, online learning; bidirectional and hierarchical settings are refused | | Tensors load with correct shapes | `src/llama-model.cpp` (`llm_load_tensors` ESN branch) | `ggml_mul_mat` semantics respected — `ne[0]` is the contracted axis for each weight | | Recurrent memory sized correctly | `src/llama-hparams.cpp` | `n_embd_s()` returns `esn_reservoir_size` for `LLM_ARCH_ESN` | @@ -140,6 +140,7 @@ and Inference Optimizations" in `docs/esn.md`. | Arch registry | `tests/test-esn.cpp` (CTest, 8 asserts) | | C API end-to-end | `tests/test-esn-inference.cpp` (build-only; takes a model path) | | Numerical correctness vs. baseline | `tests/test-esn-perplexity.cpp` (build-only; takes a model + text) | +| Online readout adaptation (`llama_esn_*`) | `tests/test-esn-online.cpp` (CTest; writes its own models, or takes one) | **Verified by**: `ctest -R test-esn --verbose` passes; both build-only tests pass on the markdown-trained model. diff --git a/docs/esn.md b/docs/esn.md index d41ed63e7595..4090c1195b55 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -123,8 +123,8 @@ Notes on features that live outside the inference path: training (`scripts/esn_training.py`) for regularization; omitted from the deterministic inference graph - **`esn_bidirectional`**: not supported. Inference is causal, and the - training script rejects `--bidirectional`; the loader warns when a GGUF - sets it + training script rejects `--bidirectional` and the loader refuses a GGUF + that sets it - **`esn_spectral_radius`, `esn_sparsity`**: baked into the reservoir weight matrix at training time; the inference graph does not need to see them beyond metadata @@ -268,8 +268,12 @@ ESNs exhibit favorable scaling properties: at position t a backward pass has already read it, so backward-pass states would leak the target into training and validation while inference runs forward only. `esn_training.py` rejects `--bidirectional` - and `"bidirectional": true` configs, and the loader warns on GGUF files + and `"bidirectional": true` configs, and the loader refuses GGUF files that set `esn.bidirectional`. +7. **One reservoir**: `esn.n_levels` > 1, `esn.lateral_links` and + `esn.top_down_mod` describe hierarchical reservoirs that the graph does + not build; the loader refuses models that set them rather than running a + single reservoir in their place. ### Best Practices @@ -311,6 +315,7 @@ python scripts/esn_training.py \ --spectral-radius 0.95 \ --leaking-rate 0.3 \ --activation tanh \ + --train-data corpus.txt \ --output esn-model.gguf # 2. Build llama-cli (and the ESN inference smoke test). @@ -329,16 +334,16 @@ llama.cpp supports. Any input string is split into its UTF-8 bytes and each byte becomes its own token, which gives: - `llama-cli -p "..."` works directly, no extra setup -- `vocab_size` is pinned to 256 (the script will override larger values - with a warning so training/inference stay consistent) +- `vocab_size` is 256 (the default; any other value is an error with + this tokenizer) - Round-trip is exact — a model that memorizes a byte-sequence produces that sequence back verbatim For non-text sequence-learning use cases (where the ESN is driven with raw token IDs via `llama_batch_get_one`, as in -`tests/test-esn-inference.cpp`), pass `--tokenizer none` to emit the -`no_vocab` stub instead. The model loads but `llama-cli -p "..."` will -not work on it. +`tests/test-esn-inference.cpp`), pass `--tokenizer none` to write no text +tokenizer (tokenizer model `no_vocab`). The model loads but `llama-cli -p +"..."` will not work on it. Switching to a larger pretrained tokenizer (SPM/BPE) is a straightforward extension of `_write_tokenizer()` — call `writer.add_tokenizer_model(...)`, @@ -396,8 +401,9 @@ ESN training is provided via a Python utility in `scripts/esn_training.py`: # Install dependencies pip install numpy -# Basic training with sample data -python scripts/esn_training.py --reservoir-size 1024 --output model.gguf +# Basic training on a text file (byte-level next-token prediction); +# --train-data is required unless --init-only +python scripts/esn_training.py --reservoir-size 1024 --train-data corpus.txt --output model.gguf # With custom configuration python scripts/esn_training.py --config esn_config.json --output trained.gguf @@ -410,7 +416,7 @@ python scripts/esn_training.py --init-only --reservoir-size 2048 --output untrai | Parameter | Flag | Default | Description | |-----------|------|---------|-------------| -| Vocabulary Size | `--vocab-size` | 32000 | Token vocabulary size | +| Vocabulary Size | `--vocab-size` | 256 | Token vocabulary size (256 for the byte tokenizer) | | Embedding Dim | `--embedding-dim` | 512 | Input embedding dimension | | Reservoir Size | `--reservoir-size` | 1024 | Number of reservoir neurons | | Spectral Radius | `--spectral-radius` | 0.95 | Reservoir stability parameter | @@ -608,7 +614,10 @@ new, separable PRs if they were pursued: 1. **Hierarchical ESNs** — Multi-layer reservoir architectures. See `DTECHO.md`, which is a vision document describing a possible - Deep-Tree-Echo architecture built *on top of* this ESN runtime. + Deep-Tree-Echo architecture built *on top of* this ESN runtime. The + `esn.n_levels` / `esn.branching_factor` / `esn.lateral_links` / + `esn.top_down_mod` keys are reserved for it; models that set them are + refused until it exists. 2. **Advanced initialization** — Dynamic spectral-radius adaptation. 3. **Adaptive hyperparameters** — Online tuning of the leaking rate. 4. **Sparse operations** — A dedicated sparse `ggml_mul_mat` path for @@ -635,10 +644,58 @@ Token t arrives ├─► [Feedback] Optional feedback event (correction, reward, tool result) │ accumulated in bounded replay buffer │ - └─► [Train step] Online update of W_out only (O(R²), < 1 ms) + └─► [Train step] llama_esn_update_readout: per-context W_out only Reservoir weights W_res and W_in are NEVER modified ``` +### Online readout adaptation (C API) + +A model exported with `--save-online-metadata` (`esn.online_learning.enabled`) +makes every context record the readout input `x` (the RMS-normalized state) +of each position it decodes with logits, keyed by `(seq_id, pos)`; the +newest `esn.replay_window` positions per sequence are kept. Feedback names a +position whose logits were read and what the readout should have produced +there: + +```c +// decode, read logits at position p, sample `tok`, ... +llama_esn_feedback_event ev = { + LLAMA_ESN_FEEDBACK_CORRECTION, /*seq_id*/ 0, /*pos*/ p, /*signal*/ 0.0f, + &correct_token, 1, +}; +llama_esn_submit_feedback(ctx, &ev, 1); + +// the mode, rates and window exported with the model, or set your own +llama_esn_online_params op = llama_esn_model_online_params(model); +op.update_mode = 0; // 0 ridge, 1 RLS, 2 SGD +op.regularization = 1e-2f; +llama_esn_update_readout(ctx, &op); // later decodes on ctx use the new W_out +// ... +llama_esn_reset_adaptation(ctx); // back to the model's W_out +``` + +The first update copies `W_out` (dequantized to F32) into a buffer owned by +the context, which the graph then reads instead of the model tensor; the +model, and every other context on it, keep the checkpoint. Updates: + +| Mode | Objective | Cost per update | +|------|-----------|-----------------| +| 0 ridge | `min Σ wᵢ‖T yᵢ − W xᵢ‖² + λ‖W − W₀‖²` over the newest `replay_window` samples, refit from W₀ (Woodbury: an n×n solve for n samples) | O(V·R·n + n³) | +| 1 RLS | the same objective, recursively from the current W with forgetting `1 − decay_rate`; keeps P = (λI + Σ w x xᵀ)⁻¹ | O(R² + V·R) per sample, R² doubles of memory | +| 2 SGD | one weighted cross-entropy step on softmax(W x) per sample, plus `regularization`·(W − W₀) | O(V·R) per sample | + +`T` is `esn.output_temperature`: `esn_training.py` fits `W_out` to one-hot +targets and folds the calibrated softmax temperature into it, so the +exported readout is fit to `T · onehot` and ridge/RLS keep that scale. A +readout without the key (SGD-trained or untrained) can only be adapted with +SGD. Corrections and tool results are samples of weight 1; rewards weight +the emitted token by the reward (negative only with SGD); confidence +weights it by a value in [0, 1]. Latency events are rejected: they carry +no token target. A readout stored repacked for the CPU kernels cannot be +read back; load such models with `use_extra_bufts = false` (`--no-repack`). +The adapted readout is not included in `llama_state_*` data. +`tests/test-esn-online.cpp` checks each mode against its closed form. + **Proprioceptive feedback**: Signals originating from the model's own execution context: - `CORRECTION` — explicit user or verifier correction - `REWARD` — scalar RL-style reward/penalty @@ -650,11 +707,11 @@ Token t arrives | Invariant | Guarantee | |-----------|-----------| -| Bounded latency | Train step completes in < 1 ms for R ≤ 4096 on CPU | +| Bounded cost | Train step cost is set by the mode (table above), independent of context length | | Stable dynamics | Spectral radius validated to be in (0, 1) at load time | | Non-destructive | Only W_out is adapted; W_res, W_in are read-only | -| Reproducible | State + W_out can be checkpointed and restored at any time | -| Safe | Updates bounded by L2 regularisation; drift detection + rollback available | +| Reversible | `llama_esn_reset_adaptation` returns a context to the checkpoint W_out | +| Regularized | Ridge and RLS are anchored to the checkpoint by λ‖W − W₀‖²; SGD optionally | ### Capability Matrix @@ -664,8 +721,8 @@ Token t arrives | Parameter validation at load | ✅ | | Online RLS/SGD (Python) | ✅ | | Online learning GGUF metadata | ✅ | -| Proprioceptive feedback API (C stubs) | ✅ | -| Synchronous infer-train runtime loop | 🔄 Phase 4 | +| Feedback API + online readout updates (C, ridge/RLS/SGD) | ✅ | +| Synchronous infer-train runtime loop (in a CLI/server) | 🔄 Phase 4 | | Hierarchical reservoir (DTE) | 🔄 Phase 6 | | ESN–Transformer hybrid | 🔄 Phase 7 | | Safety governance + rollback | 🔄 Phase 8 | diff --git a/include/llama.h b/include/llama.h index c3c7b20d0c76..fc75ecd229e6 100644 --- a/include/llama.h +++ b/include/llama.h @@ -550,92 +550,111 @@ extern "C" { LLAMA_API bool llama_model_is_diffusion(const struct llama_model * model); // - // ESN / ESLLM – Synchronous infer-train and proprioceptive feedback API + // ESN – online readout adaptation // - // These types and functions provide the building blocks for the ESLLM - // "synchronous infer-train" execution model described in docs/esllm-roadmap.md. + // An ESN's reservoir is fixed; its linear readout W_out can be retrained + // per context from feedback on the outputs it produced. Contexts on a + // model exported with esn.online_learning.enabled record the readout + // input (the RMS-normalized reservoir state) of every output position + // they decode; a feedback event names a (seq_id, pos) whose logits were + // read and the token(s) the readout should have produced there. + // llama_esn_update_readout() then fits the context's own copy of W_out, + // which every later decode on that context uses. The model's W_out is not + // modified, so other contexts are unaffected, and the adapted readout is + // not part of the llama_state_* data. // - // Design invariants: - // - Reservoir weights are always frozen during adaptation (echo state property). - // - Only the linear readout (W_out) is updated online. - // - Every online update is bounded by regularization to prevent drift. - // - State and readout checkpoints can be serialised via llama_state_* APIs. + // Error codes shared by these functions: + // -1 the model is not an ESN + // -2 ctx is NULL + // -3 invalid argument (see each function) + // -4 the model was not exported with esn.online_learning.enabled + // -5 the feedback buffer (esn.online_learning.buf_size samples) is full + // -6 a least-squares mode needs esn.output_temperature, which the model lacks + // -7 a least-squares mode was given samples with negative weight + // -8 the readout could not be read or allocated (see the log) // - // Type of feedback signal carried in a llama_esn_feedback_event. enum llama_esn_feedback_type { - LLAMA_ESN_FEEDBACK_CORRECTION = 0, // explicit token-level correction by the user - LLAMA_ESN_FEEDBACK_REWARD = 1, // scalar reward / penalty signal - LLAMA_ESN_FEEDBACK_CONFIDENCE = 2, // model output confidence (self-supervised) - LLAMA_ESN_FEEDBACK_TOOL_RESULT = 3, // structured result from a tool/function call - LLAMA_ESN_FEEDBACK_LATENCY = 4, // observed latency of the last generation step + // target_tokens[k] is the token the readout should have produced at + // pos + k; each is a sample of weight 1 + LLAMA_ESN_FEEDBACK_CORRECTION = 0, + // target_tokens[k] were produced at pos + k and earned reward `signal`: + // weight = signal (negative pushes probability away; SGD only) + LLAMA_ESN_FEEDBACK_REWARD = 1, + // like REWARD with signal in [0, 1] (self-training on confident outputs) + LLAMA_ESN_FEEDBACK_CONFIDENCE = 2, + // target_tokens are what a tool returned, to be predicted from pos on; + // weight 1, as CORRECTION + LLAMA_ESN_FEEDBACK_TOOL_RESULT = 3, + // rejected with -3: latency carries no token target and does not + // depend on the readout + LLAMA_ESN_FEEDBACK_LATENCY = 4, }; - // A single proprioceptive feedback event emitted during or after inference. - // Submit a batch of these to llama_esn_submit_feedback() to drive online adaptation. struct llama_esn_feedback_event { enum llama_esn_feedback_type type; - llama_seq_id seq_id; // sequence that produced this event - llama_pos pos; // token position the feedback refers to - float signal; // scalar value: reward, confidence, latency, … - const llama_token * target_tokens; // optional ground-truth target tokens - int32_t n_target_tokens; // number of target tokens (0 = none) + llama_seq_id seq_id; // sequence the outputs belong to + llama_pos pos; // position whose logits produced the first target + float signal; // reward or confidence (see the type) + const llama_token * target_tokens; // required: one target per position from pos on + int32_t n_target_tokens; // >= 1 }; - // Parameters controlling the online-adaptation behaviour of an ESN/ESLLM model. - // Obtain defaults with llama_esn_online_params_default(), then customise. struct llama_esn_online_params { - bool enabled; // master switch: enable online readout adaptation - uint32_t update_mode; // 0=batch_ridge, 1=recursive_least_squares, 2=sgd - float learning_rate; // step size (SGD/RLS); ignored for batch ridge - float regularization; // L2 / Tikhonov regularization coefficient - float decay_rate; // exponential forgetting: [0 = no forgetting, 1 = full reset) - uint32_t replay_window; // sliding replay buffer length (in tokens) - bool freeze_reservoir; // if true, keep W_res / W_in frozen (should always be true) + bool enabled; // false: llama_esn_update_readout does nothing and returns 0 + uint32_t update_mode; // 0 = batch ridge, 1 = recursive least squares, 2 = SGD + float learning_rate; // SGD step size (> 0); unused by ridge and RLS + float regularization; // ridge/RLS: lambda > 0 (pull toward the checkpoint); + // SGD: >= 0, L2 pull toward the checkpoint + float decay_rate; // [0, 1): ridge down-weights a sample by (1 - decay)^age, + // RLS forgets with factor 1 - decay; unused by SGD + uint32_t replay_window; // >= 1: samples kept for ridge, which refits from the + // checkpoint on the newest replay_window samples each update + bool freeze_reservoir; // must be true (-3 otherwise): only W_out is trained }; - // Returns a safe default llama_esn_online_params with adaptation disabled. + // Defaults: disabled, ridge, lr 1e-4, regularization 1e-6, no decay, + // window 256, frozen reservoir. LLAMA_API struct llama_esn_online_params llama_esn_online_params_default(void); - // Returns true if the model was saved with online-learning enabled in its GGUF metadata. + // The online parameters exported with the model (esn.online_learning.*, + // esn.replay_window); enabled is true iff llama_esn_is_adaptive(model). + LLAMA_API struct llama_esn_online_params llama_esn_model_online_params(const struct llama_model * model); + + // True if the model is an ESN exported with esn.online_learning.enabled. LLAMA_API bool llama_esn_is_adaptive(const struct llama_model * model); - // Submit a batch of proprioceptive feedback events to the given context. - // - // Events are accumulated in an internal replay buffer (bounded by - // esn_online_buffer_size). They are consumed on the next call to - // llama_esn_update_readout(). - // - // Returns 0 on success, or a negative error code. - // Returns -1 if the model is not an ESN architecture. - // Returns -2 if ctx is NULL. + // Turn feedback events into training samples, using the readout inputs + // recorded when the referenced positions were decoded with logits (the + // newest esn.replay_window positions of each sequence are kept). All + // events are validated first; on error none is added. + // Returns 0 on success; -3 for an unknown or LATENCY type, missing or + // out-of-range targets, a non-finite reward, a confidence outside [0, 1], + // or a position with no recorded readout input; -1, -2, -4, -5. LLAMA_API int32_t llama_esn_submit_feedback( struct llama_context * ctx, const struct llama_esn_feedback_event * events, int32_t n_events); - // Trigger an online readout-weight update using the accumulated feedback buffer. - // - // This is the "train step" of the synchronous infer-train loop. It updates - // W_out (and only W_out) using the algorithm specified in params->update_mode. - // The reservoir weights are always left untouched. - // - // Returns the number of feedback events consumed, or a negative error code. - // Returns -1 if the model is not an ESN architecture. - // Returns -2 if ctx is NULL. + // Train the context's readout on the submitted samples (see + // llama_esn_online_params). Ridge and RLS fit W_out x to T * one-hot, + // T = esn.output_temperature, the scale the exported readout was fit to. + // Returns the number of events consumed (0 if none were pending or + // params->enabled is false); -3 for invalid params; -1, -2, -4, -6, -7, + // -8. On error the pending samples are kept. LLAMA_API int32_t llama_esn_update_readout( struct llama_context * ctx, const struct llama_esn_online_params * params); - // Discard all accumulated feedback events and reset the readout weights to - // the values stored in the GGUF checkpoint. - // No-op if the model is not an ESN architecture. + // Discard pending and replayed samples and return the context to the + // model's W_out. No-op for other contexts. LLAMA_API void llama_esn_reset_adaptation(struct llama_context * ctx); // Returns the reservoir size of an ESN model (0 if model is not ESN). LLAMA_API uint32_t llama_esn_reservoir_size(const struct llama_model * model); - // Returns the number of hierarchical reservoir levels (1 for flat ESN). + // Returns the number of reservoir levels (always 1: hierarchical models + // are refused at load), or 0 if the model is not an ESN. LLAMA_API uint32_t llama_esn_n_levels(const struct llama_model * model); // Returns 0 on success diff --git a/scripts/esn_training.py b/scripts/esn_training.py index 9007ccb5d1d9..6d4bd1a5be47 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -74,7 +74,7 @@ class ESNConfig: def __init__( self, - vocab_size: int = 32000, + vocab_size: int = 256, embedding_dim: int = 512, reservoir_size: int = 1024, spectral_radius: float = 0.95, @@ -108,11 +108,8 @@ def __init__( self.seed = seed self.tokenizer = tokenizer # "byte" | "none" if self.tokenizer == "byte" and self.vocab_size != 256: - # Byte tokenizer must have vocab == 256. Auto-correct and warn - # rather than silently producing a broken model. - logger.warning(f"[ESNConfig] tokenizer='byte' requires vocab_size=256; " - f"overriding vocab_size {self.vocab_size} -> 256") - self.vocab_size = 256 + raise ValueError(f"tokenizer='byte' has 256 tokens, but vocab_size is {self.vocab_size}; " + f"use vocab_size=256 or tokenizer='none'") @classmethod def from_json(cls, path: str) -> "ESNConfig": @@ -293,6 +290,12 @@ def __init__(self, config: ESNConfig): # probability scale; inference treats it as logits. train() fits this # scale on held-out data and save_gguf() folds it into W_out. self.output_temperature = 1.0 + # True once W_out is a least-squares fit (batch ridge or RLS) to + # output_temperature * one-hot targets; save_gguf() then records that + # scale as esn.output_temperature, which llama.cpp's online ridge and + # RLS updates continue from. An SGD-trained or untrained readout has + # no such target scale and the key is left out. + self.readout_is_least_squares = False # Type the reservoir matrix is stored in by save_gguf(). self.reservoir_type = "f32" @@ -663,6 +666,7 @@ def train( logger.info(f"Training output weights on {n_rows} samples " f"(state dim: {self.config.reservoir_size}, ridge penalty {lam:.3g})...") self.W_out = self._ridge_solve(XtX, XtY, lam) + self.readout_is_least_squares = True accuracy = float(np.mean(np.argmax(X_fit @ self.W_out.T, axis=1) == y_fit)) logger.info(f"Training complete. Accuracy: {accuracy:.4f}" @@ -879,6 +883,8 @@ def save_gguf(self, path: str, input_table: bool = True) -> None: - ``esn.noise_level`` (float32, optional) - ``esn.activation_type`` (uint32, optional: 0=tanh, 1=sigmoid, 2=leaky_relu) - ``esn.bidirectional`` (bool, optional; always false) + - ``esn.output_temperature`` (float32, when W_out is a least-squares + fit: the scale of its one-hot targets, folded into W_out) - ``esn.attention.layernorm_rms_eps`` (float32, required by loader) Tensors emitted (``.weight`` suffix per llama.cpp convention): @@ -919,9 +925,9 @@ def save_gguf(self, path: str, input_table: bool = True) -> None: # text-prompt path: any input string is split into its UTF-8 # bytes, each mapped to its byte-id. Requires vocab_size == 256. # - # - "none": emits the "no_vocab" stub. The model loads but text - # tokenization is unavailable; drive it with raw token IDs via - # llama_batch_get_one. Useful when the ESN is being used as a + # - "none": writes tokenizer model "no_vocab" (llama.cpp's + # LLAMA_VOCAB_TYPE_NONE). The model has no text tokenizer; drive + # it with raw token IDs via llama_batch_get_one, e.g. as a # non-text sequence learner. # self._write_tokenizer(writer) @@ -940,6 +946,8 @@ def save_gguf(self, path: str, input_table: bool = True) -> None: writer.add_float32("esn.noise_level", self.config.noise_level) writer.add_uint32("esn.activation_type", self.config.activation_type) writer.add_bool("esn.bidirectional", self.config.bidirectional) + if self.readout_is_least_squares: + writer.add_float32("esn.output_temperature", self.output_temperature) if self.config.online_learning: writer.add_bool("esn.online_learning.enabled", True) @@ -1016,7 +1024,8 @@ def _write_tokenizer(self, writer: GGUFWriter) -> None: - "byte": a 256-token byte-level tokenizer using the RWKV escape format. Any text input is split into UTF-8 bytes and each byte becomes its own token. llama-cli -p "..." works. - - "none": the "no_vocab" stub. Load-only, raw-token-id driven. + - "none": tokenizer model "no_vocab"; the model is driven by raw + token IDs. """ mode = self.config.tokenizer @@ -1062,28 +1071,6 @@ def _write_tokenizer(self, writer: GGUFWriter) -> None: writer.add_add_eos_token(False) -def create_sample_training_data( - vocab_size: int, - n_sequences: int = 1000, - seq_length: int = 128, - seed: int = 42 -) -> Tuple[np.ndarray, np.ndarray]: - """ - Create sample training data for testing. - - In practice, you would load real tokenized text data here. - """ - rng = np.random.default_rng(seed) - - # Random token sequences (replace with real data) - input_seqs = rng.integers(0, vocab_size, (n_sequences, seq_length)) - - # Target is next token prediction (shifted by 1) - target_seqs = np.roll(input_seqs, -1, axis=1) - - return input_seqs, target_seqs - - def load_text_training_data( path: str, vocab_size: int, @@ -1143,21 +1130,21 @@ def main(): formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: - # Basic batch ridge regression training - python esn_training.py --reservoir-size 1024 --output model.gguf + # Basic batch ridge regression training on a text file + python esn_training.py --reservoir-size 1024 --train-data corpus.txt --output model.gguf # With sigmoid activation and bias - python esn_training.py --reservoir-size 2048 --activation sigmoid --use-bias + python esn_training.py --reservoir-size 2048 --activation sigmoid --use-bias --train-data corpus.txt # Generative ESN with feedback - python esn_training.py --reservoir-size 1024 --feedback-scaling 0.5 + python esn_training.py --reservoir-size 1024 --feedback-scaling 0.5 --train-data corpus.txt # Online RLS training (infer-train / ESLLM) - python esn_training.py --reservoir-size 1024 --online --online-mode rls \\ + python esn_training.py --reservoir-size 1024 --train-data corpus.txt --online --online-mode rls \\ --forgetting-factor 0.999 --output online_model.gguf # Online SGD training - python esn_training.py --reservoir-size 1024 --online --online-mode sgd \\ + python esn_training.py --reservoir-size 1024 --train-data corpus.txt --online --online-mode sgd \\ --online-lr 1e-4 --output online_sgd_model.gguf """ ) @@ -1168,7 +1155,8 @@ def main(): help="Output GGUF file path") # ESN hyperparameters - parser.add_argument("--vocab-size", type=int, default=32000) + parser.add_argument("--vocab-size", type=int, default=256, + help="Vocabulary size; the byte tokenizer has 256 tokens") parser.add_argument("--embedding-dim", type=int, default=512) parser.add_argument("--reservoir-size", type=int, default=1024) parser.add_argument("--spectral-radius", type=float, default=0.95) @@ -1195,8 +1183,8 @@ def main(): # Training options parser.add_argument("--train-data", type=str, help="Path to training data") - parser.add_argument("--n-sequences", type=int, default=1000, - help="Number of sequences for sample data") + parser.add_argument("--n-sequences", type=int, default=None, + help="Use at most this many training windows (default: all)") parser.add_argument("--seq-length", type=int, default=128) parser.add_argument("--washout", type=int, default=100) parser.add_argument("--val-fraction", type=float, default=0.1, @@ -1220,8 +1208,8 @@ def main(): parser.add_argument("--tokenizer", choices=["byte", "none"], default="byte", help="Tokenizer type. 'byte' (default) emits a 256-" "token byte-level tokenizer so llama-cli -p " - "\"text\" works. 'none' emits the no_vocab stub " - "for raw-token-id driven use.") + "\"text\" works. 'none' writes no text tokenizer " + "(tokenizer model no_vocab), for raw-token-id use.") # Online learning options (Phase 3 – ESLLM infer-train substrate) parser.add_argument("--online", action="store_true", @@ -1239,7 +1227,7 @@ def main(): help="L2 weight decay for online SGD") parser.add_argument("--save-online-metadata", action="store_true", help="Embed online-learning config in GGUF metadata so llama.cpp " - "enables adaptation at runtime") + "enables readout adaptation (llama_esn_*) at runtime") # Modes parser.add_argument("--init-only", action="store_true", @@ -1249,6 +1237,11 @@ def main(): args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(message)s") + if not args.init_only and not args.train_data: + parser.error("--train-data is required to train the readout " + "(use --init-only to write untrained random weights)") + if not (0.0 < args.forgetting_factor <= 1.0): + parser.error("--forgetting-factor must be in (0, 1]") if args.bidirectional: parser.error("--bidirectional is not supported: at position t the backward " "pass has already read token t+1, the readout's target, and " @@ -1297,20 +1290,13 @@ def main(): esn.set_reservoir_type(args.outtype) if not args.init_only: - # Load or create training data - if args.train_data: - logger.info(f"Loading training data from {args.train_data}") - input_seqs, target_seqs = load_text_training_data( - args.train_data, - config.vocab_size, - seq_length=args.seq_length, - max_sequences=args.n_sequences, - ) - else: - logger.info("Using sample training data (for testing only)") - input_seqs, target_seqs = create_sample_training_data( - config.vocab_size, args.n_sequences, args.seq_length, config.seed - ) + logger.info(f"Loading training data from {args.train_data}") + input_seqs, target_seqs = load_text_training_data( + args.train_data, + config.vocab_size, + seq_length=args.seq_length, + max_sequences=args.n_sequences, + ) if args.online: # ---------------------------------------------------------- # @@ -1344,24 +1330,8 @@ def main(): mean_loss = total_loss / max(total_updates, 1) logger.info(f"\nOnline training complete. " f"Total updates: {total_updates} Mean loss: {mean_loss:.4f}") - - # Embed online-learning metadata in the GGUF file if requested - if args.save_online_metadata: - config.online_learning = True - config.online_lr = args.online_lr - config.online_reg = args.online_reg - config.online_buffer_size = 64 - config.online_update_mode = 0 if args.online_mode == "rls" else 2 - # decay_rate is the complement of the forgetting factor, clamped to [0, 1) - # A forgetting_factor of 1.0 means no forgetting → decay_rate = 0.0 - # A forgetting_factor approaching 0.0 means fast forgetting → decay_rate approaches 1.0 - # We clamp to < 1.0 to satisfy the validation constraint. - raw_decay = 1.0 - args.forgetting_factor - config.online_decay_rate = min(max(raw_decay, 0.0), 0.9999) - config.freeze_reservoir = True - config.replay_window = 256 - esn.config = config - logger.info("Online learning metadata will be embedded in GGUF.") + # RLS fits W_out to one-hot targets (scale 1); SGD fits logits + esn.readout_is_least_squares = args.online_mode == "rls" else: # Batch ridge regression (original mode) reg_grid = None @@ -1373,6 +1343,27 @@ def main(): reg_grid=reg_grid) logger.info(f"Final training accuracy: {accuracy:.4f}") + # Embed the online-adaptation config, which enables llama_esn_* on the + # model in llama.cpp. The mode is the one llama.cpp should use: 0 batch + # ridge, 1 RLS, 2 SGD (ridge and RLS need a least-squares readout). + if args.save_online_metadata: + if args.online and args.online_mode == "sgd": + mode = 2 + elif args.online: + mode = 1 + else: + mode = 0 + config.online_learning = True + config.online_lr = args.online_lr + config.online_reg = args.online_reg + config.online_buffer_size = 64 + config.online_update_mode = mode + config.online_decay_rate = 1.0 - args.forgetting_factor + config.freeze_reservoir = True + config.replay_window = 256 + esn.config = config + logger.info("Online learning metadata will be embedded in GGUF.") + # Save to GGUF esn.save_gguf(args.output, input_table=not args.no_input_table) logger.info(f"\nModel saved to {args.output}") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 18cfc76564d3..40d5476301fe 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,6 +14,7 @@ add_library(llama llama-batch.cpp llama-chat.cpp llama-context.cpp + llama-esn.cpp llama-cparams.cpp llama-grammar.cpp llama-graph.cpp diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 9c9f61368dad..5a779c539dec 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -273,6 +273,7 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_ESN_NOISE_LEVEL, "esn.noise_level" }, { LLM_KV_ESN_ACTIVATION_TYPE, "esn.activation_type" }, { LLM_KV_ESN_BIDIRECTIONAL, "esn.bidirectional" }, + { LLM_KV_ESN_OUTPUT_TEMPERATURE, "esn.output_temperature" }, // Online learning / infer-train { LLM_KV_ESN_ONLINE_LEARNING_ENABLED, "esn.online_learning.enabled" }, diff --git a/src/llama-arch.h b/src/llama-arch.h index 0a28953d05eb..48027eeab4ad 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -278,6 +278,7 @@ enum llm_kv { LLM_KV_ESN_NOISE_LEVEL, LLM_KV_ESN_ACTIVATION_TYPE, LLM_KV_ESN_BIDIRECTIONAL, + LLM_KV_ESN_OUTPUT_TEMPERATURE, // ESN online learning / infer-train configuration (Phase 3) LLM_KV_ESN_ONLINE_LEARNING_ENABLED, diff --git a/src/llama-context.cpp b/src/llama-context.cpp index c5e4cae3fa68..cca11e4a8813 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2,6 +2,7 @@ #include "llama-impl.h" #include "llama-batch.h" +#include "llama-esn.h" #include "llama-io.h" #include "llama-memory.h" #include "llama-mmap.h" @@ -200,6 +201,10 @@ llama_context::llama_context( }; memory.reset(model.create_memory(params_mem, cparams)); + + if (model.arch == LLM_ARCH_ESN && hparams.esn_online_learning) { + esn = std::make_unique(model); + } } // init backends @@ -476,6 +481,10 @@ llama_memory_t llama_context::get_memory() const { return memory.get(); } +llama_esn_adapter * llama_context::get_esn() const { + return esn.get(); +} + bool llama_context::memory_update(bool optimize) { if (!memory) { return false; @@ -1200,6 +1209,18 @@ int llama_context::decode(const llama_batch & batch_inp) { } } + // record the ESN readout inputs for online adaptation + if (esn && n_outputs > 0) { + ggml_tensor * t_x = res->get_embd(); + GGML_ASSERT(t_x != nullptr && t_x->type == GGML_TYPE_F32); + ggml_backend_t backend_x = ggml_backend_sched_get_tensor_backend(sched.get(), t_x); + GGML_ASSERT(backend_x != nullptr); + esn_rows.resize((size_t) n_outputs * t_x->ne[0]); + ggml_backend_tensor_get_async(backend_x, t_x, esn_rows.data(), 0, esn_rows.size()*sizeof(float)); + ggml_backend_sched_synchronize(sched.get()); + esn->capture(ubatch, n_outputs, esn_rows.data()); + } + n_outputs_prev += n_outputs; } while (mctx->next()); @@ -1443,6 +1464,8 @@ llm_graph_params llama_context::graph_params( /*.loras =*/ &loras, /*.mctx =*/ mctx, /*.cross =*/ &cross, + /*.esn_readout =*/ esn ? esn->readout() : nullptr, + /*.esn_capture =*/ esn != nullptr, /*.n_outputs =*/ n_outputs, /*.cb =*/ graph_get_cb(), /*.res =*/ res, diff --git a/src/llama-context.h b/src/llama-context.h index ed6d82cb396f..4258e4b779d0 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -22,6 +22,8 @@ struct llama_memory_i; struct llama_memory_context_i; // "memory" as in physical memory for a buffer type, in bytes +struct llama_esn_adapter; + struct llama_memory_breakdown_data { size_t model = 0; // memory allocated for the model size_t context = 0; // memory allocated for the context @@ -54,6 +56,10 @@ struct llama_context { llama_memory_t get_memory() const; + // online readout adaptation state; nullptr unless the model is an ESN + // with esn.online_learning.enabled + llama_esn_adapter * get_esn() const; + // return true if the memory was updated bool memory_update(bool optimize); @@ -238,6 +244,9 @@ struct llama_context { std::unique_ptr memory; + std::unique_ptr esn; + std::vector esn_rows; // readout inputs of the last ubatch + // decode output (2-dimensional array: [n_outputs][n_vocab]) size_t logits_size = 0; // capacity (of floats) for logits float * logits = nullptr; diff --git a/src/llama-esn.cpp b/src/llama-esn.cpp new file mode 100644 index 000000000000..4f2f215e66f7 --- /dev/null +++ b/src/llama-esn.cpp @@ -0,0 +1,606 @@ +#include "llama-esn.h" + +#include "llama-impl.h" +#include "llama-batch.h" +#include "llama-model.h" + +#include "ggml-backend.h" + +#include +#include +#include +#include +#include + +// +// helpers +// + +// Run fn(i0, i1) over [0, n) split across up to n_threads threads. +template +static void esn_parallel_for(int n_threads, int64_t n, F && fn) { + n_threads = (int) std::max(1, std::min(n_threads, n / 64)); + if (n_threads <= 1) { + fn((int64_t) 0, n); + return; + } + std::vector workers; + workers.reserve(n_threads - 1); + const int64_t chunk = (n + n_threads - 1) / n_threads; + for (int t = 1; t < n_threads; ++t) { + const int64_t i0 = t * chunk; + const int64_t i1 = std::min(n, i0 + chunk); + if (i0 >= i1) { + break; + } + workers.emplace_back([&fn, i0, i1]() { fn(i0, i1); }); + } + fn((int64_t) 0, std::min(n, chunk)); + for (auto & w : workers) { + w.join(); + } +} + +// Eight independent partial sums, so the loop vectorizes without -ffast-math. +static float esn_dot(const float * a, const float * b, int64_t n) { + float acc[8] = { 0 }; + int64_t i = 0; + for (; i + 8 <= n; i += 8) { + for (int k = 0; k < 8; ++k) { + acc[k] += a[i + k] * b[i + k]; + } + } + float s = ((acc[0] + acc[1]) + (acc[2] + acc[3])) + ((acc[4] + acc[5]) + (acc[6] + acc[7])); + for (; i < n; ++i) { + s += a[i] * b[i]; + } + return s; +} + +static void esn_axpy(float * y, float a, const float * x, int64_t n) { + for (int64_t i = 0; i < n; ++i) { + y[i] += a * x[i]; + } +} + +// +// llama_esn_adapter +// + +llama_esn_adapter::llama_esn_adapter(const llama_model & model) : + model(model), + n_res (model.hparams.esn_reservoir_size), + n_vocab(model.output->ne[1]), + recorded_cap(std::max(1, model.hparams.esn_replay_window)), + pending_cap (std::max(1, model.hparams.esn_online_buffer_size)) { + GGML_ASSERT(model.output && model.output->ne[0] == n_res); +} + +llama_esn_adapter::~llama_esn_adapter() = default; + +void llama_esn_adapter::capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows) { + uint32_t j = 0; + for (uint32_t i = 0; i < ubatch.n_tokens && j < n_outputs; ++i) { + if (n_outputs != ubatch.n_tokens && !ubatch.output[i]) { + continue; + } + const float * x = rows + (size_t) j * n_res; + ++j; + const llama_pos pos = ubatch.pos[i]; + for (int32_t s = 0; s < ubatch.n_seq_id[i]; ++s) { + auto & q = recorded[ubatch.seq_id[i][s]]; + // a position at or before the newest one means the sequence was + // rewound (seq_rm, memory clear): what was recorded from there on + // belongs to tokens that are gone + while (!q.empty() && q.back().pos >= pos) { + q.pop_back(); + } + q.push_back({ pos, std::vector(x, x + n_res) }); + while (q.size() > recorded_cap) { + q.pop_front(); + } + } + } +} + +const llama_esn_adapter::captured * llama_esn_adapter::find(llama_seq_id seq, llama_pos pos) const { + const auto it = recorded.find(seq); + if (it == recorded.end()) { + return nullptr; + } + const auto & q = it->second; + const auto c = std::lower_bound(q.begin(), q.end(), pos, + [](const captured & a, llama_pos p) { return a.pos < p; }); + return c != q.end() && c->pos == pos ? &*c : nullptr; +} + +int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32_t n_events) { + if (n_events < 0 || (n_events > 0 && events == nullptr)) { + return -3; + } + + // validate everything before taking anything: a batch is all or nothing + std::vector fresh; + for (int32_t e = 0; e < n_events; ++e) { + const auto & ev = events[e]; + + float weight = 1.0f; + switch (ev.type) { + case LLAMA_ESN_FEEDBACK_CORRECTION: + case LLAMA_ESN_FEEDBACK_TOOL_RESULT: + weight = 1.0f; + break; + case LLAMA_ESN_FEEDBACK_REWARD: + if (!std::isfinite(ev.signal)) { + LLAMA_LOG_ERROR("%s: event %d: reward signal is not finite\n", __func__, e); + return -3; + } + weight = ev.signal; + break; + case LLAMA_ESN_FEEDBACK_CONFIDENCE: + if (!(ev.signal >= 0.0f && ev.signal <= 1.0f)) { + LLAMA_LOG_ERROR("%s: event %d: confidence must be in [0, 1], got %f\n", __func__, e, ev.signal); + return -3; + } + weight = ev.signal; + break; + case LLAMA_ESN_FEEDBACK_LATENCY: + LLAMA_LOG_ERROR("%s: event %d: latency feedback carries no token target and the readout " + "does not determine latency; it cannot train the readout\n", __func__, e); + return -3; + default: + LLAMA_LOG_ERROR("%s: event %d: unknown feedback type %d\n", __func__, e, (int) ev.type); + return -3; + } + + if (ev.n_target_tokens <= 0 || ev.target_tokens == nullptr) { + LLAMA_LOG_ERROR("%s: event %d: target_tokens is required\n", __func__, e); + return -3; + } + + for (int32_t k = 0; k < ev.n_target_tokens; ++k) { + const llama_token tok = ev.target_tokens[k]; + if (tok < 0 || tok >= n_vocab) { + LLAMA_LOG_ERROR("%s: event %d: target token %d is out of range\n", __func__, e, tok); + return -3; + } + const captured * c = find(ev.seq_id, ev.pos + k); + if (c == nullptr) { + LLAMA_LOG_ERROR("%s: event %d: no readout input recorded for seq %d pos %d (the position " + "was not decoded with an output, was rewound, or is older than the last %zu)\n", + __func__, e, ev.seq_id, ev.pos + k, recorded_cap); + return -3; + } + fresh.push_back({ c->x, tok, weight }); + } + } + + if (pending.size() + fresh.size() > pending_cap) { + LLAMA_LOG_ERROR("%s: %zu samples would exceed the feedback buffer (%zu pending of %zu); " + "call llama_esn_update_readout first\n", __func__, fresh.size(), pending.size(), pending_cap); + return -5; + } + + for (auto & s : fresh) { + pending.push_back(std::move(s)); + } + pending_events += n_events; + + return 0; +} + +float * llama_esn_adapter::w_data() const { + return (float *) w->data; +} + +void llama_esn_adapter::ensure_readout() { + if (w != nullptr) { + return; + } + + // the checkpoint, dequantized + const ggml_tensor * out = model.output; + // weights repacked for the CPU matmul kernels cannot be read back + if (out->buffer && strstr(ggml_backend_buft_name(ggml_backend_buffer_get_type(out->buffer)), "REPACK") != nullptr) { + throw std::runtime_error("ESN: the readout is stored repacked for the CPU kernels and cannot be read back; " + "load the model with use_extra_bufts = false (--no-repack) to adapt it"); + } + std::vector raw(ggml_nbytes(out)); + ggml_backend_tensor_get(out, raw.data(), 0, raw.size()); + + w0.resize((size_t) n_vocab * n_res); + const size_t row_size = ggml_row_size(out->type, n_res); + if (out->type == GGML_TYPE_F32) { + memcpy(w0.data(), raw.data(), w0.size() * sizeof(float)); + } else { + const auto * traits = ggml_get_type_traits(out->type); + if (traits->to_float == nullptr) { + throw std::runtime_error(std::string("ESN: cannot read a readout of type ") + ggml_type_name(out->type)); + } + for (int64_t v = 0; v < n_vocab; ++v) { + traits->to_float(raw.data() + v * row_size, w0.data() + v * n_res, n_res); + } + } + + ggml_init_params params = { + /*.mem_size =*/ ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ctx_w.reset(ggml_init(params)); + w = ggml_new_tensor_2d(ctx_w.get(), GGML_TYPE_F32, n_res, n_vocab); + ggml_set_name(w, "esn_adapted_readout"); + + ggml_backend_dev_t cpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); + if (cpu == nullptr) { + throw std::runtime_error("ESN: online adaptation needs the CPU backend"); + } + buf_w.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_w.get(), ggml_backend_dev_buffer_type(cpu))); + if (!buf_w) { + throw std::runtime_error("ESN: failed to allocate the adapted readout"); + } + GGML_ASSERT(ggml_backend_buffer_is_host(buf_w.get())); + + memcpy(w_data(), w0.data(), w0.size() * sizeof(float)); +} + +int32_t llama_esn_adapter::update(const llama_esn_online_params & p, int n_threads) { + if (!p.enabled) { + return 0; + } + + const bool finite = std::isfinite(p.learning_rate) && std::isfinite(p.regularization) && std::isfinite(p.decay_rate); + if (!finite || p.update_mode > 2 || !p.freeze_reservoir || p.replay_window == 0 || + p.decay_rate < 0.0f || p.decay_rate >= 1.0f || p.regularization < 0.0f || + (p.update_mode != 2 && p.regularization <= 0.0f) || + (p.update_mode == 2 && p.learning_rate <= 0.0f)) { + LLAMA_LOG_ERROR("%s: invalid parameters (mode %u, lr %g, reg %g, decay %g, window %u, freeze_reservoir %d)\n", + __func__, p.update_mode, p.learning_rate, p.regularization, p.decay_rate, p.replay_window, + (int) p.freeze_reservoir); + return -3; + } + + if (pending.empty()) { + return 0; + } + + const float temperature = model.hparams.esn_output_temperature; + if (p.update_mode != 2) { + if (temperature <= 0.0f) { + LLAMA_LOG_ERROR("%s: least-squares updates need the scale the readout was fit to, and this " + "model has no esn.output_temperature; re-export it with scripts/esn_training.py " + "or use SGD (mode 2)\n", __func__); + return -6; + } + const auto negative = [](const sample & s) { return s.weight < 0.0f; }; + bool has_negative = std::any_of(pending.begin(), pending.end(), negative); + if (p.update_mode == 0) { + const size_t n_hist = std::min(history.size(), p.replay_window > pending.size() ? p.replay_window - pending.size() : 0); + has_negative = has_negative || std::any_of(history.end() - n_hist, history.end(), negative); + } + if (has_negative) { + LLAMA_LOG_ERROR("%s: negative-reward samples have no least-squares target; use SGD (mode 2)\n", __func__); + return -7; + } + } + + ensure_readout(); + + switch (p.update_mode) { + case 0: update_ridge(p.regularization, p.decay_rate, p.replay_window, temperature, n_threads); break; + case 1: update_rls (p.regularization, p.decay_rate, temperature); break; + case 2: update_sgd (p.learning_rate, p.regularization); break; + } + last_mode = (int) p.update_mode; + active = true; + + for (auto & s : pending) { + history.push_back(std::move(s)); + } + while (history.size() > p.replay_window) { + history.pop_front(); + } + pending.clear(); + + const int32_t consumed = pending_events; + pending_events = 0; + return consumed; +} + +void llama_esn_adapter::update_ridge(float lambda, float decay, uint32_t window, float temperature, int n_threads) { + // the newest `window` samples of history + pending + std::vector set; + for (const auto & s : history) { + set.push_back(&s); + } + for (const auto & s : pending) { + set.push_back(&s); + } + if (set.size() > window) { + set.erase(set.begin(), set.end() - window); + } + const int64_t n = (int64_t) set.size(); + + // S[i] = sqrt(w_i) x_i, with w_i decayed by age (0 for the newest) + std::vector S((size_t) n * n_res); + std::vector sw(n); + for (int64_t i = 0; i < n; ++i) { + const double age = (double) (n - 1 - i); + sw[i] = (float) std::sqrt((double) set[i]->weight * std::pow(1.0 - (double) decay, age)); + for (int64_t r = 0; r < n_res; ++r) { + S[i * n_res + r] = sw[i] * set[i]->x[r]; + } + } + + // G = S S^T + lambda I, Cholesky-factored in place (lower triangle) + std::vector G((size_t) n * n); + for (int64_t i = 0; i < n; ++i) { + for (int64_t j = 0; j <= i; ++j) { + double g = 0.0; + const float * a = &S[i * n_res]; + const float * b = &S[j * n_res]; + for (int64_t r = 0; r < n_res; ++r) { + g += (double) a[r] * b[r]; + } + G[i * n + j] = g + (i == j ? (double) lambda : 0.0); + } + } + for (int64_t j = 0; j < n; ++j) { + double d = G[j * n + j]; + for (int64_t k = 0; k < j; ++k) { + d -= G[j * n + k] * G[j * n + k]; + } + GGML_ASSERT(d > 0.0); + d = std::sqrt(d); + G[j * n + j] = d; + for (int64_t i = j + 1; i < n; ++i) { + double s = G[i * n + j]; + for (int64_t k = 0; k < j; ++k) { + s -= G[i * n + k] * G[j * n + k]; + } + G[i * n + j] = s / d; + } + } + + // per output row v: e = sqrt(w) (T y_v - W0_v x), a = G^-1 e, + // W_v = W0_v + sum_i a_i S_i + float * W = w_data(); + esn_parallel_for(n_threads, n_vocab, [&](int64_t v0, int64_t v1) { + std::vector a(n); + for (int64_t v = v0; v < v1; ++v) { + const float * w0v = &w0[v * n_res]; + for (int64_t i = 0; i < n; ++i) { + const double target = set[i]->token == v ? (double) sw[i] * temperature : 0.0; + a[i] = target - esn_dot(w0v, &S[i * n_res], n_res); + } + for (int64_t i = 0; i < n; ++i) { // L y = e + double s = a[i]; + for (int64_t k = 0; k < i; ++k) { + s -= G[i * n + k] * a[k]; + } + a[i] = s / G[i * n + i]; + } + for (int64_t i = n - 1; i >= 0; --i) { // L^T a = y + double s = a[i]; + for (int64_t k = i + 1; k < n; ++k) { + s -= G[k * n + i] * a[k]; + } + a[i] = s / G[i * n + i]; + } + float * wv = W + v * n_res; + memcpy(wv, w0v, n_res * sizeof(float)); + for (int64_t i = 0; i < n; ++i) { + esn_axpy(wv, (float) a[i], &S[i * n_res], n_res); + } + } + }); +} + +void llama_esn_adapter::update_rls(float lambda, float decay, float temperature) { + const int64_t R = n_res; + + // P is the inverse of lambda I + sum w x x^T for samples since the last + // restart; it restarts at I / lambda (a prior centered on the current + // readout) when lambda changes or another mode moved the readout + if (rls_p.empty() || rls_lambda != lambda || last_mode != 1) { + rls_p.assign((size_t) R * R, 0.0); + for (int64_t r = 0; r < R; ++r) { + rls_p[r * R + r] = 1.0 / lambda; + } + rls_lambda = lambda; + } + + const double f = 1.0 - (double) decay; + float * W = w_data(); + std::vector g(R); + std::vector k(R); + + for (const auto & s : pending) { + if (s.weight <= 0.0f) { + continue; + } + const float * x = s.x.data(); + + double xg = 0.0; + for (int64_t i = 0; i < R; ++i) { + const double * pi = &rls_p[i * R]; + double acc = 0.0; + for (int64_t j = 0; j < R; ++j) { + acc += pi[j] * x[j]; + } + g[i] = acc; + xg += acc * x[i]; + } + const double denom = f / s.weight + xg; + for (int64_t i = 0; i < R; ++i) { + k[i] = (float) (g[i] / denom); + } + + for (int64_t v = 0; v < n_vocab; ++v) { + float * wv = W + v * R; + const float e = (s.token == v ? temperature : 0.0f) - esn_dot(wv, x, R); + esn_axpy(wv, e, k.data(), R); + } + + for (int64_t i = 0; i < R; ++i) { + double * pi = &rls_p[i * R]; + const double ki = g[i] / denom; + for (int64_t j = 0; j < R; ++j) { + pi[j] = (pi[j] - ki * g[j]) / f; + } + } + } +} + +void llama_esn_adapter::update_sgd(float lr, float reg) { + const int64_t R = n_res; + float * W = w_data(); + std::vector z(n_vocab); + + for (const auto & s : pending) { + const float * x = s.x.data(); + + float zmax = -INFINITY; + for (int64_t v = 0; v < n_vocab; ++v) { + z[v] = esn_dot(W + v * R, x, R); + zmax = std::max(zmax, z[v]); + } + double sum = 0.0; + for (int64_t v = 0; v < n_vocab; ++v) { + sum += std::exp((double) (z[v] - zmax)); + } + + // gradient ascent on w * log softmax(W x)[token], then the pull toward W0 + for (int64_t v = 0; v < n_vocab; ++v) { + const double prob = std::exp((double) (z[v] - zmax)) / sum; + const float c = (float) (lr * s.weight * ((s.token == v ? 1.0 : 0.0) - prob)); + float * wv = W + v * R; + if (reg > 0.0f) { + const float * w0v = &w0[v * R]; + const float shrink = lr * reg; + for (int64_t r = 0; r < R; ++r) { + wv[r] -= shrink * (wv[r] - w0v[r]); + } + } + esn_axpy(wv, c, x, R); + } + } +} + +void llama_esn_adapter::reset() { + pending.clear(); + pending_events = 0; + history.clear(); + rls_p.clear(); + rls_p.shrink_to_fit(); + last_mode = -1; + active = false; + // the readout buffer is kept: graphs may still reference the tensor, and + // the next update rewrites it from the checkpoint + if (w != nullptr) { + memcpy(w_data(), w0.data(), w0.size() * sizeof(float)); + } +} + +// +// API +// + +#include "llama-context.h" + +llama_esn_online_params llama_esn_online_params_default(void) { + llama_esn_online_params p = { + /*.enabled =*/ false, + /*.update_mode =*/ 0, + /*.learning_rate =*/ 1e-4f, + /*.regularization =*/ 1e-6f, + /*.decay_rate =*/ 0.0f, + /*.replay_window =*/ 256, + /*.freeze_reservoir =*/ true, + }; + return p; +} + +llama_esn_online_params llama_esn_model_online_params(const llama_model * model) { + llama_esn_online_params p = llama_esn_online_params_default(); + if (model == nullptr || model->arch != LLM_ARCH_ESN) { + return p; + } + const auto & hp = model->hparams; + p.enabled = hp.esn_online_learning; + p.update_mode = hp.esn_online_update_mode; + p.learning_rate = hp.esn_online_lr; + p.regularization = hp.esn_online_reg; + p.decay_rate = hp.esn_online_decay_rate; + p.replay_window = hp.esn_replay_window; + p.freeze_reservoir = hp.esn_freeze_reservoir; + return p; +} + +bool llama_esn_is_adaptive(const llama_model * model) { + return model != nullptr && model->arch == LLM_ARCH_ESN && model->hparams.esn_online_learning; +} + +uint32_t llama_esn_reservoir_size(const llama_model * model) { + return model != nullptr && model->arch == LLM_ARCH_ESN ? model->hparams.esn_reservoir_size : 0; +} + +uint32_t llama_esn_n_levels(const llama_model * model) { + return model != nullptr && model->arch == LLM_ARCH_ESN ? model->hparams.esn_n_levels : 0; +} + +// -1 not an ESN, -4 ESN without online learning, 0 adapter available +static int32_t llama_esn_check(const llama_context * ctx) { + const llama_model & model = ctx->get_model(); + if (model.arch != LLM_ARCH_ESN) { + return -1; + } + if (ctx->get_esn() == nullptr) { + LLAMA_LOG_ERROR("%s: the model was not exported with esn.online_learning.enabled\n", __func__); + return -4; + } + return 0; +} + +int32_t llama_esn_submit_feedback( + llama_context * ctx, + const llama_esn_feedback_event * events, + int32_t n_events) { + if (ctx == nullptr) { + return -2; + } + if (const int32_t rc = llama_esn_check(ctx); rc != 0) { + return rc; + } + return ctx->get_esn()->submit(events, n_events); +} + +int32_t llama_esn_update_readout( + llama_context * ctx, + const llama_esn_online_params * params) { + if (ctx == nullptr) { + return -2; + } + if (const int32_t rc = llama_esn_check(ctx); rc != 0) { + return rc; + } + if (params == nullptr) { + return -3; + } + // no graph may be reading the readout while it changes + ctx->synchronize(); + try { + return ctx->get_esn()->update(*params, (int) ctx->n_threads_batch()); + } catch (const std::exception & e) { + LLAMA_LOG_ERROR("%s: %s\n", __func__, e.what()); + return -8; + } +} + +void llama_esn_reset_adaptation(llama_context * ctx) { + if (ctx == nullptr || ctx->get_esn() == nullptr) { + return; + } + ctx->synchronize(); + ctx->get_esn()->reset(); +} diff --git a/src/llama-esn.h b/src/llama-esn.h new file mode 100644 index 000000000000..274ba82167dd --- /dev/null +++ b/src/llama-esn.h @@ -0,0 +1,101 @@ +#pragma once + +#include "llama.h" + +#include "ggml-cpp.h" + +#include +#include +#include +#include + +struct llama_model; +struct llama_ubatch; + +// Online readout adaptation for an ESN context (the llama_esn_* API). +// +// The reservoir is fixed; only the linear readout W_out is trained. The +// context records the readout input x (result_norm, one vector per output +// token) after every ubatch, keyed by (seq_id, pos). Feedback events turn +// those recorded vectors into training samples (x, target token, weight), and +// llama_esn_update_readout() fits a per-context copy of W_out to them, which +// the graph then uses in place of the model's tensor. The model's own W_out +// (the checkpoint W0) is never modified, so contexts adapt independently. +// +// Objectives, with y the one-hot target and T = esn.output_temperature (the +// training script fits W_out to T * y and keeps that scale): +// 0 ridge: W = argmin sum_i w_i |T y_i - W x_i|^2 + lambda |W - W0|^2 +// over the newest replay_window samples, solved from W0 each time +// (Woodbury form, an n x n system for n samples) +// 1 RLS: the same objective solved recursively from the current W, with +// forgetting factor 1 - decay; P = (lambda I + sum w x x^T)^-1 +// 2 SGD: one cross-entropy step per sample on softmax(W x), weighted by w +// (negative w pushes probability away from the token), plus an L2 +// pull toward W0 +struct llama_esn_adapter { + explicit llama_esn_adapter(const llama_model & model); + ~llama_esn_adapter(); + + // Record the readout inputs of one ubatch. `rows` holds n_outputs + // vectors of reservoir_size floats, in ubatch output order. + void capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows); + + int32_t submit (const llama_esn_feedback_event * events, int32_t n_events); + int32_t update (const llama_esn_online_params & params, int n_threads); + void reset(); + + // the adapted readout, or nullptr while the checkpoint is in use + ggml_tensor * readout() const { return active ? w : nullptr; } + + size_t n_pending_samples() const { return pending.size(); } + +private: + struct captured { + llama_pos pos; + std::vector x; + }; + + struct sample { + std::vector x; + llama_token token; + float weight; + }; + + const llama_model & model; + + const int64_t n_res; // reservoir size: readout input width + const int64_t n_vocab; // readout output width + + // recorded readout inputs per sequence, oldest first, ascending pos + std::map> recorded; + size_t recorded_cap; // per sequence + + std::vector pending; // submitted, not yet trained on + int32_t pending_events = 0; + size_t pending_cap; + + std::deque history; // trained-on samples, newest last + + // checkpoint readout as F32, [n_vocab][n_res]; loaded on first update + std::vector w0; + + // adapted readout, F32 [n_res, n_vocab] in a host buffer + ggml_context_ptr ctx_w; + ggml_backend_buffer_ptr buf_w; + ggml_tensor * w = nullptr; + bool active = false; + + // RLS inverse correlation matrix, [n_res][n_res], valid for rls_lambda + std::vector rls_p; + float rls_lambda = 0.0f; + int last_mode = -1; + + const captured * find(llama_seq_id seq, llama_pos pos) const; + + void ensure_readout(); + float * w_data() const; + + void update_ridge(float lambda, float decay, uint32_t window, float temperature, int n_threads); + void update_rls (float lambda, float decay, float temperature); + void update_sgd (float lr, float reg); +}; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 242b8b4d0af2..9c0402213e91 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -583,6 +583,8 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : loras (params.loras), mctx (params.mctx), cross (params.cross), + esn_readout (params.esn_readout), + esn_capture (params.esn_capture), cb_func (params.cb), res (params.res), ctx0 (res->get_ctx()), diff --git a/src/llama-graph.h b/src/llama-graph.h index 5ae3364edbe3..41d47075ab78 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -419,6 +419,13 @@ struct llm_graph_params { const llama_memory_context_i * mctx; const llama_cross * cross; + // ESN: per-context readout trained online (llama_esn_update_readout), + // used in place of the model's output tensor when not null + ggml_tensor * esn_readout = nullptr; + // ESN: keep result_norm (the readout input) as a graph output so the + // context can capture it for online learning + bool esn_capture = false; + uint32_t n_outputs; llm_graph_cb cb; @@ -466,6 +473,8 @@ struct llm_graph_params { cvec == other.cvec && loras == other.loras && cross == other.cross && + esn_readout == other.esn_readout && + esn_capture == other.esn_capture && n_outputs == other.n_outputs; } }; @@ -582,6 +591,9 @@ struct llm_graph_context { const llama_memory_context_i * mctx; const llama_cross * cross; + ggml_tensor * esn_readout; + bool esn_capture; + const llm_graph_cb & cb_func; llm_graph_result * res; diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp index ca73291c69c9..5cf03a1a8c54 100644 --- a/src/llama-hparams.cpp +++ b/src/llama-hparams.cpp @@ -2,6 +2,7 @@ #include "ggml.h" #include +#include #include #include @@ -299,6 +300,11 @@ void llama_hparams::validate_esn_params() const { "ESN: esn_online_reg must be >= 0, got " + std::to_string(esn_online_reg)); } + if (esn_online_update_mode != 2 && esn_online_reg <= 0.0f) { + throw std::invalid_argument( + "ESN: esn_online_reg must be > 0 for ridge and RLS updates, got " + + std::to_string(esn_online_reg)); + } if (esn_online_update_mode > 2) { throw std::invalid_argument( "ESN: esn_online_update_mode must be 0 (batch_ridge), 1 (rls), or 2 (sgd), got " + @@ -311,11 +317,30 @@ void llama_hparams::validate_esn_params() const { } } - // Hierarchical parameters + if (esn_output_temperature < 0.0f || !std::isfinite(esn_output_temperature)) { + throw std::invalid_argument( + "ESN: esn.output_temperature must be finite and > 0 when present, got " + + std::to_string(esn_output_temperature)); + } + + // The graph runs one forward reservoir. Configurations it cannot run are + // refused instead of being executed as something else. + if (esn_bidirectional) { + throw std::invalid_argument( + "ESN: esn.bidirectional is set, but inference runs the reservoir forward only " + "(a backward pass would read tokens that have not been generated yet)"); + } if (esn_n_levels == 0) { throw std::invalid_argument("ESN: esn_n_levels must be >= 1"); } - if (esn_n_levels > 1 && esn_branching_factor == 0) { - throw std::invalid_argument("ESN: esn_branching_factor must be >= 1 for hierarchical ESN (n_levels > 1)"); + if (esn_n_levels > 1 || esn_lateral_links || esn_top_down_mod) { + throw std::invalid_argument( + "ESN: hierarchical reservoirs (esn.n_levels > 1, esn.lateral_links, " + "esn.top_down_mod) are not implemented; this build runs a single reservoir"); + } + if (esn_online_learning && !esn_freeze_reservoir) { + throw std::invalid_argument( + "ESN: esn.freeze_reservoir = false is not supported; online learning " + "updates the readout only"); } } diff --git a/src/llama-hparams.h b/src/llama-hparams.h index 6b8286f92cf9..deeb35677de2 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -146,11 +146,14 @@ struct llama_hparams { bool esn_feedback_token = false; // fed-back output is the input token's one-hot float esn_noise_level = 0.0f; // noise injection for regularization uint32_t esn_activation_type = 0; // 0=tanh, 1=sigmoid, 2=leaky_relu - bool esn_bidirectional = false; // unsupported (inference is causal); loader warns + bool esn_bidirectional = false; // unsupported (inference is causal); loader rejects it + // softmax temperature folded into W_out by training: the readout was fit + // to temperature * one-hot targets (0 = not recorded in the GGUF) + float esn_output_temperature = 0.0f; // ESN online learning / infer-train (Phase 3) bool esn_online_learning = false; // enable online readout adaptation - float esn_online_lr = 1e-4f; // online learning rate for RLS/SGD + float esn_online_lr = 1e-4f; // online learning rate (SGD) float esn_online_reg = 1e-6f; // L2 regularization coefficient uint32_t esn_online_buffer_size = 64; // experience replay buffer capacity (tokens) uint32_t esn_online_update_mode = 0; // 0=batch_ridge, 1=rls, 2=sgd diff --git a/src/llama-model.cpp b/src/llama-model.cpp index a222da284444..ff9ef1c44abc 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -2064,6 +2064,7 @@ void llama_model::load_hparams(llama_model_loader & ml) { ml.get_key(LLM_KV_ESN_NOISE_LEVEL, hparams.esn_noise_level, false); ml.get_key(LLM_KV_ESN_ACTIVATION_TYPE, hparams.esn_activation_type, false); ml.get_key(LLM_KV_ESN_BIDIRECTIONAL, hparams.esn_bidirectional, false); + ml.get_key(LLM_KV_ESN_OUTPUT_TEMPERATURE, hparams.esn_output_temperature, false); // Online learning configuration (optional, defaults to disabled) ml.get_key(LLM_KV_ESN_ONLINE_LEARNING_ENABLED, hparams.esn_online_learning, false); @@ -2086,12 +2087,6 @@ void llama_model::load_hparams(llama_model_loader & ml) { // Validate all ESN parameters now that they are loaded hparams.validate_esn_params(); - if (hparams.esn_bidirectional) { - LLAMA_LOG_WARN("%s: esn.bidirectional is set, but inference runs the reservoir forward only; " - "a readout trained on backward-pass states saw the next token and scores worse than " - "its training metrics\n", __func__); - } - switch (hparams.n_layer) { case 1: type = LLM_TYPE_SMALL; break; default: type = LLM_TYPE_UNKNOWN; @@ -19608,10 +19603,16 @@ struct llm_build_esn : public llm_graph_context_mamba { cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); cb(cur, "result_norm", -1); res->t_embd = cur; + if (esn_capture) { + // the context reads the readout input back for online adaptation + ggml_set_output(cur); + } // W_out · x : [reservoir_size, n_vocab] * [reservoir_size, n_out] // -> [n_vocab, n_out] - cur = build_lora_mm(model.output, cur); + // A context that has adapted its readout (llama_esn_update_readout) + // supplies its own copy of W_out. + cur = build_lora_mm(esn_readout ? esn_readout : model.output, cur); cb(cur, "result_output", -1); res->t_logits = cur; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 25f762838f1d..00fa905e5097 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -149,6 +149,8 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) # calls the CPU backend directly llama_build_and_test(test-esn-activations.cpp) endif() + # online readout adaptation; writes its own small models + llama_build_and_test(test-esn-online.cpp) # 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-online.cpp b/tests/test-esn-online.cpp new file mode 100644 index 000000000000..93a86743a46a --- /dev/null +++ b/tests/test-esn-online.cpp @@ -0,0 +1,398 @@ +// Online readout adaptation of an ESN context (the llama_esn_* API). +// +// Writes small ESN GGUFs with the gguf API (random reservoir, byte +// vocabulary; one with esn.online_learning.enabled, one without), decodes +// through the public llama API, and checks that feedback actually retrains +// the readout the next decode uses: +// +// A. Non-ESN-adaptive and argument errors: -2 for a NULL context, -4 for an +// ESN without online learning, -3 for feedback on a position that was +// never decoded, for latency events and for out-of-range tokens. +// B. Ridge (mode 0): one correction at a position moves the readout so the +// logits there become T * one-hot(target) (T = esn.output_temperature), +// to within lambda; the update returns the number of events consumed. +// C. The adapted readout is per context: a second context on the same model +// still produces the checkpoint logits. +// D. llama_esn_reset_adaptation restores the checkpoint logits bit for bit. +// E. RLS (mode 1) on the same single sample reaches the ridge solution. +// F. SGD (mode 2): a correction raises the target's probability; a negative +// reward lowers it. Least-squares modes refuse negative rewards (-7). +// G. Graph reuse: single-token decodes after an update keep using the +// readout as later updates change it in place. +// H. The feedback buffer is bounded by esn.online_learning.buf_size (-5). +// +// With a model path argument the same flow runs on that model (it must have +// esn.online_learning.enabled) with checks that do not depend on knowing its +// temperature: after a ridge correction the target is the argmax. + +#ifdef NDEBUG +#undef NDEBUG +#endif + +#include "llama.h" +#include "ggml.h" +#include "gguf.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static constexpr uint32_t N_RES = 64; +static constexpr uint32_t N_EMBD = 16; +static constexpr uint32_t N_VOCAB = 256; +static constexpr float TEMP = 2.0f; + +static void silent_log(enum ggml_log_level, const char *, void *) {} + +static void write_model(const std::string & path, bool online) { + gguf_context * g = gguf_init_empty(); + gguf_set_val_str (g, "general.architecture", "esn"); + gguf_set_val_u32 (g, "esn.vocab_size", N_VOCAB); + gguf_set_val_u32 (g, "esn.embedding_length", N_EMBD); + gguf_set_val_u32 (g, "esn.context_length", 2048); + gguf_set_val_u32 (g, "esn.block_count", 1); + gguf_set_val_f32 (g, "esn.attention.layer_norm_rms_epsilon", 1e-6f); + gguf_set_val_u32 (g, "esn.reservoir_size", N_RES); + gguf_set_val_f32 (g, "esn.spectral_radius", 0.9f); + gguf_set_val_f32 (g, "esn.sparsity", 1.0f); + gguf_set_val_f32 (g, "esn.leaking_rate", 0.5f); + gguf_set_val_f32 (g, "esn.input_scaling", 1.0f); + gguf_set_val_f32 (g, "esn.output_temperature", TEMP); + if (online) { + gguf_set_val_bool(g, "esn.online_learning.enabled", true); + gguf_set_val_u32 (g, "esn.online_learning.buf_size", 64); + gguf_set_val_u32 (g, "esn.replay_window", 256); + } + + std::vector text(N_VOCAB); + std::vector tokens(N_VOCAB); + std::vector types(N_VOCAB, 1); + for (uint32_t b = 0; b < N_VOCAB; ++b) { + char buf[8]; + snprintf(buf, sizeof(buf), "\\x%02x", b); + text[b] = buf; + tokens[b] = text[b].c_str(); + } + gguf_set_val_str (g, "tokenizer.ggml.model", "rwkv"); + gguf_set_arr_str (g, "tokenizer.ggml.tokens", tokens.data(), tokens.size()); + gguf_set_arr_data(g, "tokenizer.ggml.token_type", GGUF_TYPE_INT32, types.data(), types.size()); + + ggml_init_params ip = { 64 * ggml_tensor_overhead() + 4 * (N_EMBD * N_VOCAB + N_EMBD * N_RES + N_RES * N_RES + N_RES + N_RES * N_VOCAB) + 4096, + nullptr, false }; + ggml_context * ctx = ggml_init(ip); + std::mt19937 rng(1234); + std::normal_distribution nd(0.0f, 1.0f); + auto fill = [&](const char * name, int64_t ne0, int64_t ne1, float scale) { + ggml_tensor * t = ne1 ? ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne0, ne1) : ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne0); + ggml_set_name(t, name); + float * d = (float *) t->data; + for (int64_t i = 0; i < ggml_nelements(t); ++i) { + d[i] = scale < 0 ? 1.0f : scale * nd(rng); + } + gguf_add_tensor(g, t); + }; + fill("token_embd.weight", N_EMBD, N_VOCAB, 1.0f); + fill("esn_input_weights.weight", N_EMBD, N_RES, 0.5f / std::sqrt((float) N_EMBD)); + fill("esn_reservoir_weights.weight", N_RES, N_RES, 0.9f / std::sqrt((float) N_RES)); + fill("output_norm.weight", N_RES, 0, -1.0f); + fill("esn_output_weights.weight", N_RES, N_VOCAB, 0.1f); + + const bool ok = gguf_write_to_file(g, path.c_str(), false); + assert(ok); + gguf_free(g); + ggml_free(ctx); +} + +static llama_context * make_ctx(llama_model * model) { + llama_context_params cp = llama_context_default_params(); + cp.n_ctx = 128; + cp.n_batch = 128; + cp.n_ubatch = 128; + cp.no_perf = true; + return llama_init_from_model(model, cp); +} + +// Decode tokens from position 0 with every position as an output and return +// the logits of all positions. +static std::vector> decode_all(llama_context * ctx, const std::vector & toks) { + llama_memory_clear(llama_get_memory(ctx), true); + llama_batch b = llama_batch_init((int32_t) toks.size(), 0, 1); + for (size_t i = 0; i < toks.size(); ++i) { + b.token[i] = toks[i]; + b.pos[i] = (llama_pos) i; + b.n_seq_id[i] = 1; + b.seq_id[i][0] = 0; + b.logits[i] = 1; + } + b.n_tokens = (int32_t) toks.size(); + const int rc = llama_decode(ctx, b); + assert(rc == 0); + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + std::vector> out(toks.size()); + for (size_t i = 0; i < toks.size(); ++i) { + const float * l = llama_get_logits_ith(ctx, (int32_t) i); + out[i].assign(l, l + n_vocab); + } + llama_batch_free(b); + return out; +} + +static double prob(const std::vector & z, int tok) { + const float m = *std::max_element(z.begin(), z.end()); + double s = 0.0; + for (float v : z) { + s += std::exp((double) (v - m)); + } + return std::exp((double) (z[tok] - m)) / s; +} + +static llama_esn_feedback_event event(llama_esn_feedback_type type, llama_pos pos, const llama_token * tok, float signal = 0.0f) { + return { type, 0, pos, signal, tok, 1 }; +} + +static llama_esn_online_params mode_params(uint32_t mode, float lr = 0.0f, float reg = 1e-4f) { + llama_esn_online_params p = llama_esn_online_params_default(); + p.enabled = true; + p.update_mode = mode; + p.learning_rate = lr; + p.regularization = reg; + return p; +} + +static float max_abs_diff(const std::vector & a, const std::vector & b) { + float d = 0.0f; + for (size_t i = 0; i < a.size(); ++i) { + d = std::max(d, std::fabs(a[i] - b[i])); + } + return d; +} + +int main(int argc, char ** argv) { + llama_log_set(silent_log, nullptr); + llama_backend_init(); + + const bool synthetic = argc < 2; + const auto dir = std::filesystem::temp_directory_path(); + const std::string path_on = synthetic ? (dir / "test-esn-online.gguf").string() : argv[1]; + const std::string path_off = (dir / "test-esn-online-off.gguf").string(); + if (synthetic) { + write_model(path_on, true); + } + write_model(path_off, false); + + llama_model_params mp = llama_model_default_params(); + mp.use_extra_bufts = false; + llama_model * model = llama_model_load_from_file(path_on.c_str(), mp); + llama_model * plain = llama_model_load_from_file(path_off.c_str(), mp); + assert(model && plain); + assert(llama_esn_is_adaptive(model) && !llama_esn_is_adaptive(plain)); + assert(llama_esn_reservoir_size(plain) == N_RES && llama_esn_n_levels(plain) == 1); + assert(llama_esn_model_online_params(model).enabled && !llama_esn_model_online_params(plain).enabled); + if (synthetic) { + const llama_esn_online_params mp_on = llama_esn_model_online_params(model); + assert(mp_on.update_mode == 0 && mp_on.replay_window == 256 && mp_on.freeze_reservoir); + } + + printf("test-esn-online: %s\n", synthetic ? "synthetic model" : path_on.c_str()); + + const std::vector prompt = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' }; + const llama_pos at = 4; + const llama_token target = 'z'; + + // A + { + llama_context * ctx_plain = make_ctx(plain); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, 0, &target); + llama_esn_online_params p = mode_params(0); + assert(llama_esn_submit_feedback(nullptr, &ev, 1) == -2); + assert(llama_esn_update_readout(nullptr, &p) == -2); + assert(llama_esn_submit_feedback(ctx_plain, &ev, 1) == -4); + assert(llama_esn_update_readout(ctx_plain, &p) == -4); + llama_esn_reset_adaptation(ctx_plain); + llama_free(ctx_plain); + printf(" A1 errors on NULL / non-adaptive contexts: ok\n"); + } + + llama_context * ctx = make_ctx(model); + llama_context * ctx2 = make_ctx(model); + { + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == -3); // nothing decoded yet + } + + const auto base = decode_all(ctx, prompt); + { + const llama_token bad = (llama_token) N_VOCAB; + llama_esn_feedback_event lat = event(LLAMA_ESN_FEEDBACK_LATENCY, at, &target, 12.0f); + llama_esn_feedback_event oob = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &bad); + llama_esn_feedback_event far = event(LLAMA_ESN_FEEDBACK_CORRECTION, (llama_pos) prompt.size(), &target); + llama_esn_feedback_event ok = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + llama_esn_feedback_event batch[2] = { ok, oob }; + assert(llama_esn_submit_feedback(ctx, &lat, 1) == -3); + assert(llama_esn_submit_feedback(ctx, &oob, 1) == -3); + assert(llama_esn_submit_feedback(ctx, &far, 1) == -3); + assert(llama_esn_submit_feedback(ctx, batch, 2) == -3); // all or nothing + llama_esn_online_params p = mode_params(0); + assert(llama_esn_update_readout(ctx, &p) == 0); // nothing pending + p.freeze_reservoir = false; + assert(llama_esn_update_readout(ctx, &p) == -3); + printf(" A2 invalid feedback and parameters are rejected: ok\n"); + } + + // B: ridge + std::vector> ridge; + { + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + llama_esn_online_params off = mode_params(0); + off.enabled = false; + assert(llama_esn_update_readout(ctx, &off) == 0); + assert(max_abs_diff(decode_all(ctx, prompt)[at], base[at]) == 0.0f); + + llama_esn_online_params p = mode_params(0, 0.0f, 1e-4f); + assert(llama_esn_update_readout(ctx, &p) == 1); + ridge = decode_all(ctx, prompt); + const auto & z = ridge[at]; + int argmax = (int) (std::max_element(z.begin(), z.end()) - z.begin()); + assert(argmax == target); + if (synthetic) { + // |x|^2 = N_RES after the RMS norm, so the residual shrinks by + // lambda / (N_RES + lambda) + for (uint32_t v = 0; v < N_VOCAB; ++v) { + const float want = v == (uint32_t) target ? TEMP : 0.0f; + assert(std::fabs(z[v] - want) < 1e-3f); + } + } + assert(max_abs_diff(ridge[at + 1], base[at + 1]) > 0.0f); // the readout changed everywhere + printf(" B ridge correction: logit[target] %.4f -> %.4f, p %.4f -> %.4f: ok\n", + base[at][target], z[target], prob(base[at], target), prob(z, target)); + } + + // C + { + const auto other = decode_all(ctx2, prompt); + for (size_t i = 0; i < prompt.size(); ++i) { + assert(max_abs_diff(other[i], base[i]) == 0.0f); + } + printf(" C a second context keeps the checkpoint readout: ok\n"); + } + + // D + { + llama_esn_reset_adaptation(ctx); + const auto again = decode_all(ctx, prompt); + for (size_t i = 0; i < prompt.size(); ++i) { + assert(max_abs_diff(again[i], base[i]) == 0.0f); + } + printf(" D reset restores the checkpoint logits exactly: ok\n"); + } + + // E: RLS on the same sample + { + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + llama_esn_online_params p = mode_params(1, 0.0f, 1e-4f); + assert(llama_esn_update_readout(ctx, &p) == 1); + const auto rls = decode_all(ctx, prompt); + for (size_t i = 0; i < prompt.size(); ++i) { + assert(max_abs_diff(rls[i], ridge[i]) < 1e-3f); + } + printf(" E RLS reaches the ridge solution for one sample: ok\n"); + llama_esn_reset_adaptation(ctx); + } + + // F: SGD + { + decode_all(ctx, prompt); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + llama_esn_online_params p = mode_params(2, 0.02f, 0.0f); + assert(llama_esn_update_readout(ctx, &p) == 1); + const double p_up = prob(decode_all(ctx, prompt)[at], target); + assert(p_up > prob(base[at], target)); + + const llama_token emitted = 'q'; + llama_esn_feedback_event pen = event(LLAMA_ESN_FEEDBACK_REWARD, at, &emitted, -1.0f); + const double q_before = prob(decode_all(ctx, prompt)[at], emitted); + assert(llama_esn_submit_feedback(ctx, &pen, 1) == 0); + llama_esn_online_params ls = mode_params(0); + assert(llama_esn_update_readout(ctx, &ls) == -7); // stays pending + assert(llama_esn_update_readout(ctx, &p) == 1); + const double q_after = prob(decode_all(ctx, prompt)[at], emitted); + assert(q_after < q_before); + printf(" F SGD: p[target] %.4f -> %.4f; negative reward p %.4f -> %.4f: ok\n", + prob(base[at], target), p_up, q_before, q_after); + llama_esn_reset_adaptation(ctx); + } + + // G: in-place readout updates under graph reuse + { + decode_all(ctx, prompt); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + llama_esn_online_params p = mode_params(2, 0.02f, 0.0f); + assert(llama_esn_update_readout(ctx, &p) == 1); + + // one token at a time from pos 0: same-shaped graphs, reused + auto step_all = [&]() { + llama_memory_clear(llama_get_memory(ctx), true); + std::vector last; + for (size_t i = 0; i <= (size_t) at; ++i) { + llama_token t = prompt[i]; + assert(llama_decode(ctx, llama_batch_get_one(&t, 1)) == 0); + } + const float * l = llama_get_logits_ith(ctx, -1); + last.assign(l, l + N_VOCAB); + return last; + }; + const auto first = step_all(); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + assert(llama_esn_update_readout(ctx, &p) == 1); + const int32_t reused = llama_perf_context(ctx).n_reused; + const auto second = step_all(); + if (getenv("LLAMA_GRAPH_REUSE_DISABLE") == nullptr) { + assert(llama_perf_context(ctx).n_reused > reused); + } + assert(prob(second, target) > prob(first, target)); + llama_esn_reset_adaptation(ctx); + assert(max_abs_diff(step_all(), base[at]) < 1e-5f); + printf(" G updates apply to reused graphs: ok\n"); + } + + // H + { + std::vector longp; + for (int i = 0; i < 70; ++i) { + longp.push_back((llama_token) ('a' + i % 26)); + } + decode_all(ctx, longp); + std::vector tg(65, target); + llama_esn_feedback_event ev = { LLAMA_ESN_FEEDBACK_CORRECTION, 0, 0, 0.0f, tg.data(), 65 }; + assert(llama_esn_submit_feedback(ctx, &ev, 1) == -5); + ev.n_target_tokens = 64; + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + llama_esn_online_params p = mode_params(0, 0.0f, 1e-2f); + assert(llama_esn_update_readout(ctx, &p) == 1); + printf(" H the feedback buffer is bounded: ok\n"); + } + + llama_free(ctx); + llama_free(ctx2); + llama_model_free(model); + llama_model_free(plain); + if (synthetic) { + std::filesystem::remove(path_on); + } + std::filesystem::remove(path_off); + llama_backend_free(); + + printf("test-esn-online: PASSED (A..H)\n"); + return 0; +} From 6b77faf12dc64cb8ce52f82c439e59364c4b1f56 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 17:47:53 +0000 Subject: [PATCH 05/10] ESN: stack step states with concat on multi-backend schedulers; fix vulkan 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 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- .github/workflows/build.yml | 9 +++++- docs/esn.md | 8 ++++-- src/llama-model.cpp | 56 +++++++++++++++++++++++++++++-------- 3 files changed, 59 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 58078da6dd0b..f68b0ea0683d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -398,10 +398,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # GGML_NATIVE (the default) builds with -march=native, and ccache 4.5 + # hashes that flag literally, so key the cache on the runner's CPU + # features to never reuse objects built for a different CPU + run: echo "fingerprint=$(grep -E '^(model name|flags|CPU part|Features)' /proc/cpuinfo | sort -u | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT" + - name: ccache uses: ggml-org/ccache-action@v1.2.16 with: - key: ubuntu-24-cmake-vulkan + key: ubuntu-24-cmake-vulkan-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Dependencies diff --git a/docs/esn.md b/docs/esn.md index 4090c1195b55..8ebce34e67a9 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -113,7 +113,10 @@ The ESN forward pass (`llm_build_esn` in `src/llama-model.cpp`) consists of: 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 + the last sees them all. The row index is a per-step view of a CPU input, + which a GPU backend would copy as one split input per step (and abort + past `GGML_SCHED_MAX_SPLIT_INPUTS`), so with more than one backend the + steps are concatenated in a balanced `ggml_concat` tree instead 9. **Output Normalization & Projection**: RMS norm, then `W_out * reservoir_state → vocabulary_logits` @@ -520,7 +523,8 @@ the table below at R = 2048 and 8192): 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). + times; it now writes each state once (step 8 above) when the CPU is the + only backend. | R | 256 | 1024 | 2048 | 8192 | |---|---:|---:|---:|---:| diff --git a/src/llama-model.cpp b/src/llama-model.cpp index ff9ef1c44abc..a4aedcda0ca0 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -19523,16 +19523,25 @@ 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. 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. + // loop, and stack every step's state so the output has one reservoir + // vector per input token, laid out [reservoir_size, n_seq_tokens, + // n_seqs] so it flattens in the order inp_out_ids indexes. + // + // When the CPU is the only backend, each step's state is written into + // its row of `states` with ggml_set_rows: one row copy per step. Every + // write returns a view of the whole buffer that depends on the + // previous one, so reading the last sees them all. The row index is a + // per-step view of an input, though, and with another backend in the + // scheduler each such view becomes a separate split input; more than + // GGML_SCHED_MAX_SPLIT_INPUTS of them abort the graph. Then the steps + // are concatenated pairwise in a balanced tree instead (each copied + // log2(n) times), which keeps every operand on the backend that + // computed it. + const bool stack_rows = n_seq_tokens > 1 && ggml_backend_sched_get_n_backends(sched) == 1; + std::vector per_step; ggml_tensor * states = nullptr; ggml_tensor * steps = nullptr; - if (n_seq_tokens > 1) { + if (stack_rows) { auto inp = std::make_unique(); inp->steps = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seq_tokens); ggml_set_input(inp->steps); @@ -19540,6 +19549,8 @@ struct llm_build_esn : public llm_graph_context_mamba { res->add_input(std::move(inp)); states = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, reservoir_size, n_seq_tokens, n_seqs); + } else if (n_seq_tokens > 1) { + per_step.reserve(n_seq_tokens); } ggml_tensor * state = reservoir_state; // [reservoir_size, n_seqs] @@ -19574,6 +19585,8 @@ struct llm_build_esn : public llm_graph_context_mamba { 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))); + } else if (n_seq_tokens > 1) { + per_step.push_back(state); } } cb(state, "esn_reservoir_final", -1); @@ -19590,9 +19603,30 @@ struct llm_build_esn : public llm_graph_context_mamba { // 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); + ggml_tensor * cur; + if (n_seq_tokens == 1) { + cur = ggml_reshape_2d(ctx0, state, reservoir_size, n_seqs); + } else if (states) { + cur = ggml_reshape_2d(ctx0, states, reservoir_size, n_tokens); + } else { + std::vector level; + level.reserve(n_seq_tokens); + for (ggml_tensor * s : per_step) { + 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); + } cb(cur, "esn_reservoir_seq", -1); if (inp_out_ids) { From 4917497c8cee95a821e543c45adf3492654ab9ed Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 17:57:18 +0000 Subject: [PATCH 06/10] ci: key the webgpu job's ccache on the runner's CPU ubuntu-22-cmake-webgpu builds with GGML_NATIVE (-march=native) and runs ctest, but its ccache key ignored the CPU. Objects built on a runner with a newer instruction set were restored on an older one, and test-esn-activations and test-esn-online died with SIGILL. Use the same CPU-fingerprint key as the Vulkan and ggml-ci jobs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- .github/workflows/build.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f68b0ea0683d..de0eadb203a3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -463,10 +463,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # GGML_NATIVE (the default) builds with -march=native, and ccache 4.5 + # hashes that flag literally, so key the cache on the runner's CPU + # features to never reuse objects built for a different CPU + run: echo "fingerprint=$(grep -E '^(model name|flags|CPU part|Features)' /proc/cpuinfo | sort -u | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT" + - name: ccache uses: ggml-org/ccache-action@v1.2.16 with: - key: ubuntu-22-cmake-webgpu + key: ubuntu-22-cmake-webgpu-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Vulkan SDK Dependencies From 913eb695e6bef51297ac2ba088aed19300312318 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 18:14:17 +0000 Subject: [PATCH 07/10] ESN online: fix stale captures, unsafe failure paths and LoRA handling Review fixes for the llama_esn_* online readout API: - Captures follow the sequence: every decoded token, output or not, discards recordings at and after its position, and feedback is refused for positions past the memory's newest one. Before, re-decoding a cleared sequence with logits only at the end left the old prompt's states trainable at the earlier positions. - The readout check refuses every CPU extra buffer type (REPACK, AMX) found through ggml_backend_dev_get_extra_bufts, instead of matching "REPACK" by name; AMX has no get_tensor and crashed. - The adapted readout is built in locals and committed only once allocated, so a failed allocation can be retried or reset safely. - A singular ridge pivot (below 1e-12 of its diagonal) or a non-positive RLS denominator returns -9 instead of aborting; RLS restores W and P, so the readout and the pending samples are unchanged. - submit checks the buffer bound before each copy rather than after copying the whole batch. - A LoRA on the readout and an adapted readout exclude each other (-10 from the update; llama_set_adapter_lora returns -1 while adapted), since the adapted tensor would silently drop the LoRA delta. - Setting, removing or clearing LoRA adapters now resets the previous graph: graph reuse compared the adapter map by address only, so an adapter added after a decode was not applied. - esn_training.py refuses --save-online-metadata with --init-only unless the runtime mode is SGD: ridge/RLS need esn.output_temperature. - The ESN tests call ggml_backend_load_all() (GGML_BACKEND_DL builds). test-esn-online adds I (rewind/clear), J (singular solve) and K (LoRA). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- docs/esn.md | 21 ++++- include/llama.h | 14 +++- scripts/esn_training.py | 6 ++ src/llama-context.cpp | 61 +++++++++++--- src/llama-context.h | 6 +- src/llama-esn.cpp | 146 ++++++++++++++++++++++++---------- src/llama-esn.h | 17 ++-- tests/test-esn-inference.cpp | 2 + tests/test-esn-online.cpp | 119 ++++++++++++++++++++++++++- tests/test-esn-perplexity.cpp | 2 + 10 files changed, 327 insertions(+), 67 deletions(-) diff --git a/docs/esn.md b/docs/esn.md index 8ebce34e67a9..9b60aa2b478b 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -695,10 +695,25 @@ readout without the key (SGD-trained or untrained) can only be adapted with SGD. Corrections and tool results are samples of weight 1; rewards weight the emitted token by the reward (negative only with SGD); confidence weights it by a value in [0, 1]. Latency events are rejected: they carry -no token target. A readout stored repacked for the CPU kernels cannot be -read back; load such models with `use_extra_bufts = false` (`--no-repack`). +no token target. A readout stored in one of the CPU's extra buffer types +(REPACK, AMX) cannot be read back; load such models with +`use_extra_bufts = false` (`--no-repack`). The adapted readout is not included in `llama_state_*` data. -`tests/test-esn-online.cpp` checks each mode against its closed form. + +Recordings follow the sequence: decoding a position again (after +`llama_memory_seq_rm` or a memory clear) discards what was recorded at and +after it, even when the new tokens produce no logits, and feedback is +refused (-3) for positions past the newest one the context's memory holds. +A batch of feedback that would overflow `esn.online_learning.buf_size` is +refused (-5) before anything is copied. If a least-squares solve is +numerically singular (λ below the rounding of `Σ w x xᵀ`), the update +returns -9 and leaves the readout and the pending samples as they were; +raise `regularization`. A LoRA on `esn_output_weights` and an adapted +readout exclude each other: the update returns -10 while such an adapter +is set, and `llama_set_adapter_lora` returns -1 for one while the readout +is adapted (`llama_esn_reset_adaptation` lifts it). +`tests/test-esn-online.cpp` checks each mode against its closed form, and +the rewind, singular-solve and LoRA rules. **Proprioceptive feedback**: Signals originating from the model's own execution context: - `CORRECTION` — explicit user or verifier correction diff --git a/include/llama.h b/include/llama.h index fc75ecd229e6..13f64a882748 100644 --- a/include/llama.h +++ b/include/llama.h @@ -572,6 +572,13 @@ extern "C" { // -6 a least-squares mode needs esn.output_temperature, which the model lacks // -7 a least-squares mode was given samples with negative weight // -8 the readout could not be read or allocated (see the log) + // -9 the least-squares solve was numerically singular; raise regularization + // -10 a LoRA adapter on the context modifies the readout + // + // Positions are tracked per sequence: decoding a position again (after + // llama_memory_seq_rm or a memory clear) discards what was recorded at + // and after it, and feedback is refused for positions past the newest one + // the context's memory holds. // enum llama_esn_feedback_type { @@ -630,7 +637,8 @@ extern "C" { // events are validated first; on error none is added. // Returns 0 on success; -3 for an unknown or LATENCY type, missing or // out-of-range targets, a non-finite reward, a confidence outside [0, 1], - // or a position with no recorded readout input; -1, -2, -4, -5. + // or a position with no recorded readout input; -5 if the batch would + // overflow the feedback buffer; -1, -2, -4. LLAMA_API int32_t llama_esn_submit_feedback( struct llama_context * ctx, const struct llama_esn_feedback_event * events, @@ -641,7 +649,7 @@ extern "C" { // T = esn.output_temperature, the scale the exported readout was fit to. // Returns the number of events consumed (0 if none were pending or // params->enabled is false); -3 for invalid params; -1, -2, -4, -6, -7, - // -8. On error the pending samples are kept. + // -8, -9, -10. On error the readout and the pending samples are unchanged. LLAMA_API int32_t llama_esn_update_readout( struct llama_context * ctx, const struct llama_esn_online_params * params); @@ -702,6 +710,8 @@ extern "C" { // Add a loaded LoRA adapter to given context // This will not modify model's weight + // Returns -1 if the adapter modifies an ESN readout the context has + // adapted online (see llama_esn_reset_adaptation), 0 otherwise LLAMA_API int32_t llama_set_adapter_lora( struct llama_context * ctx, struct llama_adapter_lora * adapter, diff --git a/scripts/esn_training.py b/scripts/esn_training.py index 6d4bd1a5be47..ee9e46531dc7 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -1240,6 +1240,12 @@ def main(): if not args.init_only and not args.train_data: parser.error("--train-data is required to train the readout " "(use --init-only to write untrained random weights)") + if args.save_online_metadata and args.init_only and not (args.online and args.online_mode == "sgd"): + # the runtime ridge/RLS updates fit W_out x to T * one-hot, and an + # untrained readout has no scale T (esn.output_temperature) to use + parser.error("--save-online-metadata with --init-only selects a least-squares runtime update, " + "which needs the scale a trained readout was fit to; train the readout " + "(--train-data) or choose SGD (--online --online-mode sgd)") if not (0.0 < args.forgetting_factor <= 1.0): parser.error("--forgetting-factor must be in (0, 1]") if args.bidirectional: diff --git a/src/llama-context.cpp b/src/llama-context.cpp index cca11e4a8813..310d25453b9c 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -485,6 +485,18 @@ llama_esn_adapter * llama_context::get_esn() const { return esn.get(); } +bool llama_context::lora_adapts_readout() const { + if (model.output == nullptr) { + return false; + } + for (const auto & lora : loras) { + if (lora.first->get_weight(model.output) != nullptr) { + return true; + } + } + return false; +} + bool llama_context::memory_update(bool optimize) { if (!memory) { return false; @@ -700,12 +712,26 @@ void llama_context::set_warmup(bool value) { cparams.warmup = value; } -void llama_context::set_adapter_lora( +bool llama_context::set_adapter_lora( llama_adapter_lora * adapter, float scale) { LLAMA_LOG_DEBUG("%s: adapter = %p, scale = %f\n", __func__, (void *) adapter, scale); + // the adapted ESN readout replaces model.output in the graph, where a + // LoRA on it would no longer apply + if (esn && esn->readout() != nullptr && adapter->get_weight(model.output) != nullptr) { + LLAMA_LOG_ERROR("%s: the adapter modifies the ESN readout, which this context has adapted online; " + "call llama_esn_reset_adaptation first\n", __func__); + return false; + } + loras[adapter] = scale; + // graph reuse compares the adapter set by address only, so a graph built + // before this change must not be reused + if (gf_res_prev) { + gf_res_prev->reset(); + } + return true; } bool llama_context::rm_adapter_lora( @@ -715,6 +741,9 @@ bool llama_context::rm_adapter_lora( auto pos = loras.find(adapter); if (pos != loras.end()) { loras.erase(pos); + if (gf_res_prev) { + gf_res_prev->reset(); + } return true; } @@ -725,6 +754,9 @@ void llama_context::clear_adapter_lora() { LLAMA_LOG_DEBUG("%s: call\n", __func__); loras.clear(); + if (gf_res_prev) { + gf_res_prev->reset(); + } } bool llama_context::apply_adapter_cvec( @@ -1209,15 +1241,20 @@ int llama_context::decode(const llama_batch & batch_inp) { } } - // record the ESN readout inputs for online adaptation - if (esn && n_outputs > 0) { - ggml_tensor * t_x = res->get_embd(); - GGML_ASSERT(t_x != nullptr && t_x->type == GGML_TYPE_F32); - ggml_backend_t backend_x = ggml_backend_sched_get_tensor_backend(sched.get(), t_x); - GGML_ASSERT(backend_x != nullptr); - esn_rows.resize((size_t) n_outputs * t_x->ne[0]); - ggml_backend_tensor_get_async(backend_x, t_x, esn_rows.data(), 0, esn_rows.size()*sizeof(float)); - ggml_backend_sched_synchronize(sched.get()); + // record the ESN readout inputs for online adaptation; every ubatch + // is passed, since decoding a position invalidates older recordings + // at and after it even when it produces no output + if (esn) { + esn_rows.clear(); + if (n_outputs > 0) { + ggml_tensor * t_x = res->get_embd(); + GGML_ASSERT(t_x != nullptr && t_x->type == GGML_TYPE_F32); + ggml_backend_t backend_x = ggml_backend_sched_get_tensor_backend(sched.get(), t_x); + GGML_ASSERT(backend_x != nullptr); + esn_rows.resize((size_t) n_outputs * t_x->ne[0]); + ggml_backend_tensor_get_async(backend_x, t_x, esn_rows.data(), 0, esn_rows.size()*sizeof(float)); + ggml_backend_sched_synchronize(sched.get()); + } esn->capture(ubatch, n_outputs, esn_rows.data()); } @@ -2504,9 +2541,7 @@ int32_t llama_set_adapter_lora( llama_context * ctx, llama_adapter_lora * adapter, float scale) { - ctx->set_adapter_lora(adapter, scale); - - return 0; + return ctx->set_adapter_lora(adapter, scale) ? 0 : -1; } int32_t llama_rm_adapter_lora( diff --git a/src/llama-context.h b/src/llama-context.h index 4258e4b779d0..833c34e2e863 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -60,6 +60,9 @@ struct llama_context { // with esn.online_learning.enabled llama_esn_adapter * get_esn() const; + // true if a LoRA adapter on this context modifies the model's readout + bool lora_adapts_readout() const; + // return true if the memory was updated bool memory_update(bool optimize); @@ -86,7 +89,8 @@ struct llama_context { void set_causal_attn(bool value); void set_warmup(bool value); - void set_adapter_lora( + // false if the adapter modifies an ESN readout that is currently adapted + bool set_adapter_lora( llama_adapter_lora * adapter, float scale); diff --git a/src/llama-esn.cpp b/src/llama-esn.cpp index 4f2f215e66f7..70c855025329 100644 --- a/src/llama-esn.cpp +++ b/src/llama-esn.cpp @@ -80,27 +80,29 @@ llama_esn_adapter::~llama_esn_adapter() = default; void llama_esn_adapter::capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows) { uint32_t j = 0; - for (uint32_t i = 0; i < ubatch.n_tokens && j < n_outputs; ++i) { - if (n_outputs != ubatch.n_tokens && !ubatch.output[i]) { - continue; - } - const float * x = rows + (size_t) j * n_res; - ++j; + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + const bool is_output = n_outputs == ubatch.n_tokens || (n_outputs > 0 && ubatch.output[i]); + const float * x = is_output ? rows + (size_t) j++ * n_res : nullptr; const llama_pos pos = ubatch.pos[i]; for (int32_t s = 0; s < ubatch.n_seq_id[i]; ++s) { auto & q = recorded[ubatch.seq_id[i][s]]; - // a position at or before the newest one means the sequence was - // rewound (seq_rm, memory clear): what was recorded from there on - // belongs to tokens that are gone + // decoding a position at or before the newest recorded one means + // the sequence was rewound (seq_rm, memory clear): what was + // recorded from there on belongs to tokens that are gone, whether + // or not this token produces an output while (!q.empty() && q.back().pos >= pos) { q.pop_back(); } + if (x == nullptr) { + continue; + } q.push_back({ pos, std::vector(x, x + n_res) }); while (q.size() > recorded_cap) { q.pop_front(); } } } + GGML_ASSERT(j == n_outputs); } const llama_esn_adapter::captured * llama_esn_adapter::find(llama_seq_id seq, llama_pos pos) const { @@ -114,7 +116,8 @@ const llama_esn_adapter::captured * llama_esn_adapter::find(llama_seq_id seq, ll return c != q.end() && c->pos == pos ? &*c : nullptr; } -int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32_t n_events) { +int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32_t n_events, + const std::function & pos_max) { if (n_events < 0 || (n_events > 0 && events == nullptr)) { return -3; } @@ -164,23 +167,24 @@ int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32 LLAMA_LOG_ERROR("%s: event %d: target token %d is out of range\n", __func__, e, tok); return -3; } - const captured * c = find(ev.seq_id, ev.pos + k); + const captured * c = ev.pos + k <= pos_max(ev.seq_id) ? find(ev.seq_id, ev.pos + k) : nullptr; if (c == nullptr) { LLAMA_LOG_ERROR("%s: event %d: no readout input recorded for seq %d pos %d (the position " - "was not decoded with an output, was rewound, or is older than the last %zu)\n", + "was not decoded with an output, was rewound or cleared, or is older than the last %zu)\n", __func__, e, ev.seq_id, ev.pos + k, recorded_cap); return -3; } + // checked before each copy, so an oversized batch fails before + // it allocates more than the buffer could hold + if (pending.size() + fresh.size() >= pending_cap) { + LLAMA_LOG_ERROR("%s: event %d: the batch exceeds the feedback buffer (%zu pending of %zu); " + "call llama_esn_update_readout first\n", __func__, e, pending.size(), pending_cap); + return -5; + } fresh.push_back({ c->x, tok, weight }); } } - if (pending.size() + fresh.size() > pending_cap) { - LLAMA_LOG_ERROR("%s: %zu samples would exceed the feedback buffer (%zu pending of %zu); " - "call llama_esn_update_readout first\n", __func__, fresh.size(), pending.size(), pending_cap); - return -5; - } - for (auto & s : fresh) { pending.push_back(std::move(s)); } @@ -198,12 +202,29 @@ void llama_esn_adapter::ensure_readout() { return; } + ggml_backend_dev_t cpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); + if (cpu == nullptr) { + throw std::runtime_error("ESN: online adaptation needs the CPU backend"); + } + // the checkpoint, dequantized const ggml_tensor * out = model.output; - // weights repacked for the CPU matmul kernels cannot be read back - if (out->buffer && strstr(ggml_backend_buft_name(ggml_backend_buffer_get_type(out->buffer)), "REPACK") != nullptr) { - throw std::runtime_error("ESN: the readout is stored repacked for the CPU kernels and cannot be read back; " - "load the model with use_extra_bufts = false (--no-repack) to adapt it"); + if (out->buffer == nullptr) { + throw std::runtime_error("ESN: the readout has no data"); + } + // the CPU's extra buffer types (REPACK, AMX, ...) hold weights in kernel + // layouts and some cannot be read back at all + { + const ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(out->buffer); + auto * get_extra = (ggml_backend_dev_get_extra_bufts_t) + ggml_backend_reg_get_proc_address(ggml_backend_dev_backend_reg(cpu), "ggml_backend_dev_get_extra_bufts"); + for (ggml_backend_buffer_type_t * e = get_extra ? get_extra(cpu) : nullptr; e && *e; ++e) { + if (*e == buft) { + throw std::runtime_error(std::string("ESN: the readout is stored in the ") + ggml_backend_buft_name(buft) + + " buffer for the CPU kernels and cannot be read back; load the model with " + "use_extra_bufts = false (--no-repack) to adapt it"); + } + } } std::vector raw(ggml_nbytes(out)); ggml_backend_tensor_get(out, raw.data(), 0, raw.size()); @@ -222,26 +243,30 @@ void llama_esn_adapter::ensure_readout() { } } + // built in locals and committed only once fully allocated, so a failure + // leaves the adapter as it was and a later update can retry ggml_init_params params = { /*.mem_size =*/ ggml_tensor_overhead(), /*.mem_buffer =*/ nullptr, /*.no_alloc =*/ true, }; - ctx_w.reset(ggml_init(params)); - w = ggml_new_tensor_2d(ctx_w.get(), GGML_TYPE_F32, n_res, n_vocab); - ggml_set_name(w, "esn_adapted_readout"); - - ggml_backend_dev_t cpu = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); - if (cpu == nullptr) { - throw std::runtime_error("ESN: online adaptation needs the CPU backend"); + ggml_context_ptr ctx(ggml_init(params)); + if (!ctx) { + throw std::runtime_error("ESN: failed to create the adapted readout"); } - buf_w.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_w.get(), ggml_backend_dev_buffer_type(cpu))); - if (!buf_w) { + ggml_tensor * t = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, n_res, n_vocab); + ggml_set_name(t, "esn_adapted_readout"); + + ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), ggml_backend_dev_buffer_type(cpu))); + if (!buf) { throw std::runtime_error("ESN: failed to allocate the adapted readout"); } - GGML_ASSERT(ggml_backend_buffer_is_host(buf_w.get())); + GGML_ASSERT(ggml_backend_buffer_is_host(buf.get())); + memcpy(t->data, w0.data(), w0.size() * sizeof(float)); - memcpy(w_data(), w0.data(), w0.size() * sizeof(float)); + ctx_w = std::move(ctx); + buf_w = std::move(buf); + w = t; } int32_t llama_esn_adapter::update(const llama_esn_online_params & p, int n_threads) { @@ -286,10 +311,17 @@ int32_t llama_esn_adapter::update(const llama_esn_online_params & p, int n_threa ensure_readout(); + bool ok = true; switch (p.update_mode) { - case 0: update_ridge(p.regularization, p.decay_rate, p.replay_window, temperature, n_threads); break; - case 1: update_rls (p.regularization, p.decay_rate, temperature); break; - case 2: update_sgd (p.learning_rate, p.regularization); break; + case 0: ok = update_ridge(p.regularization, p.decay_rate, p.replay_window, temperature, n_threads); break; + case 1: ok = update_rls (p.regularization, p.decay_rate, temperature); break; + case 2: update_sgd (p.learning_rate, p.regularization); break; + } + if (!ok) { + LLAMA_LOG_ERROR("%s: the %s solve is numerically singular at regularization %g; the readout and the " + "pending feedback are unchanged (raise the regularization)\n", __func__, + p.update_mode == 0 ? "ridge" : "RLS", p.regularization); + return -9; } last_mode = (int) p.update_mode; active = true; @@ -307,7 +339,7 @@ int32_t llama_esn_adapter::update(const llama_esn_online_params & p, int n_threa return consumed; } -void llama_esn_adapter::update_ridge(float lambda, float decay, uint32_t window, float temperature, int n_threads) { +bool llama_esn_adapter::update_ridge(float lambda, float decay, uint32_t window, float temperature, int n_threads) { // the newest `window` samples of history + pending std::vector set; for (const auto & s : history) { @@ -346,11 +378,17 @@ void llama_esn_adapter::update_ridge(float lambda, float decay, uint32_t window, } } for (int64_t j = 0; j < n; ++j) { - double d = G[j * n + j]; + const double diag = G[j * n + j]; + double d = diag; for (int64_t k = 0; k < j; ++k) { d -= G[j * n + k] * G[j * n + k]; } - GGML_ASSERT(d > 0.0); + // lambda > 0 makes G positive definite in exact arithmetic, but a + // lambda below the rounding of S S^T leaves a pivot that is only + // rounding noise: treat pivots under 1e-12 of their diagonal as zero + if (!(d > 1e-12 * diag) || !std::isfinite(d)) { + return false; + } d = std::sqrt(d); G[j * n + j] = d; for (int64_t i = j + 1; i < n; ++i) { @@ -394,11 +432,24 @@ void llama_esn_adapter::update_ridge(float lambda, float decay, uint32_t window, } } }); + return true; } -void llama_esn_adapter::update_rls(float lambda, float decay, float temperature) { +bool llama_esn_adapter::update_rls(float lambda, float decay, float temperature) { const int64_t R = n_res; + // restored if a step loses positive definiteness, so a failed update + // changes nothing + std::vector w_saved(w_data(), w_data() + (size_t) n_vocab * R); + std::vector p_saved = rls_p; + const float lambda_saved = rls_lambda; + const auto rollback = [&]() { + memcpy(w_data(), w_saved.data(), w_saved.size() * sizeof(float)); + rls_p = std::move(p_saved); + rls_lambda = lambda_saved; + return false; + }; + // P is the inverse of lambda I + sum w x x^T for samples since the last // restart; it restarts at I / lambda (a prior centered on the current // readout) when lambda changes or another mode moved the readout @@ -432,6 +483,10 @@ void llama_esn_adapter::update_rls(float lambda, float decay, float temperature) xg += acc * x[i]; } const double denom = f / s.weight + xg; + // P is positive definite, so xg >= 0; anything else is rounding loss + if (!(xg >= 0.0) || !std::isfinite(denom)) { + return rollback(); + } for (int64_t i = 0; i < R; ++i) { k[i] = (float) (g[i] / denom); } @@ -450,6 +505,7 @@ void llama_esn_adapter::update_rls(float lambda, float decay, float temperature) } } } + return true; } void llama_esn_adapter::update_sgd(float lr, float reg) { @@ -572,7 +628,10 @@ int32_t llama_esn_submit_feedback( if (const int32_t rc = llama_esn_check(ctx); rc != 0) { return rc; } - return ctx->get_esn()->submit(events, n_events); + const llama_memory_t mem = ctx->get_memory(); + return ctx->get_esn()->submit(events, n_events, [mem](llama_seq_id seq) { + return mem ? mem->seq_pos_max(seq) : (llama_pos) -1; + }); } int32_t llama_esn_update_readout( @@ -587,6 +646,11 @@ int32_t llama_esn_update_readout( if (params == nullptr) { return -3; } + if (params->enabled && ctx->lora_adapts_readout()) { + LLAMA_LOG_ERROR("%s: a LoRA adapter on this context modifies the readout; the adapted readout would " + "replace it, so remove the adapter (llama_rm_adapter_lora) before adapting\n", __func__); + return -10; + } // no graph may be reading the readout while it changes ctx->synchronize(); try { diff --git a/src/llama-esn.h b/src/llama-esn.h index 274ba82167dd..d6472428a4e2 100644 --- a/src/llama-esn.h +++ b/src/llama-esn.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -36,11 +37,16 @@ struct llama_esn_adapter { explicit llama_esn_adapter(const llama_model & model); ~llama_esn_adapter(); - // Record the readout inputs of one ubatch. `rows` holds n_outputs - // vectors of reservoir_size floats, in ubatch output order. + // Record the readout inputs of one ubatch, which is called for every + // ubatch, with or without outputs: each decoded position invalidates what + // was recorded at or after it. `rows` holds n_outputs vectors of + // reservoir_size floats, in ubatch output order. void capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows); - int32_t submit (const llama_esn_feedback_event * events, int32_t n_events); + // `pos_max(seq)` is the newest position the context's memory holds for + // seq; positions after it were cleared and cannot be trained on + int32_t submit(const llama_esn_feedback_event * events, int32_t n_events, + const std::function & pos_max); int32_t update (const llama_esn_online_params & params, int n_threads); void reset(); @@ -95,7 +101,8 @@ struct llama_esn_adapter { void ensure_readout(); float * w_data() const; - void update_ridge(float lambda, float decay, uint32_t window, float temperature, int n_threads); - void update_rls (float lambda, float decay, float temperature); + // false: the solve was numerically singular and nothing was changed + bool update_ridge(float lambda, float decay, uint32_t window, float temperature, int n_threads); + bool update_rls (float lambda, float decay, float temperature); void update_sgd (float lr, float reg); }; diff --git a/tests/test-esn-inference.cpp b/tests/test-esn-inference.cpp index b9d0874fd076..539591d5bf81 100644 --- a/tests/test-esn-inference.cpp +++ b/tests/test-esn-inference.cpp @@ -32,6 +32,7 @@ #endif #include "llama.h" +#include "ggml-backend.h" #include #include @@ -192,6 +193,7 @@ int main(int argc, char ** argv) { llama_log_set(silent_log, nullptr); llama_backend_init(); + ggml_backend_load_all(); llama_model_params mparams = llama_model_default_params(); mparams.use_mmap = false; diff --git a/tests/test-esn-online.cpp b/tests/test-esn-online.cpp index 93a86743a46a..9494d9a47bb1 100644 --- a/tests/test-esn-online.cpp +++ b/tests/test-esn-online.cpp @@ -31,6 +31,7 @@ #include "llama.h" #include "ggml.h" +#include "ggml-backend.h" #include "gguf.h" #include @@ -110,6 +111,31 @@ static void write_model(const std::string & path, bool online) { ggml_free(ctx); } +// A rank-1 LoRA on the readout. +static void write_readout_lora(const std::string & path) { + gguf_context * g = gguf_init_empty(); + gguf_set_val_str(g, "general.type", "adapter"); + gguf_set_val_str(g, "general.architecture", "esn"); + gguf_set_val_str(g, "adapter.type", "lora"); + gguf_set_val_f32(g, "adapter.lora.alpha", 1.0f); + + ggml_init_params ip = { 4 * ggml_tensor_overhead() + 4 * (N_RES + N_VOCAB) + 1024, nullptr, false }; + ggml_context * ctx = ggml_init(ip); + ggml_tensor * a = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, N_RES, 1); + ggml_tensor * b = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, N_VOCAB); + ggml_set_name(a, "esn_output_weights.weight.lora_a"); + ggml_set_name(b, "esn_output_weights.weight.lora_b"); + for (int64_t i = 0; i < ggml_nelements(a); ++i) { ((float *) a->data)[i] = 0.01f; } + for (int64_t i = 0; i < ggml_nelements(b); ++i) { ((float *) b->data)[i] = 0.01f * (float) (i % 7); } + gguf_add_tensor(g, a); + gguf_add_tensor(g, b); + + const bool ok = gguf_write_to_file(g, path.c_str(), false); + assert(ok); + gguf_free(g); + ggml_free(ctx); +} + static llama_context * make_ctx(llama_model * model) { llama_context_params cp = llama_context_default_params(); cp.n_ctx = 128; @@ -175,8 +201,12 @@ static float max_abs_diff(const std::vector & a, const std::vector } int main(int argc, char ** argv) { - llama_log_set(silent_log, nullptr); + if (getenv("ESN_TEST_LOG") == nullptr) { + llama_log_set(silent_log, nullptr); + } llama_backend_init(); + // a GGML_BACKEND_DL build registers no backend until it is loaded + ggml_backend_load_all(); const bool synthetic = argc < 2; const auto dir = std::filesystem::temp_directory_path(); @@ -383,6 +413,91 @@ int main(int argc, char ** argv) { printf(" H the feedback buffer is bounded: ok\n"); } + // I: recordings follow the sequence as it is rewound or cleared + llama_esn_reset_adaptation(ctx); + { + llama_esn_online_params p = mode_params(0); + decode_all(ctx, prompt); + + // a clear with nothing decoded after it: every position is gone + llama_memory_clear(llama_get_memory(ctx), true); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == -3); + + // re-decoded with an output only at the last position: the earlier + // positions were decoded again, so their old recordings are stale + llama_batch b = llama_batch_init((int32_t) prompt.size(), 0, 1); + for (size_t i = 0; i < prompt.size(); ++i) { + b.token[i] = prompt[prompt.size() - 1 - i]; + b.pos[i] = (llama_pos) i; + b.n_seq_id[i] = 1; + b.seq_id[i][0] = 0; + b.logits[i] = i + 1 == prompt.size(); + } + b.n_tokens = (int32_t) prompt.size(); + assert(llama_decode(ctx, b) == 0); + llama_batch_free(b); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == -3); + llama_esn_feedback_event last = event(LLAMA_ESN_FEEDBACK_CORRECTION, (llama_pos) prompt.size() - 1, &target); + assert(llama_esn_submit_feedback(ctx, &last, 1) == 0); + assert(llama_esn_update_readout(ctx, &p) == 1); + llama_esn_reset_adaptation(ctx); + printf(" I rewound and cleared positions cannot be trained on: ok\n"); + } + + // J: a singular solve fails without changing anything + { + decode_all(ctx, prompt); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + llama_esn_feedback_event twice[2] = { ev, ev }; + assert(llama_esn_submit_feedback(ctx, twice, 2) == 0); + for (uint32_t mode : { 0u, 1u }) { + // two identical samples: lambda below the rounding of |x|^2 leaves + // the second pivot at zero + llama_esn_online_params tiny = mode_params(mode, 0.0f, 1e-30f); + const int32_t rc = llama_esn_update_readout(ctx, &tiny); + assert(rc == -9 || (mode == 1 && rc == 2)); + if (rc == 2) { + // RLS stays stable here; start over for the ridge check + llama_esn_reset_adaptation(ctx); + assert(llama_esn_submit_feedback(ctx, twice, 2) == 0); + continue; + } + assert(max_abs_diff(decode_all(ctx, prompt)[at], base[at]) == 0.0f); + } + llama_esn_online_params p = mode_params(0, 0.0f, 1e-4f); + assert(llama_esn_update_readout(ctx, &p) == 2); // the samples were kept + llama_esn_reset_adaptation(ctx); + printf(" J a singular least-squares solve is refused and changes nothing: ok\n"); + } + + // K: a LoRA on the readout and an adapted readout exclude each other + if (synthetic) { + const std::string path_lora = (dir / "test-esn-online-lora.gguf").string(); + write_readout_lora(path_lora); + llama_adapter_lora * lora = llama_adapter_lora_init(model, path_lora.c_str()); + assert(lora != nullptr); + + decode_all(ctx, prompt); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + llama_esn_online_params p = mode_params(0); + assert(llama_set_adapter_lora(ctx, lora, 1.0f) == 0); + const auto with_lora = decode_all(ctx, prompt); + assert(max_abs_diff(with_lora[at], base[at]) > 0.0f); // the LoRA applies + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + assert(llama_esn_update_readout(ctx, &p) == -10); + assert(llama_rm_adapter_lora(ctx, lora) == 0); + assert(llama_esn_update_readout(ctx, &p) == 1); + assert(llama_set_adapter_lora(ctx, lora, 1.0f) == -1); // refused while adapted + llama_esn_reset_adaptation(ctx); + assert(llama_set_adapter_lora(ctx, lora, 1.0f) == 0); + assert(llama_rm_adapter_lora(ctx, lora) == 0); + + llama_adapter_lora_free(lora); + std::filesystem::remove(path_lora); + printf(" K a readout LoRA and online adaptation are mutually exclusive: ok\n"); + } + llama_free(ctx); llama_free(ctx2); llama_model_free(model); @@ -393,6 +508,6 @@ int main(int argc, char ** argv) { std::filesystem::remove(path_off); llama_backend_free(); - printf("test-esn-online: PASSED (A..H)\n"); + printf("test-esn-online: PASSED (A..K)\n"); return 0; } diff --git a/tests/test-esn-perplexity.cpp b/tests/test-esn-perplexity.cpp index 95851f7a5aa9..0fccc8677290 100644 --- a/tests/test-esn-perplexity.cpp +++ b/tests/test-esn-perplexity.cpp @@ -19,6 +19,7 @@ #endif #include "llama.h" +#include "ggml-backend.h" #include #include @@ -56,6 +57,7 @@ int main(int argc, char ** argv) { llama_log_set(silent_log, nullptr); llama_backend_init(); + ggml_backend_load_all(); llama_model_params mparams = llama_model_default_params(); mparams.use_mmap = false; From 80a067e8e06e99a26d0c1978cd90951768517895 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 18:40:52 +0000 Subject: [PATCH 08/10] ESN online: invalidate recordings on state restore; RLS objective; review Second round of review fixes for the llama_esn_* online readout API: - llama_memory_i gains seq_epoch(), which the recurrent memory advances whenever a sequence's content is replaced instead of extended or truncated: clear, seq_cp onto it, seq_add/seq_div, state restore. The ESN adapter tags recordings with it and refuses ones from an older epoch, so feedback after llama_state_set_data no longer trains on the vectors of the history that was replaced (test L). - Clearing an empty LoRA set, or re-setting an adapter at the same scale, no longer discards the reusable graph; the server clears adapters before every batch. - The documented RLS objective now states that forgetting decays the pull toward the checkpoint as well (exact for decay 0); a fixed anchor is what ridge provides. - esn_training.py rejects a --forgetting-factor whose decay rounds to 1 in float32, which the loader would refuse. - test-esn-online sizes its out-of-range token and logits copies by the loaded model's vocabulary, so it works on external models of any size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- docs/esn.md | 8 +++++--- include/llama.h | 6 ++++-- scripts/esn_training.py | 3 +++ src/llama-context.cpp | 11 +++++++++- src/llama-esn.cpp | 37 ++++++++++++++++++++++------------ src/llama-esn.h | 36 +++++++++++++++++++++------------ src/llama-memory-recurrent.cpp | 18 +++++++++++++++++ src/llama-memory-recurrent.h | 6 ++++++ src/llama-memory.h | 6 ++++++ tests/test-esn-online.cpp | 26 +++++++++++++++++++++--- 10 files changed, 122 insertions(+), 35 deletions(-) diff --git a/docs/esn.md b/docs/esn.md index 9b60aa2b478b..11685ef184f8 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -685,7 +685,7 @@ model, and every other context on it, keep the checkpoint. Updates: | Mode | Objective | Cost per update | |------|-----------|-----------------| | 0 ridge | `min Σ wᵢ‖T yᵢ − W xᵢ‖² + λ‖W − W₀‖²` over the newest `replay_window` samples, refit from W₀ (Woodbury: an n×n solve for n samples) | O(V·R·n + n³) | -| 1 RLS | the same objective, recursively from the current W with forgetting `1 − decay_rate`; keeps P = (λI + Σ w x xᵀ)⁻¹ | O(R² + V·R) per sample, R² doubles of memory | +| 1 RLS | recursively from the current W with forgetting f = `1 − decay_rate`: after k samples `min Σ f^(k−i) wᵢ‖T yᵢ − W xᵢ‖² + f^k λ‖W − W₀‖²`, keeping P = (f^k λI + Σ f^(k−i) w x xᵀ)⁻¹. With decay 0 it is ridge over every sample since the last restart; with decay > 0 the pull toward W₀ fades with the samples (use ridge for a fixed anchor) | O(R² + V·R) per sample, R² doubles of memory | | 2 SGD | one weighted cross-entropy step on softmax(W x) per sample, plus `regularization`·(W − W₀) | O(V·R) per sample | `T` is `esn.output_temperature`: `esn_training.py` fits `W_out` to one-hot @@ -703,7 +703,9 @@ The adapted readout is not included in `llama_state_*` data. Recordings follow the sequence: decoding a position again (after `llama_memory_seq_rm` or a memory clear) discards what was recorded at and after it, even when the new tokens produce no logits, and feedback is -refused (-3) for positions past the newest one the context's memory holds. +refused (-3) for positions past the newest one the context's memory holds, +and for anything recorded before the memory replaced the sequence's content +(`llama_state_*set_data`/`load_file`, `llama_memory_seq_cp` onto it). A batch of feedback that would overflow `esn.online_learning.buf_size` is refused (-5) before anything is copied. If a least-squares solve is numerically singular (λ below the rounding of `Σ w x xᵀ`), the update @@ -730,7 +732,7 @@ the rewind, singular-solve and LoRA rules. | Stable dynamics | Spectral radius validated to be in (0, 1) at load time | | Non-destructive | Only W_out is adapted; W_res, W_in are read-only | | Reversible | `llama_esn_reset_adaptation` returns a context to the checkpoint W_out | -| Regularized | Ridge and RLS are anchored to the checkpoint by λ‖W − W₀‖²; SGD optionally | +| Regularized | Ridge is anchored to the checkpoint by λ‖W − W₀‖²; RLS by the same term decayed by `(1 − decay_rate)^k` (fixed at decay 0); SGD optionally | ### Capability Matrix diff --git a/include/llama.h b/include/llama.h index 13f64a882748..01a2de84cda3 100644 --- a/include/llama.h +++ b/include/llama.h @@ -578,7 +578,8 @@ extern "C" { // Positions are tracked per sequence: decoding a position again (after // llama_memory_seq_rm or a memory clear) discards what was recorded at // and after it, and feedback is refused for positions past the newest one - // the context's memory holds. + // the context's memory holds or recorded before its content was replaced + // (state restore, llama_memory_seq_cp onto the sequence). // enum llama_esn_feedback_type { @@ -614,7 +615,8 @@ extern "C" { float regularization; // ridge/RLS: lambda > 0 (pull toward the checkpoint); // SGD: >= 0, L2 pull toward the checkpoint float decay_rate; // [0, 1): ridge down-weights a sample by (1 - decay)^age, - // RLS forgets with factor 1 - decay; unused by SGD + // RLS forgets samples and the pull toward the + // checkpoint alike by 1 - decay; unused by SGD uint32_t replay_window; // >= 1: samples kept for ridge, which refits from the // checkpoint on the newest replay_window samples each update bool freeze_reservoir; // must be true (-3 otherwise): only W_out is trained diff --git a/scripts/esn_training.py b/scripts/esn_training.py index ee9e46531dc7..047e99f77110 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -1248,6 +1248,9 @@ def main(): "(--train-data) or choose SGD (--online --online-mode sgd)") if not (0.0 < args.forgetting_factor <= 1.0): parser.error("--forgetting-factor must be in (0, 1]") + if args.save_online_metadata and not float(np.float32(1.0 - args.forgetting_factor)) < 1.0: + # exported as esn.online_learning.decay (f32), which must be < 1 + parser.error("--forgetting-factor is too small: 1 - forgetting_factor rounds to 1 in float32") if args.bidirectional: parser.error("--bidirectional is not supported: at position t the backward " "pass has already read token t+1, the readout's target, and " diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 310d25453b9c..01b4ae9fa8fd 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -725,6 +725,10 @@ bool llama_context::set_adapter_lora( return false; } + const auto it = loras.find(adapter); + if (it != loras.end() && it->second == scale) { + return true; + } loras[adapter] = scale; // graph reuse compares the adapter set by address only, so a graph built // before this change must not be reused @@ -753,6 +757,11 @@ bool llama_context::rm_adapter_lora( void llama_context::clear_adapter_lora() { LLAMA_LOG_DEBUG("%s: call\n", __func__); + // callers such as the server clear before every batch: only an actual + // change invalidates the graph + if (loras.empty()) { + return; + } loras.clear(); if (gf_res_prev) { gf_res_prev->reset(); @@ -1255,7 +1264,7 @@ int llama_context::decode(const llama_batch & batch_inp) { ggml_backend_tensor_get_async(backend_x, t_x, esn_rows.data(), 0, esn_rows.size()*sizeof(float)); ggml_backend_sched_synchronize(sched.get()); } - esn->capture(ubatch, n_outputs, esn_rows.data()); + esn->capture(ubatch, n_outputs, esn_rows.data(), memory.get()); } n_outputs_prev += n_outputs; diff --git a/src/llama-esn.cpp b/src/llama-esn.cpp index 70c855025329..872f8d8a0a0f 100644 --- a/src/llama-esn.cpp +++ b/src/llama-esn.cpp @@ -3,6 +3,7 @@ #include "llama-impl.h" #include "llama-batch.h" #include "llama-model.h" +#include "llama-memory.h" #include "ggml-backend.h" @@ -78,14 +79,23 @@ llama_esn_adapter::llama_esn_adapter(const llama_model & model) : llama_esn_adapter::~llama_esn_adapter() = default; -void llama_esn_adapter::capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows) { +void llama_esn_adapter::capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows, const llama_memory_i * mem) { uint32_t j = 0; for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { const bool is_output = n_outputs == ubatch.n_tokens || (n_outputs > 0 && ubatch.output[i]); const float * x = is_output ? rows + (size_t) j++ * n_res : nullptr; const llama_pos pos = ubatch.pos[i]; for (int32_t s = 0; s < ubatch.n_seq_id[i]; ++s) { - auto & q = recorded[ubatch.seq_id[i][s]]; + const llama_seq_id seq = ubatch.seq_id[i][s]; + auto & rec = recorded[seq]; + // the memory replaced this sequence's content (restored state, + // seq_cp onto it, ...): nothing recorded before belongs to it + const uint64_t epoch = mem ? mem->seq_epoch(seq) : 0; + if (rec.epoch != epoch) { + rec.q.clear(); + rec.epoch = epoch; + } + auto & q = rec.q; // decoding a position at or before the newest recorded one means // the sequence was rewound (seq_rm, memory clear): what was // recorded from there on belongs to tokens that are gone, whether @@ -105,19 +115,23 @@ void llama_esn_adapter::capture(const llama_ubatch & ubatch, uint32_t n_outputs, GGML_ASSERT(j == n_outputs); } -const llama_esn_adapter::captured * llama_esn_adapter::find(llama_seq_id seq, llama_pos pos) const { +const llama_esn_adapter::captured * llama_esn_adapter::find(llama_seq_id seq, llama_pos pos, const llama_memory_i * mem) const { + // positions past the memory's newest one were cleared, and recordings + // from before the memory replaced the sequence's content are stale + if (mem == nullptr || pos > mem->seq_pos_max(seq)) { + return nullptr; + } const auto it = recorded.find(seq); - if (it == recorded.end()) { + if (it == recorded.end() || it->second.epoch != mem->seq_epoch(seq)) { return nullptr; } - const auto & q = it->second; + const auto & q = it->second.q; const auto c = std::lower_bound(q.begin(), q.end(), pos, [](const captured & a, llama_pos p) { return a.pos < p; }); return c != q.end() && c->pos == pos ? &*c : nullptr; } -int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32_t n_events, - const std::function & pos_max) { +int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32_t n_events, const llama_memory_i * mem) { if (n_events < 0 || (n_events > 0 && events == nullptr)) { return -3; } @@ -167,10 +181,10 @@ int32_t llama_esn_adapter::submit(const llama_esn_feedback_event * events, int32 LLAMA_LOG_ERROR("%s: event %d: target token %d is out of range\n", __func__, e, tok); return -3; } - const captured * c = ev.pos + k <= pos_max(ev.seq_id) ? find(ev.seq_id, ev.pos + k) : nullptr; + const captured * c = find(ev.seq_id, ev.pos + k, mem); if (c == nullptr) { LLAMA_LOG_ERROR("%s: event %d: no readout input recorded for seq %d pos %d (the position " - "was not decoded with an output, was rewound or cleared, or is older than the last %zu)\n", + "was not decoded with an output, was rewound, cleared or replaced, or is older than the last %zu)\n", __func__, e, ev.seq_id, ev.pos + k, recorded_cap); return -3; } @@ -628,10 +642,7 @@ int32_t llama_esn_submit_feedback( if (const int32_t rc = llama_esn_check(ctx); rc != 0) { return rc; } - const llama_memory_t mem = ctx->get_memory(); - return ctx->get_esn()->submit(events, n_events, [mem](llama_seq_id seq) { - return mem ? mem->seq_pos_max(seq) : (llama_pos) -1; - }); + return ctx->get_esn()->submit(events, n_events, ctx->get_memory()); } int32_t llama_esn_update_readout( diff --git a/src/llama-esn.h b/src/llama-esn.h index d6472428a4e2..658bed739189 100644 --- a/src/llama-esn.h +++ b/src/llama-esn.h @@ -6,12 +6,12 @@ #include #include -#include #include #include struct llama_model; struct llama_ubatch; +struct llama_memory_i; // Online readout adaptation for an ESN context (the llama_esn_* API). // @@ -28,8 +28,12 @@ struct llama_ubatch; // 0 ridge: W = argmin sum_i w_i |T y_i - W x_i|^2 + lambda |W - W0|^2 // over the newest replay_window samples, solved from W0 each time // (Woodbury form, an n x n system for n samples) -// 1 RLS: the same objective solved recursively from the current W, with -// forgetting factor 1 - decay; P = (lambda I + sum w x x^T)^-1 +// 1 RLS: solved recursively from the current W with forgetting factor +// f = 1 - decay: after k samples, W = argmin sum_i f^(k-i) w_i +// |T y_i - W x_i|^2 + f^k lambda |W - W0|^2, with W0 the readout at +// the last restart; P = (f^k lambda I + sum f^(k-i) w x x^T)^-1. +// With decay = 0 this is ridge over every sample since the restart; +// with decay > 0 the pull toward W0 fades along with old samples // 2 SGD: one cross-entropy step per sample on softmax(W x), weighted by w // (negative w pushes probability away from the token), plus an L2 // pull toward W0 @@ -40,13 +44,14 @@ struct llama_esn_adapter { // Record the readout inputs of one ubatch, which is called for every // ubatch, with or without outputs: each decoded position invalidates what // was recorded at or after it. `rows` holds n_outputs vectors of - // reservoir_size floats, in ubatch output order. - void capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows); - - // `pos_max(seq)` is the newest position the context's memory holds for - // seq; positions after it were cleared and cannot be trained on - int32_t submit(const llama_esn_feedback_event * events, int32_t n_events, - const std::function & pos_max); + // reservoir_size floats, in ubatch output order. `mem` is the context's + // memory: a sequence whose content it has since replaced (seq_epoch) + // starts over. + void capture(const llama_ubatch & ubatch, uint32_t n_outputs, const float * rows, const llama_memory_i * mem); + + // Positions past the memory's newest one for the sequence, or recorded + // before its content was replaced, cannot be trained on. + int32_t submit(const llama_esn_feedback_event * events, int32_t n_events, const llama_memory_i * mem); int32_t update (const llama_esn_online_params & params, int n_threads); void reset(); @@ -72,8 +77,13 @@ struct llama_esn_adapter { const int64_t n_res; // reservoir size: readout input width const int64_t n_vocab; // readout output width - // recorded readout inputs per sequence, oldest first, ascending pos - std::map> recorded; + // recorded readout inputs per sequence, oldest first, ascending pos, + // valid for the memory's seq_epoch at the time + struct recording { + uint64_t epoch = 0; + std::deque q; + }; + std::map recorded; size_t recorded_cap; // per sequence std::vector pending; // submitted, not yet trained on @@ -96,7 +106,7 @@ struct llama_esn_adapter { float rls_lambda = 0.0f; int last_mode = -1; - const captured * find(llama_seq_id seq, llama_pos pos) const; + const captured * find(llama_seq_id seq, llama_pos pos, const llama_memory_i * mem) const; void ensure_readout(); float * w_data() const; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index e23e74982b27..35407821e6aa 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -127,6 +127,7 @@ void llama_memory_recurrent::clear(bool data) { head = 0; used = 0; + ++epoch_all; if (data) { for (auto & buf : bufs) { @@ -210,6 +211,8 @@ void llama_memory_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id return; } + ++epoch_seq[seq_id_dst]; + if (p0 < 0) { p0 = 0; } @@ -292,6 +295,8 @@ void llama_memory_recurrent::seq_add(llama_seq_id seq_id, llama_pos p0, llama_po return; } + ++epoch_seq[seq_id]; + // for Mamba-like or RWKV models, only the pos needs to be shifted if (0 <= seq_id && seq_id < (int64_t) size) { const int32_t tail_id = cells[seq_id].tail; @@ -322,6 +327,8 @@ void llama_memory_recurrent::seq_div(llama_seq_id seq_id, llama_pos p0, llama_po return; } + ++epoch_seq[seq_id]; + // for Mamba-like or RWKV models, only the pos needs to be changed if (0 <= seq_id && seq_id < (int64_t) size) { const int32_t tail_id = cells[seq_id].tail; @@ -334,6 +341,11 @@ void llama_memory_recurrent::seq_div(llama_seq_id seq_id, llama_pos p0, llama_po } } +uint64_t llama_memory_recurrent::seq_epoch(llama_seq_id seq_id) const { + const auto it = epoch_seq.find(seq_id); + return epoch_all + (it != epoch_seq.end() ? it->second : 0); +} + llama_pos llama_memory_recurrent::seq_pos_min(llama_seq_id seq_id) const { llama_pos result = std::numeric_limits::max(); @@ -734,6 +746,12 @@ void llama_memory_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { GGML_UNUSED(flags); + if (seq_id == -1) { + ++epoch_all; + } else { + ++epoch_seq[seq_id]; + } + uint32_t cell_count; io.read_to(&cell_count, sizeof(cell_count)); diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 077c6e3ce938..af462df9ec62 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -51,6 +51,8 @@ class llama_memory_recurrent : public llama_memory_i { llama_pos seq_pos_min(llama_seq_id seq_id) const override; llama_pos seq_pos_max(llama_seq_id seq_id) const override; + uint64_t seq_epoch(llama_seq_id seq_id) const override; + std::map memory_breakdown() const override; bool prepare(const std::vector & ubatches); @@ -109,6 +111,10 @@ class llama_memory_recurrent : public llama_memory_i { const uint32_t n_seq_max = 1; + // seq_epoch() is epoch_all + epoch_seq[seq_id]; both only grow + uint64_t epoch_all = 0; + std::map epoch_seq; + std::vector ctxs; std::vector bufs; diff --git a/src/llama-memory.h b/src/llama-memory.h index 4a157b91fdbd..a172778753f8 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -109,6 +109,12 @@ struct llama_memory_i { virtual llama_pos seq_pos_min(llama_seq_id seq_id) const = 0; virtual llama_pos seq_pos_max(llama_seq_id seq_id) const = 0; + // changes whenever the content of seq_id is replaced rather than extended + // or truncated (clear, seq_cp onto it, shifted positions, state restore), + // so that state keyed by (seq_id, pos) can detect that it is stale; + // 0 for memories that do not track it + virtual uint64_t seq_epoch(llama_seq_id /*seq_id*/) const { return 0; } + virtual std::map memory_breakdown() const = 0; // diff --git a/tests/test-esn-online.cpp b/tests/test-esn-online.cpp index 9494d9a47bb1..419d62b23201 100644 --- a/tests/test-esn-online.cpp +++ b/tests/test-esn-online.cpp @@ -232,6 +232,9 @@ int main(int argc, char ** argv) { printf("test-esn-online: %s\n", synthetic ? "synthetic model" : path_on.c_str()); + // the loaded model's vocabulary: an external model need not have 256 + const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + const std::vector prompt = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' }; const llama_pos at = 4; const llama_token target = 'z'; @@ -259,7 +262,7 @@ int main(int argc, char ** argv) { const auto base = decode_all(ctx, prompt); { - const llama_token bad = (llama_token) N_VOCAB; + const llama_token bad = (llama_token) n_vocab; llama_esn_feedback_event lat = event(LLAMA_ESN_FEEDBACK_LATENCY, at, &target, 12.0f); llama_esn_feedback_event oob = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &bad); llama_esn_feedback_event far = event(LLAMA_ESN_FEEDBACK_CORRECTION, (llama_pos) prompt.size(), &target); @@ -379,7 +382,7 @@ int main(int argc, char ** argv) { assert(llama_decode(ctx, llama_batch_get_one(&t, 1)) == 0); } const float * l = llama_get_logits_ith(ctx, -1); - last.assign(l, l + N_VOCAB); + last.assign(l, l + n_vocab); return last; }; const auto first = step_all(); @@ -445,6 +448,23 @@ int main(int argc, char ** argv) { printf(" I rewound and cleared positions cannot be trained on: ok\n"); } + // L: restoring a saved state replaces the sequence's history + { + decode_all(ctx, prompt); + std::vector saved(llama_state_get_size(ctx)); + assert(llama_state_get_data(ctx, saved.data(), saved.size()) == saved.size()); + + // a different history ending at the same position + std::vector other(prompt.rbegin(), prompt.rend()); + decode_all(ctx, other); + assert(llama_state_set_data(ctx, saved.data(), saved.size()) == saved.size()); + + // the recordings are other's, not the restored prompt's + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == -3); + printf(" L recordings do not survive a state restore: ok\n"); + } + // J: a singular solve fails without changing anything { decode_all(ctx, prompt); @@ -508,6 +528,6 @@ int main(int argc, char ** argv) { std::filesystem::remove(path_off); llama_backend_free(); - printf("test-esn-online: PASSED (A..K)\n"); + printf("test-esn-online: PASSED (A..L)\n"); return 0; } From 09ecb0e453b7772eb4fe0fbb6ea41f8aaa6d9513 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:01:16 +0000 Subject: [PATCH 09/10] Fix ESN split-input abort when the readout is offloaded (Vulkan CI) With weights on the CPU and op_offload moving large-batch ops to a GPU, the unrolled recurrence ended up split across backends and every per-step view became a separate split input, tripping GGML_ASSERT(n_inputs < GGML_SCHED_MAX_SPLIT_INPUTS). - Classify the recurrence tensors (W_in, W_res, feedback, biases, input table) as REPEATING on block 0 so they live with the recurrent state; GGUF names are unchanged. - Pin the input drive, the per-step ops and the output stacking to the backend that holds W_res, and only use set_rows stacking when that backend is the CPU. - ggml_backend_sched_reserve no longer resets the scheduler before splitting (as upstream), so assignments made while building the graph are honored when compute buffers are reserved. - test-esn-inference: ESN_TEST_LOG keeps logging on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- CLAUDE.md | 2 +- ggml/src/ggml-backend.cpp | 5 +- src/llama-arch.cpp | 27 ++++----- src/llama-model.cpp | 105 ++++++++++++++++++++++++----------- tests/test-esn-inference.cpp | 4 +- tests/test-esn.cpp | 18 +++--- 6 files changed, 102 insertions(+), 59 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e89e895ebbba..93d8eebc0333 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -106,7 +106,7 @@ assert(esn_arch == LLM_ARCH_ESN); // Test tensor info const llm_tensor_info & info = llm_tensor_info_for(LLM_TENSOR_ESN_INPUT_WEIGHTS); -assert(info.layer == LLM_TENSOR_LAYER_INPUT); +assert(info.layer == LLM_TENSOR_LAYER_REPEATING); ``` ## Training ESN Models diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index ff9135fe2d87..939b1102bcbf 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -1698,8 +1698,9 @@ bool ggml_backend_sched_reserve(ggml_backend_sched_t sched, struct ggml_cgraph * GGML_ASSERT(sched); GGML_ASSERT((int)sched->hash_set.size >= measure_graph->n_nodes + measure_graph->n_leafs); - ggml_backend_sched_reset(sched); - + // no reset here: it would discard the backend assignments the caller made + // with ggml_backend_sched_set_tensor_backend while building the graph, so + // the reserved splits would differ from the ones computed (as upstream) ggml_backend_sched_synchronize(sched); ggml_backend_sched_split_graph(sched, measure_graph); diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 5a779c539dec..c7b836d00072 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -2466,19 +2466,20 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, // ESN specific tensors. // - // ESN logically has exactly one reservoir "layer" and we address it as - // layers[0] in the C++ loader. The create_tensor() calls use tn(...) - // without a layer index, so these tensors must be classified as non- - // repeating (INPUT / OUTPUT) — otherwise the loader asserts - // "repeating layer tensor used without a layer number". Classifying them - // as INPUT also keeps the GGUF tensor names stable (no blk.N. prefix). - {LLM_TENSOR_ESN_INPUT_WEIGHTS, {LLM_TENSOR_LAYER_INPUT, GGML_OP_MUL_MAT}}, - {LLM_TENSOR_ESN_RESERVOIR_WEIGHTS, {LLM_TENSOR_LAYER_INPUT, GGML_OP_MUL_MAT}}, - {LLM_TENSOR_ESN_OUTPUT_WEIGHTS, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, - {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}}, + // ESN logically has exactly one reservoir "layer", addressed as layers[0] + // in the C++ loader. The tensors the recurrence reads are REPEATING so + // they are placed on layer 0's device with the recurrent state: every + // unrolled step multiplies by W_res and adds the input drive, and an + // operand on another backend would make each step a separate split + // input. create_tensor() passes block 0 for them; their GGUF names carry + // no block number (no blk.N. prefix), so the names stay as they were. + {LLM_TENSOR_ESN_INPUT_WEIGHTS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_ESN_RESERVOIR_WEIGHTS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_ESN_OUTPUT_WEIGHTS, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}}, + {LLM_TENSOR_ESN_INPUT_BIAS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, + {LLM_TENSOR_ESN_RESERVOIR_BIAS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, + {LLM_TENSOR_ESN_INPUT_TABLE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}}, }; LLM_KV::LLM_KV(llm_arch arch, const char * suffix) : arch(arch), suffix(suffix) {} diff --git a/src/llama-model.cpp b/src/llama-model.cpp index a4aedcda0ca0..df568974b6c8 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -6035,14 +6035,19 @@ bool llama_model::load_tensors(llama_model_loader & ml) { tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); // ESN uses a single "layer" to hold all the weight tensors. + // Everything the recurrence reads is a block-0 tensor so it + // lives on layer 0's device: the per-step W_res·x and the + // input drive it adds must share a backend, or each + // unrolled step becomes another split input. The names + // carry no block number; passing 0 only selects the device. layers.resize(1); // W_in: used as ggml_mul_mat(W_in, embd) where embd.ne[0]=n_embd. // So W_in.ne[0]=n_embd, W_in.ne[1]=reservoir_size. - layers[0].wq = create_tensor(tn(LLM_TENSOR_ESN_INPUT_WEIGHTS, "weight"), {n_embd, reservoir_size}, 0); + layers[0].wq = create_tensor(tn(LLM_TENSOR_ESN_INPUT_WEIGHTS, "weight", 0), {n_embd, reservoir_size}, 0); // W_res: square recurrent matrix. - layers[0].wk = create_tensor(tn(LLM_TENSOR_ESN_RESERVOIR_WEIGHTS, "weight"), {reservoir_size, reservoir_size}, 0); + layers[0].wk = create_tensor(tn(LLM_TENSOR_ESN_RESERVOIR_WEIGHTS, "weight", 0), {reservoir_size, reservoir_size}, 0); // RMS norm weights are per-feature along reservoir axis. output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {reservoir_size}, 0); @@ -6055,16 +6060,16 @@ bool llama_model::load_tensors(llama_model_loader & ml) { // Optional: W_fb. The fed-back output is the one-hot of // the input token, so W_fb·y is a row lookup like // tok_embd: ne[0]=reservoir_size, ne[1]=n_vocab. - layers[0].wv = create_tensor(tn(LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, "weight"), {reservoir_size, n_vocab}, TENSOR_NOT_REQUIRED); + layers[0].wv = create_tensor(tn(LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, "weight", 0), {reservoir_size, n_vocab}, TENSOR_NOT_REQUIRED); // 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); + layers[0].bq = create_tensor(tn(LLM_TENSOR_ESN_INPUT_BIAS, "weight", 0), {reservoir_size}, TENSOR_NOT_REQUIRED); + layers[0].bk = create_tensor(tn(LLM_TENSOR_ESN_RESERVOIR_BIAS, "weight", 0), {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); + layers[0].esn_input_table = create_tensor(tn(LLM_TENSOR_ESN_INPUT_TABLE, "weight", 0), {reservoir_size, n_vocab}, TENSOR_NOT_REQUIRED); } break; default: throw std::runtime_error("unknown architecture"); @@ -19481,33 +19486,58 @@ struct llm_build_esn : public llm_graph_context_mamba { // 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. + // The recurrence runs on one backend: the one holding W_res, which + // runs every step's W_res·x. Its other ops carry no weights, so the + // scheduler would place them by their neighbors: with a readout + // offloaded to another backend (op_offload, or the output layer on a + // GPU) the stacking ops follow it there, and every per-step state + // becomes a separate split input, of which a split may have at most + // GGML_SCHED_MAX_SPLIT_INPUTS. Pinning them keeps the loop on one + // backend, so only whole tensors cross into and out of it. + ggml_backend_t rec_backend = nullptr; + if (model.layers[0].wk->buffer) { + const ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(model.layers[0].wk->buffer); + for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { + ggml_backend_t b = ggml_backend_sched_get_backend(sched, i); + if (ggml_backend_supports_buft(b, buft)) { + rec_backend = b; + break; + } + } + } + std::vector pinned; + auto pin = [&](ggml_tensor * t) { + pinned.push_back(t); + return t; + }; + ggml_tensor * u = nullptr; if (model.layers[0].esn_input_table && res->t_tokens) { // {reservoir_size, n_vocab} rows -> {reservoir_size, n_tokens} - u = ggml_get_rows(ctx0, model.layers[0].esn_input_table, res->t_tokens); + u = pin(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); + u = pin(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); + u = pin(ggml_scale(ctx0, u, hparams.esn_input_scaling)); } if (model.layers[0].bq) { - u = ggml_add(ctx0, u, model.layers[0].bq); + u = pin(ggml_add(ctx0, u, model.layers[0].bq)); } if (model.layers[0].bk) { - u = ggml_add(ctx0, u, model.layers[0].bk); + u = pin(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); + ggml_tensor * fb = pin(ggml_get_rows(ctx0, model.layers[0].wv, res->t_tokens)); if (feedback_scaling != 1.0f) { - fb = ggml_scale(ctx0, fb, feedback_scaling); + fb = pin(ggml_scale(ctx0, fb, feedback_scaling)); } - u = ggml_add(ctx0, u, fb); + u = pin(ggml_add(ctx0, u, fb)); } } cb(u, "esn_input_proj", -1); @@ -19527,17 +19557,18 @@ struct llm_build_esn : public llm_graph_context_mamba { // vector per input token, laid out [reservoir_size, n_seq_tokens, // n_seqs] so it flattens in the order inp_out_ids indexes. // - // When the CPU is the only backend, each step's state is written into - // its row of `states` with ggml_set_rows: one row copy per step. Every - // write returns a view of the whole buffer that depends on the + // When the recurrence runs on the CPU, each step's state is written + // into its row of `states` with ggml_set_rows: one row copy per step. + // Every write returns a view of the whole buffer that depends on the // previous one, so reading the last sees them all. The row index is a - // per-step view of an input, though, and with another backend in the - // scheduler each such view becomes a separate split input; more than - // GGML_SCHED_MAX_SPLIT_INPUTS of them abort the graph. Then the steps - // are concatenated pairwise in a balanced tree instead (each copied - // log2(n) times), which keeps every operand on the backend that - // computed it. - const bool stack_rows = n_seq_tokens > 1 && ggml_backend_sched_get_n_backends(sched) == 1; + // per-step view of an input, which lives on the CPU: on any other + // backend each such view becomes a separate split input. There the + // steps are concatenated pairwise in a balanced tree instead (each + // copied log2(n) times), whose operands all stay on the recurrence's + // backend. + const bool rec_on_cpu = rec_backend == nullptr || + ggml_backend_dev_type(ggml_backend_get_device(rec_backend)) == GGML_BACKEND_DEVICE_TYPE_CPU; + const bool stack_rows = n_seq_tokens > 1 && rec_on_cpu; std::vector per_step; ggml_tensor * states = nullptr; ggml_tensor * steps = nullptr; @@ -19565,26 +19596,26 @@ struct llm_build_esn : public llm_graph_context_mamba { // W_res · x(t): [reservoir_size, reservoir_size] * [reservoir_size, n_seqs] // -> [reservoir_size, n_seqs] - ggml_tensor * rec = ggml_mul_mat(ctx0, model.layers[0].wk, state); + ggml_tensor * rec = pin(ggml_mul_mat(ctx0, model.layers[0].wk, state)); // Pre-activation = W_res·x + (W_in·u + W_fb·y + b) - ggml_tensor * pre = ggml_add(ctx0, rec, u_t); + ggml_tensor * pre = pin(ggml_add(ctx0, rec, u_t)); - ggml_tensor * activated = apply_esn_activation(pre, activation_type); + ggml_tensor * activated = pin(apply_esn_activation(pre, activation_type)); // Leaky integration (a no-op blend at leaking_rate == 1). if (leaking_rate == 1.0f) { state = activated; } else { - ggml_tensor * leaky_old = ggml_scale(ctx0, state, 1.0f - leaking_rate); - ggml_tensor * leaky_new = ggml_scale(ctx0, activated, leaking_rate); - state = ggml_add(ctx0, leaky_old, leaky_new); + ggml_tensor * leaky_old = pin(ggml_scale(ctx0, state, 1.0f - leaking_rate)); + ggml_tensor * leaky_new = pin(ggml_scale(ctx0, activated, leaking_rate)); + state = pin(ggml_add(ctx0, leaky_old, leaky_new)); } if (states) { - states = ggml_set_rows(ctx0, states, + states = pin(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))); + ggml_view_1d(ctx0, steps, 1, t * ggml_element_size(steps)))); } else if (n_seq_tokens > 1) { per_step.push_back(state); } @@ -19618,7 +19649,7 @@ struct llm_build_esn : public llm_graph_context_mamba { 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)); + next.push_back(pin(ggml_concat(ctx0, level[i], level[i + 1], 1))); } if (level.size() % 2 == 1) { next.push_back(level.back()); @@ -19629,6 +19660,14 @@ struct llm_build_esn : public llm_graph_context_mamba { } cb(cur, "esn_reservoir_seq", -1); + if (rec_backend) { + for (ggml_tensor * t : pinned) { + if (ggml_backend_supports_op(rec_backend, t)) { + ggml_backend_sched_set_tensor_backend(sched, t, rec_backend); + } + } + } + if (inp_out_ids) { cur = ggml_get_rows(ctx0, cur, inp_out_ids); } diff --git a/tests/test-esn-inference.cpp b/tests/test-esn-inference.cpp index 539591d5bf81..956e42fa02ec 100644 --- a/tests/test-esn-inference.cpp +++ b/tests/test-esn-inference.cpp @@ -191,7 +191,9 @@ int main(int argc, char ** argv) { const std::string model_path = argv[1]; fprintf(stderr, "test-esn-inference: using '%s'\n", model_path.c_str()); - llama_log_set(silent_log, nullptr); + if (getenv("ESN_TEST_LOG") == nullptr) { + llama_log_set(silent_log, nullptr); + } llama_backend_init(); ggml_backend_load_all(); diff --git a/tests/test-esn.cpp b/tests/test-esn.cpp index 6a08e3fa0de1..cf2a6b20c13d 100644 --- a/tests/test-esn.cpp +++ b/tests/test-esn.cpp @@ -58,14 +58,14 @@ int main() { { std::cout << "Test 3: ESN tensor info mappings... "; const llm_tensor_info & input_info = llm_tensor_info_for(LLM_TENSOR_ESN_INPUT_WEIGHTS); - assert(input_info.layer == LLM_TENSOR_LAYER_INPUT); + assert(input_info.layer == LLM_TENSOR_LAYER_REPEATING); assert(input_info.op == GGML_OP_MUL_MAT); - // ESN has exactly one reservoir layer and is addressed as layers[0], - // so reservoir tensors are classified as non-repeating INPUT (otherwise - // the loader asserts "repeating layer tensor used without a layer number"). + // ESN has exactly one reservoir layer, addressed as layers[0]: the + // tensors the recurrence reads are REPEATING (created with block 0) so + // they share layer 0's device with the recurrent state. const llm_tensor_info & reservoir_info = llm_tensor_info_for(LLM_TENSOR_ESN_RESERVOIR_WEIGHTS); - assert(reservoir_info.layer == LLM_TENSOR_LAYER_INPUT); + assert(reservoir_info.layer == LLM_TENSOR_LAYER_REPEATING); assert(reservoir_info.op == GGML_OP_MUL_MAT); const llm_tensor_info & output_info = llm_tensor_info_for(LLM_TENSOR_ESN_OUTPUT_WEIGHTS); assert(output_info.layer == LLM_TENSOR_LAYER_OUTPUT); @@ -73,16 +73,16 @@ int main() { // Optional tensor infos const llm_tensor_info & fb_info = llm_tensor_info_for(LLM_TENSOR_ESN_FEEDBACK_WEIGHTS); - assert(fb_info.layer == LLM_TENSOR_LAYER_INPUT); + assert(fb_info.layer == LLM_TENSOR_LAYER_REPEATING); assert(fb_info.op == GGML_OP_GET_ROWS); // row per fed-back token const llm_tensor_info & ib_info = llm_tensor_info_for(LLM_TENSOR_ESN_INPUT_BIAS); - assert(ib_info.layer == LLM_TENSOR_LAYER_INPUT); + assert(ib_info.layer == LLM_TENSOR_LAYER_REPEATING); assert(ib_info.op == GGML_OP_ADD); 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.layer == LLM_TENSOR_LAYER_REPEATING); 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.layer == LLM_TENSOR_LAYER_REPEATING); assert(it_info.op == GGML_OP_GET_ROWS); // row per input token std::cout << "PASSED\n"; } From dd5084981c19485a490ca2181c9ca5949c3c0e8d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:53:20 +0000 Subject: [PATCH 10/10] test-esn-online: compare step G against a one-token baseline Test G checked that after reset_adaptation, decoding the prompt one token at a time reproduces base[at], which came from decoding the whole prompt in one batch. On a GPU backend the two graph shapes can use different matmul kernels, so the logits differ by rounding: the ubuntu-24-cmake-vulkan job failed on that 1e-5 bound. Take the unadapted baseline with the same one-token stepping, compare the reset result against it at 1e-5, and keep a 1e-3 sanity bound between the batched and stepped logits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav --- tests/test-esn-online.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/test-esn-online.cpp b/tests/test-esn-online.cpp index 419d62b23201..a9393deb16a8 100644 --- a/tests/test-esn-online.cpp +++ b/tests/test-esn-online.cpp @@ -367,12 +367,6 @@ int main(int argc, char ** argv) { // G: in-place readout updates under graph reuse { - decode_all(ctx, prompt); - llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); - assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); - llama_esn_online_params p = mode_params(2, 0.02f, 0.0f); - assert(llama_esn_update_readout(ctx, &p) == 1); - // one token at a time from pos 0: same-shaped graphs, reused auto step_all = [&]() { llama_memory_clear(llama_get_memory(ctx), true); @@ -385,6 +379,17 @@ int main(int argc, char ** argv) { last.assign(l, l + n_vocab); return last; }; + // the unadapted baseline for this path: a GPU backend may pick + // different kernels for the one-token and the whole-prompt graphs, + // so base[at] can differ from it by rounding + const auto pristine = step_all(); + + decode_all(ctx, prompt); + llama_esn_feedback_event ev = event(LLAMA_ESN_FEEDBACK_CORRECTION, at, &target); + assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); + llama_esn_online_params p = mode_params(2, 0.02f, 0.0f); + assert(llama_esn_update_readout(ctx, &p) == 1); + const auto first = step_all(); assert(llama_esn_submit_feedback(ctx, &ev, 1) == 0); assert(llama_esn_update_readout(ctx, &p) == 1); @@ -395,7 +400,8 @@ int main(int argc, char ** argv) { } assert(prob(second, target) > prob(first, target)); llama_esn_reset_adaptation(ctx); - assert(max_abs_diff(step_all(), base[at]) < 1e-5f); + assert(max_abs_diff(step_all(), pristine) < 1e-5f); + assert(max_abs_diff(pristine, base[at]) < 1e-3f); printf(" G updates apply to reused graphs: ok\n"); }