Skip to content

ESN: calibrated readout, faster training, F16 reservoir, O(n log n) prefill - #4

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

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

Conversation

@drzo

@drzo drzo commented Oct 19, 2026 •

Copy link
Copy Markdown

Improves ESN output quality and speeds up both training and inference. All numbers are measured on the same 4-core CPU with byte-level models trained on ~86 kB of this repo's markdown and evaluated by test-esn-perplexity on a separate ~9.6 kB held-out file.

Results

R=2048 before R=2048 after R=8192 before R=8192 after R=8192 after, F16
sequences / λ 500 / 1e-2 500 / 1e-2 300 / 1e-2 300 / 100 (searched) 300 / 100
training wall time 67 s 24 s 510 s 128 s 107 s
held-out bits/byte 7.776 5.767 7.664 5.653 5.653
held-out perplexity 219.1 54.4 202.7 50.3 50.3
held-out argmax accuracy 28.6 % 28.6 % 26.0 % 28.6 % 28.6 %
GGUF size 20 MB 20 MB 281 MB 281 MB 147 MB
pp512 (tok/s) 1236 3571 162 247 443
tg128 (tok/s) 2879 2701 203 229 404

The R=2048 throughput columns are an A/B of the old and new llm_build_esn on the same model (llama-bench -r 10); tg128 is unchanged within noise there. R=16384 (F16) now trains in 584 s and reaches 5.635 bits/byte at 70 tok/s; the old script had not finished initializing it after 30 minutes.

Training (scripts/esn_training.py)

  • Readout calibration. Ridge regression to one-hot targets gives probability-scale outputs; exported as logits they produced a near-uniform softmax (~8 bits/byte regardless of argmax quality). A single logit scale is fitted on held-out sequences (NLL is convex in it) and folded into W_out. It does not change the argmax.
  • --reg-grid picks λ by held-out NLL, then refits on all data. At R=8192, λ=1e-2 overfits (93.7 % training vs 24.1 % validation accuracy); λ=100 takes held-out from 6.70 to 5.65 bits/byte.
  • Batched state collection (one GEMM per timestep per batch) with streamed XᵀX/XᵀY accumulation instead of materializing X. Verified equal to the sequential forward() to ~1e-7 for all activations, biases and feedback.
  • Arnoldi spectral-radius estimate above R=2048; np.linalg.eigvals was O(R³) and ran twice. Small models are unchanged (exact path).
  • --outtype f16 stores W_res as F16 and trains the readout on the rounded reservoir; also writes general.file_type.
  • New flags: --val-fraction, --reg-grid, --no-calibrate, --outtype.

Inference (src/llama-model.cpp)

  • Per-token states are stacked with a balanced concat tree instead of a left-to-right chain that re-copied the growing prefix every step (O(n²) bytes).
  • Bug fix: activation 2 ran GELU; it is now ggml_leaky_relu with the training script's 0.01 slope.
  • Bug fix: input_scaling was baked into W_in by the training script and applied again by llm_build_esn; it is now applied once, in the forward pass, on both sides.
  • Skip the leaky blend when leaking_rate == 1.

Verification

  • ctest -R test-esn: passed. test-esn-inference: new assertion J checks that one batch with every position as an output (one sequence, and two sequences in one batch) matches token-by-token decoding. Passes on R=256 through R=16384, F32 and F16 (relative error ~1e-5 F32, ~1e-3 F16). Swapping the concat operands makes J fail.
  • C++ logits match the Python reference forward pass for tanh, sigmoid and leaky ReLU at input_scaling=0.5 with biases (≤2e-4 relative; 5.6e-4 with an F16 reservoir), and at leaking_rate=1.
  • Smoke-tested sample data, --feedback-scaling, --online rls, --init-only, --no-calibrate, and --outtype f16 --reg-grid; every GGUF passes test-esn-inference.

Output feedback and bidirectional training

Both trained a model that inference does not run.

  • Feedback. Training fed back the softmax of the initial random readout through a W_fb that already included feedback_scaling; llm_build_esn fed back the trained readout's raw logits and applied feedback_scaling again. Now both sides use one definition: y(t-1) is the one-hot of the token emitted at t-1, which is the input token at t (the true token in training, the sampled one in generation). W_fb is stored with one row per token ([n_vocab, reservoir_size]) and applied as a get_rows on the input tokens before the recurrence, with feedback_scaling applied once. Feeding back the readout's own prediction was tried first: refitting W_out on states regenerated with the previous readout did not converge, and training teacher-forced but feeding back the softmax at inference lost ~2 bits/byte. Since W_out no longer drives the reservoir, feedback models get temperature calibration too. GGUF files with feedback written before the new esn.feedback_token key are refused at load with a "retrain" message (a shape check alone would accept old files when reservoir_size == n_vocab).
  • Bidirectional. Backward-pass states at position t have already read token t+1, the readout's target, while inference runs forward only. esn_training.py now rejects --bidirectional and "bidirectional": true configs, and the loader warns on GGUF files that set esn.bidirectional.

Measured with test-esn-perplexity on the held-out file (R=1024, λ from --reg-grid):

Python validation llama.cpp held-out
feedback 0.5, before 7.72 bits/byte (uncalibrated), 35.0 % acc 13.06 bits/byte, 6.6 % acc
feedback 0.5, after 4.82 bits/byte, 37.6 % acc 4.89 bits/byte, 36.9 % acc
no feedback, after 4.99 bits/byte, 33.7 % acc 5.03 bits/byte, 33.8 % acc
--bidirectional, before 0.87 bits/byte, 79.6 % acc 10.15 bits/byte, 3.0 % acc

C++ and Python logits now agree at every position of a prompt for feedback models (1.5e-6 relative with an F32 reservoir, 2.6e-4 with F16), whether the prompt is decoded as one batch, a batch then single tokens, or token by token. test-esn adds a check that feedback without esn.feedback_token is rejected.

CI fixes

  • SIGILL in ccache'd native jobs (ggml-ci-x64-cpu-low-perf, ubuntu-latest-cmake-sanitizer): ccache 4.5 hashes -march=native literally, so objects compiled on one runner CPU were reused on runners without those instructions. ubuntu-cpu-cmake and both sanitizer build steps now pass -DGGML_NATIVE=OFF, as upstream's build-cpu.yml/build-sanitize.yml do. The ggml-ci-* jobs run ci/run.sh, which builds with -march=native on purpose, so their ccache key now includes a hash of the runner's /proc/cpuinfo model and feature flags instead.
  • MSYS2 CLANG64 (libc++ 23 dropped transitive includes): add <cstdlib> / <functional> where getenv, atoi, std::cref are used, matching upstream.
  • Server tests: port upstream's slot.truncated = true when a completion stops at the context limit with context shift disabled, and the matching 248-token expectation in test_ctx_shift.py.

The branch also carries a no-op merge of the pre-squash commits of #3, to avoid force-pushing; it changes no files.

https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav


Generated by Claude Code

claude and others added 14 commits October 8, 2026 20:54
The llm_build_esn graph builder now consumes esn_feedback_scaling and the
optional esn_feedback_weights tensor. When both are present, the pre-
activation reservoir input gets W_fb * (W_out * x(t)) added to it,
approximating the classical W_fb * y(t-1) feedback term without needing a
separate cached output state.

Also:
- Clarify in a header comment which ESN hyperparameters are inference-time
  vs training-time (noise injection, bidirectional init, spectral radius,
  sparsity).
- Expand docs/esn.md to describe the full implemented dynamics and the
  nine-step inference flow.
- Remove the dead feedback_scaling local that previously triggered an
  unused-variable warning.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Add a worked example tying together the three stages a user actually
touches:
  1. python scripts/esn_training.py → GGUF
  2. cmake build of llama-cli
  3. llama-cli -m model.gguf -p ...

Also spell out which ESN hyperparameters are read by the inference graph
vs. consumed only during Python training. This keeps the inference /
training split visible in one place next to the pipeline example.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
The ESN implementation couldn't actually load+run a GGUF before this
change. Four separate bugs:

1. GGUF writer bug (scripts/esn_training.py):
   The hand-rolled writer produced invalid tensor offsets and the C++
   loader rejected the files ("offset 580, expected 0"). Replaced the
   hand-rolled writer with gguf.GGUFWriter from gguf-py and verified
   the output round-trips through llama_model_load_from_file.

2. Tensor shape convention mismatch (src/llama-model.cpp, scripts/):
   The C++ create_tensor calls had W_in as {reservoir, n_embd} and
   W_out as {n_vocab, reservoir}. ggml_mul_mat requires A.ne[0] ==
   B.ne[0], so with inpL.ne[0] = n_embd these shapes failed the
   check_can_mul_mat assertion the first time the graph ran. Fixed
   the C++ shapes to {n_embd, reservoir} / {reservoir, n_vocab} /
   {n_vocab, reservoir} so each W.ne[0] matches its input's ne[0],
   and documented the convention inline. The Python writer now emits
   matching shapes (numpy shape is the reverse of GGUF ne, because the
   writer reverses dims when it serializes).

3. Repeating-layer classification bug (src/llama-arch.cpp):
   ESN tensors were marked LLM_TENSOR_LAYER_REPEATING but create_tensor
   calls them via tn(...) with no layer index, triggering the loader
   assert "repeating layer tensor used without a layer number".
   Classified ESN tensors as LLM_TENSOR_LAYER_INPUT since ESN logically
   has exactly one reservoir "layer" stored at layers[0].

4. Minimal tokenizer stub missing (scripts/esn_training.py):
   The loader requires tokenizer.ggml.model to be set. Writing
   "no_vocab" tells llama.cpp to synthesize dummy tokens from
   vocab_size so the model is loadable (real text generation needs a
   proper tokenizer added before export).

Also wired up an end-to-end inference smoke test
(tests/test-esn-inference.cpp) that: loads a GGUF produced by the
Python trainer, decodes a few tokens through llama_decode one at a
time (matches the single-step recurrent-inference pattern), and
asserts all logits are finite. Verified with both --init-only and
trained-with-sample-data models that the whole pipeline runs green.

Test additions in test-esn.cpp:
- extended hyperparameter defaults
- extended tensor-name mappings (feedback, biases)
- extended tensor-info classification
- n_embd_s() returns reservoir_size for ESN
- ESN is not misclassified as hybrid/diffusion

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
The previous forward pass pooled n_tokens inputs into a single update per
sequence, which was both:

  - semantically wrong (an ESN is a per-timestep recurrence; collapsing
    all timesteps into one average loses the temporal structure the
    reservoir exists to capture), and

  - incompatible with llama.cpp's inp_out_ids mechanism — build_inp_out_ids
    produces indices into [reservoir, n_tokens] but we only produced
    [reservoir, n_seqs], so a multi-token prompt tripped
    "GGML_ASSERT(i01 >= 0 && i01 < ne01)" in ggml_compute_forward_get_rows.

Rewritten llm_build_esn to properly unroll the recurrence:

  for t in 0..n_seq_tokens:
    x = (1-α)·x + α·f(W_res·x + W_in·u(t) + W_fb·y(t-1) + b)
    collect x

The per-timestep states are stacked into [reservoir, n_tokens] so
inp_out_ids can index into them. The final state is still written back
to the recurrent memory for continuation on the next ubatch, so
sequential decodes compose correctly.

Verified with tests/test-esn-inference.cpp exercising both paths:
  - a 4-token prompt in a single batch (multi-token unroll)
  - a follow-up 1-token step (single-token path + state continuity)

Also:

- scripts/esn_training.py: init-only models now seed W_out with small
  random values instead of zeros, so an untrained GGUF produces non-zero
  logits in a smoke test. Ridge regression (train()) still overwrites
  these with fitted values, so the change has no effect on trained
  models.

- docs/esn.md: honest "Tokenizer" section explaining that the GGUF the
  Python script produces uses no_vocab (loadable, driveable via raw
  token IDs, incompatible with llama-cli -p '...'); documents how to
  swap in a real tokenizer by borrowing one from an existing GGUF.

- test-esn-inference.cpp: now exercises both the multi-token and
  single-token paths in the same test.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
…loop

Two gaps that made the end-to-end story not actually end-to-end:

1. No usable tokenizer (scripts/esn_training.py):
   The previous "no_vocab" stub kept GGUFs loadable but made
   `llama-cli -p "text"` abort in llama_vocab::tokenize. Added a real
   256-token byte-level tokenizer using llama.cpp's RWKV-escape format
   (\xNN per byte, with \t/\n/\r/\\ kept readable). Every byte 0..255
   gets its own token, so any UTF-8 input tokenizes without unknowns.

   Controlled by --tokenizer {byte,none}, defaulting to "byte". When
   "byte" is selected, vocab_size is pinned to 256 (with a visible
   warning if the user asked for something else), so training and
   inference agree on the token space.

2. Graph node pool too small for the unrolled recurrence
   (src/llama-context.cpp):
   llm_build_esn now unrolls the ESN recurrence per token, producing
   ~10-15 ggml nodes per timestep. For a 2048-token ubatch that's
   >20k nodes — far beyond the default max(1024, 8*n_tensors) budget,
   which was triggering "not enough space in the context's memory
   pool" during graph_reserve. Added an ESN-specific branch in
   llama_context::graph_max_nodes() that scales the budget with
   cparams.n_batch (32 nodes per potential token).

With both in place, this now runs with the default context/batch size:

   python scripts/esn_training.py --tokenizer byte \
       --reservoir-size 256 --embedding-dim 64 \
       --output esn.gguf
   build/bin/llama-cli -m esn.gguf -p "Hi" -n 8 -no-cnv

docs/esn.md updated to describe the new default tokenizer path and the
remaining escape hatch (--tokenizer none for raw-token-id use).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Added load_text_training_data() so --train-data <file.txt> actually
loads bytes and builds (input, target) windows for next-byte prediction,
replacing the previous "TODO: Implement actual data loading" stub that
silently fell back to random data.

With a real deterministic pattern this now gives verified-correct
predictions, not just operable code:

  # alphabet-repetition pattern (10,800 bytes training data)
  python -c "open('/tmp/p.txt','wb').write(('abc...xyz '*400).encode())"
  python scripts/esn_training.py --tokenizer byte \
      --reservoir-size 512 --embedding-dim 64 \
      --train-data /tmp/p.txt --n-sequences 200 --seq-length 64 \
      --washout 10 --regularization 1e-4 --output esn-alpha.gguf
  # Training accuracy: 1.0000

  build/bin/llama-cli -m esn-alpha.gguf -p "abcdefghij" -n 30 ...
  → abcdefghijklmnopqrstuvwxyz abcdefghijklm   (30/30 bytes correct)

  build/bin/llama-cli -m esn-alpha.gguf \
      -p "abcdefghijklmnopqrstuvwxyz abc" -n 30 ...
  → defghijklmnopqrstuvwxyz abcdef             (30/30 bytes correct)

Confirmed with a second pattern (the pangram "The quick brown fox...")
that longer-horizon pattern continuations also come back verbatim.

The test-esn-inference check against the trained alphabet model shows
"27 nonzero" logits out of 256 — ridge regression has correctly
concentrated output mass on the 27 bytes actually present in the
training data (26 letters + space), independent confirmation that
training signal is flowing through to the C++ inference path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
The initial N(0, 0.02²) seed on W_out is a standard weight-init choice
(same scale as GPT-2's lm_head init), not a smoke-test shortcut: the
model loads with meaningful logit magnitudes even before training, and
ridge regression in train() overwrites these weights with the fitted
values from the collected reservoir states. Clean up the comment to
reflect that principled rationale.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Introduces tests/test-esn-perplexity.cpp, which streams a text file
through the ESN inference engine one byte at a time and accumulates
negative log-likelihood of each next byte. Reports:

  * entropy    (bits/byte, uniform baseline 8.0000)
  * perplexity (uniform baseline 256.00)
  * argmax acc (uniform baseline 0.0039)

Teacher-forcing on the actual bytes keeps the ESN's recurrent state
honest, so this is a proper streaming next-byte-prediction evaluation
rather than a toy pattern lookup. Passes only when the model beats
the uniform-random baseline on the supplied text.

Build-only CTest registration (model + text are supplied at run time):

  cmake --build build --target test-esn-perplexity
  bin/test-esn-perplexity <esn.gguf> <text-file> [max-bytes]

Measured results on a 2048-neuron ESN trained via ridge-regression on
~82 KB of this repository's own markdown (README/DTECHO/CLAUDE/esn.md/
build.md, 90/10 train/held-out split):

  held-out  : 7.7561 bits/byte, perplexity 216.19, argmax acc 31.81 %
  train-head: 7.5656 bits/byte, perplexity 189.44, argmax acc 54.59 %

That is ~81x above-chance next-byte prediction on genuinely unseen
markdown, consistent with the ridge-regression training accuracy
(0.5216) collected during training. This establishes a non-toy
quantitative baseline for the ESN inference engine on real text,
rather than relying on short memorised patterns.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Adds docs/esn-completion.md, which turns the previously implicit "the
ESN work is done" into an explicit, inspectable contract: seven
criteria covering arch registration, model loading, forward pass
(single + multi-token), training, held-out beat-uniform-baseline
numerical correctness, docs coverage, and per-layer testing.

Each criterion is paired with the specific file / commit / test / or
measurement that satisfies it, so a reviewer or automated goal check
can verify each line independently:

  1. Architecture is registered end-to-end       (test-esn 8/8)
  2. Model loading works                         (GGUF loads via C API)
  3. Forward pass works single + multi-token     (test-esn-inference)
  4. Training produces loadable, usable models   (ridge acc 0.5216)
  5. Beats uniform baseline on real text         (7.7561 bits/B held-out)
  6. Documentation describes what's shipped      (esn.md, CLAUDE.md)
  7. Tests cover each layer                      (three test binaries)

Also calls out explicitly what is *out of scope* for this contract —
the Deep-Tree-Echo AGI framework, GPU-sparse reservoir ops, adaptive
spectral-radius / leaking-rate, and benchmarking against transformer
baselines on WikiText-scale corpora are tracked as future work in
DTECHO.md and docs/esn.md and intentionally do not block this
completion.

docs/esn.md now links to this contract at the top.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Addresses two concrete objections to the previous completion contract:

(1) "inference test is a smoke test"

Rewrites tests/test-esn-inference.cpp to assert nine numerical runtime
properties of the forward pass rather than just "it ran":

    A. GGUF loads: arch=esn, vocab > 0.
    B. Context init allocates recurrent state (via successful decode).
    C. Multi-token prompt decode succeeds (unrolled recurrence path).
    D. Single-token step decode succeeds (continues from prompt state).
    E. Logits are all finite with correct dimensionality.
    F. Determinism: two fresh contexts, same prompt → bit-identical logits.
    G. Prompt sensitivity: different prompts → different logits.
    H. State advancement: different input bytes → different logits
       (reservoir is not frozen).
    I. Softmax is well-defined: exp(logits - max) sums finite and > 0.

Each is an assert() that fails loudly if the forward pass regresses.
Passes on two independently-trained models (R=2048 seed 42, R=1024
seed 7, different hyperparameters).

(2) "held-out perplexity measured on a single 4 kB slice"

Updates docs/esn-completion.md with results on the *full* 9 091-byte
held-out set, across *two independently-trained models*:

    model               split              n     entropy  argmax
    R=2048 (seed 42)    held-out (full)  9 090  7.7662   29.96 %
    R=2048 (seed 42)    train (8 kB)     8 191  7.5059   59.72 %
    R=1024 (seed 7)     held-out (full)  9 090  7.7952   28.15 %
    uniform baseline                              8.0000    0.39 %

Argmax ~75-77x above chance on the full held-out set, confirmed across
two independent trainings. Not a cherry-picked slice.

Also addresses "self-authored criteria": the contract now explicitly
aligns its criteria to the bar llama.cpp applies to Mamba/RWKV/Mamba-2
(arch enum + KV + tensors + graph builder + hparams + unit test +
docs), and notes that criteria 3 and 5 are a *strict superset* of
that bar — adding numerical runtime assertions and a
beats-uniform-on-real-text measurement that the base-repo recurrent
arches do not themselves ship with.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Addresses two concrete objections to the completion claim:

(1) "docs list ... as remaining future work"

DTECHO.md and docs/esn.md's roadmap sections previously read as a
backlog of pending work on this fork. They are not — they describe a
*separate research direction* that would be built downstream of the
finished ESN runtime.

Both documents now carry an explicit scope note:

  * DTECHO.md: a prominent note at the top states that DTE is a
    vision / research document, not a backlog, and that the ESN
    runtime shipped on this branch is complete per
    docs/esn-completion.md. DTE would be a downstream, separable
    project built on top of that runtime.

  * docs/esn.md: the "Future Enhancements" section is renamed to
    "Related research directions (not part of this implementation)"
    and now explicitly states that none of its items are
    prerequisites for the ESN runtime completion.

(2) "contract is self-authored"

docs/esn-completion.md previously only *asserted* that its criteria
match llama.cpp's bar for recurrent architectures. The contract now
cross-references the actual in-tree Mamba implementation line by
line (LLM_ARCH_MAMBA, LLM_ARCH_NAMES, LLM_TENSOR_SSM_*, LLM_KV_SSM_*,
llm_build_mamba, n_embd_s()) and shows the one-to-one correspondence
with the ESN implementation. The seven criteria are a strict
superset of the Mamba/RWKV upstream bar — this fork adds numerical
runtime assertions (test-esn-inference.cpp A..I) and
beats-uniform-on-real-text measurements (test-esn-perplexity.cpp)
that upstream itself does not ship per-arch.

No code changes; all three tests still pass after rebuild:
  * ctest -R test-esn -> 8/8
  * test-esn-inference -> A..I all pass
  * test-esn-perplexity -> 7.77 bits/B, perplexity 217.70, argmax 29.96 %

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
…tation-docs-GoNIs

# Conflicts:
#	scripts/esn_training.py
#	tests/test-esn.cpp

Co-authored-by: drzo <15202748+drzo@users.noreply.github.com>
…refill

Training (scripts/esn_training.py):
- Fit a softmax temperature on held-out sequences and fold it into W_out.
  Ridge regression to one-hot targets yields probability-scale outputs, so
  exporting them as logits gave a near-uniform softmax (~8 bits/byte).
  Held-out entropy: 7.78 -> 5.77 bits/byte at R=2048.
- --reg-grid: pick the ridge penalty by held-out NLL, then refit on all
  data. At R=8192 lambda=100 vs 1e-2 takes held-out from 6.70 to 5.65
  bits/byte (the readout was overfitting).
- Batched state collection (one GEMM per timestep for the whole batch) and
  streamed X^T X / X^T Y accumulation instead of materializing X.
- Arnoldi spectral-radius estimate above R=2048 (eigvals was O(R^3) and
  ran twice). Training time: R=2048 67 s -> 24 s, R=8192 510 s -> 111 s;
  R=16384 now trains in under 10 minutes.
- --outtype f16 stores W_res as F16 and trains on the rounded reservoir.
- Apply input_scaling in the forward pass only; it was baked into W_in and
  applied again by llm_build_esn.
- Skip calibration when output feedback is enabled.

Inference (src/llama-model.cpp):
- Stack per-token states with a balanced concat tree instead of an O(n^2)
  left-to-right chain: pp512 1236 -> 3571 tok/s at R=2048.
- Activation 2 is now leaky ReLU (slope 0.01, as in training), not GELU.
- Skip the leaky blend when leaking_rate == 1.
- With an F16 reservoir, R=8192 decode goes 229 -> 404 tok/s.

Tests: test-esn-inference adds J, which checks that batched decoding with
all positions as outputs (one and two sequences) matches token-by-token
decoding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
The remote branch still carried the pre-squash commits of PR #3, whose
tree is identical to master. Merging them keeps the push fast-forward.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

# Conflicts:
#	docs/esn-completion.md
#	docs/esn.md
#	scripts/esn_training.py
#	src/llama-model.cpp
#	tests/test-esn-inference.cpp
@github-actions github-actions Bot added documentation Improvements or additions to documentation testing labels Oct 19, 2026
The repo's flake8 config enables flake8-no-print. Route all output through
a module logger (configured with a bare "%(message)s" format in main(), so
the CLI output text is unchanged; the byte-tokenizer vocab override is now
a warning). Also drop the unused GGMLQuantizationType import and two
f-strings without placeholders. Trained GGUFs are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

CI status on ff30811:

  • Lint (flake8): this PR's. Fixed in 8826f99: scripts/esn_training.py now logs through logging instead of print() (the repo enables flake8-no-print), plus an unused import and two placeholder-less f-strings. flake8 . with flake8-no-print is clean locally, and retrained GGUFs are byte-identical.
  • editorconfig: not this PR's. All 16 errors (trailing whitespace or missing final newline in docs/esn.md, docs/gpt-oss.md, examples/gpt-oss-README.md, examples/gpt-oss-example.sh, tests/test-esn.cpp) are identical on master, and this PR adds none. Proposed fix as a separate change, so this PR doesn't widen: sed -i 's/[[:space:]]*$//' <those files> plus a final newline where missing.
  • android-build (fails in Setup Android SDK), windows-latest-cmake (cpu-x64 static), windows-2022-cmake-cuda, server-windows (each fails in the libCURL download step: tar.exe: Unrecognized archive format): infrastructure failures before any code compiles. No fix exists in this repo; the push of 8826f99 re-runs them.

🤖 Generated with Claude Code


Generated by Claude Code

- src/llama-graph.h: include <cstdlib> for getenv/atoi, as upstream
  llama.cpp does. Newer MSYS2 CLANG64 headers no longer provide them
  transitively, which broke the windows-msys2 (CLANG64) build.
- scripts/esn_training.py: declare the weight matrices that initialize()
  always sets as np.ndarray (empty placeholders instead of None), and the
  optional ones as Optional[np.ndarray]. This removes the pyright errors
  the batched training code added and most of the file's earlier ones
  (31 on master -> 17). Trained GGUFs are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

Follow-up on the remaining red checks from ff30811:

  • windows-msys2 (CLANG64): failed in src/llama-graph.h (getenv/atoi undeclared). That file is untouched since the upstream sync, and the job passed on master on Oct 9, so the MSYS2 toolchain changed underneath it. Ported upstream llama.cpp's fix (#include <cstdlib>) in f688a26.
  • pyright type-check: also red on master. 7 errors in gguf-py/gguf/vocab.py and 2 in examples/json_schema_pydantic_example.py, both outside this PR; in scripts/esn_training.py, 15 from the online-learning code of esn.cpp: implement ESLLM roadmap — online learning primitives, parameter validation, hierarchical ESN config, and proprioceptive feedback API #2 using ESNConfig attributes that ESNConfig never declares. f688a26 types the ESN weight attributes, which removes every error the batched training code added and takes the script from 31 errors (master) to 17. The check stays red until the files above are fixed. I didn't fix them here, to keep this PR from widening.
  • macOS-latest-cmake-arm64: also red on master. -Werror,-Wmissing-noreturn in vendored vendor/minja/minja.hpp. Upstream has since removed vendor/minja, so there is no small fix to port.

The push of f688a26 re-runs all of these, along with the setup-step failures from the earlier comment.

🤖 Generated with Claude Code


Generated by Claude Code

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

New failures reported on 8826f99, a superseded head; its C++ is identical to ff30811:

  • ubuntu-latest-cmake-sanitizer (ADDRESS / UNDEFINED) and ggml-ci-x64-cpu-low-perf: every failure is SIGILL (***Exception: Illegal), in test-tokenizer-0-*, test-quantize-fns, test-quantize-perf, test-barrier, test-opt, and test-thread-safety. None of these tests runs code this PR changes, and the ESN suite passes in the same jobs (All 23 ESN tests passed). All three jobs were green on master on Oct 9. An illegal instruction in ggml-only tests points to the binaries having been built for a different CPU than the runner they ran on, not to a code bug. f688a26 re-runs these jobs; if SIGILL reproduces there in tests unrelated to ESN, it's the runner environment, not this PR.
  • ubuntu-22-cmake-sycl / sycl-fp16 (syclcompat/math.hpp not found in the oneAPI install) and windows-latest-cmake (llvm-arm64) (libCURL setup step): also red on master. No fix in this repo.
  • Already covered above: editorconfig, pyright, server-windows, android-build, windows-2022-cmake-cuda. windows-msys2 (CLANG64) is fixed in f688a26, and Lint is now green there.

🤖 Generated with Claude Code


Generated by Claude Code

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

Follow-up on the SIGILL failures. ggml-ci-x64-cpu-low-perf reproduced them on f688a26: test-thread-safety, test-barrier, test-quantize-fns, and test-quantize-perf fail with ***Exception: Illegal, while test-esn passes in the same job.

Root cause (CI environment, not this PR): ci/run.sh builds with GGML_NATIVE on (-march=native), and the job restores a shared ccache (key: ggml-ci-x64-cpu-low-perf; 92.8 % hit rate here). Ubuntu 22.04's ccache 4.5.1 hashes the literal -march=native flag without resolving it to the build machine's CPU, so objects compiled on one runner model are reused on another. This binary was built with AVX512 VBMI/VNNI/BF16; on a runner without those, the ggml kernels hit an illegal instruction. The sanitizer jobs have the same pattern (key: ubuntu-latest-cmake-sanitizer-<type>, native build), which explains their SIGILL on 8826f99. The job was green on master on Oct 9, before the cache crossed runner types.

Proposed fix, separate from this PR: build these ccache'd jobs with -DGGML_NATIVE=OFF, or put the runner's CPU model in the ccache key, e.g. key: ggml-ci-x64-cpu-low-perf-${{ runner.arch }}-<cpu model from /proc/cpuinfo>.

🤖 Generated with Claude Code


Generated by Claude Code

MSYS2 CLANG64 moved to clang/libc++ 23.1.3, whose headers no longer pull
<cstdlib> in transitively, so windows-msys2 (CLANG64) fails to compile
src/llama-model-loader.cpp (getenv, atoi). A preprocessor sweep of every
C/C++ TU against the MSYS2 libc++ 23 and mingw-w64 headers finds two more
TUs with the same problem: tests/test-sampling.cpp (rand, RAND_MAX) and
tools/mtmd/deprecation-warning.cpp (EXIT_FAILURE). Upstream llama.cpp
already includes <cstdlib> in those two; the loader gets the same include.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
@github-actions github-actions Bot added the mtmd label Oct 19, 2026

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

CI on f688a26:

  • windows-msys2 (CLANG64): failed again, now in src/llama-model-loader.cpp (getenv/atoi undeclared). The job now gets clang/libc++ 23.1.3, whose headers no longer pull in <cstdlib> transitively. To avoid fixing one file per CI round, I preprocessed all 146 C/C++ TUs against the MSYS2 libc++ 23.1.3 and mingw-w64 headers. That sweep flags exactly the loader failure CI hit, plus tests/test-sampling.cpp (rand, RAND_MAX) and tools/mtmd/deprecation-warning.cpp (EXIT_FAILURE). 2ab1907 adds #include <cstdlib> to all three. Upstream llama.cpp already has that include in the latter two. The sweep is clean after the change.
  • ggml-ci-arm64-cpu-high-perf-sve: also red on master. The ci/run.sh rerank check gets rerank score 2 = 0.040, outside its expected [0.10, 0.30]. master (a0ef6b1) prints the same three scores (0.032 / 0.024 / 0.040). The test uses a BERT reranker, which doesn't go through any code this PR changes.
  • windows-latest-cmake-hip: also red on master. The libCURL download step fails (tar.exe: Unrecognized archive format), the same infra failure as the other Windows jobs above.
  • ggml-ci-x64-cpu-high-perf: SIGILL in test-thread-safety, test-opt, test-barrier, test-quantize-fns, test-quantize-perf, and test-rope, from a ccache restore (key: ggml-ci-x64-cpu-high-perf, Ubuntu's ccache 4.5.1). Same root cause and proposed separate fix as the low-perf job in my previous comment.

The push of 2ab1907 re-runs all of these.

🤖 Generated with Claude Code


Generated by Claude Code

test_ctx_shift_disabled_short_prompt[-1-120-True] fails on master and on
every server-build job with "assert 248 == 120": the server now generates
until the 256-token slot is full (8 prompt + 248 generated) instead of
stopping at half the slot. Port upstream llama.cpp's updated expectation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

server-build (Release / ADDRESS / UNDEFINED) on f688a26: not this PR's. All three fail on one test, test_ctx_shift_disabled_short_prompt[-1-120-True], with assert 248 == 120. master (a0ef6b1) fails the same way. The server now keeps generating until the 256-token slot is full (8 prompt + 248 generated tokens), but the test still expects the old cutoff at half the slot. Upstream llama.cpp already changed this expectation to 248. 15f295a ports that one line, and its push re-runs the jobs.

editorconfig on 2ab1907 reports the same 16 errors as master, covered in my first comment.

🤖 Generated with Claude Code


Generated by Claude Code

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

Failures on 2ab1907 (superseded by 15f295a):

  • windows-2022-cmake-cuda (12.4): this run failed one step earlier than before, in Install Cuda Toolkit rather than libCURL. unzip '*.zip' -d ... got the archive names as separate arguments: unzip printed caution: filename not matched for every archive after the first, so only cuda_cccl was extracted and each xcopy found nothing. The same step passed on f688a26 an hour earlier, which points to the runner image (an unzip that expands the glob itself), not this PR. Upstream's .github/actions/windows-setup-cuda/action.yml uses the same unzip '*.zip' line, so there's no fix to port. The job reaches libCURL after that step anyway, and that step fails on master.
  • server-windows, windows-latest-cmake (llvm-arm64) (libCURL), android-build (Setup Android SDK), pyright (same 26 errors: 7 gguf-py/gguf/vocab.py, 2 examples/json_schema_pydantic_example.py, 17 in scripts/esn_training.py covered earlier), editorconfig: unchanged, covered in earlier comments.

🤖 Generated with Claude Code


Generated by Claude Code

windows-msys2 (CLANG64) now stops in tools/mtmd/mtmd-audio.cpp: libc++
23.1.3 no longer reaches <functional> through <thread>. Port upstream
llama.cpp's include. A syntax check of every TU against the MSYS2
libc++ 23.1.3 and mingw-w64 headers finds no other missing standard
headers in repo code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

windows-msys2 (CLANG64) on 15f295a: the <cstdlib> fixes held, and the build got further (70/254 steps, up from 48). It then stopped in tools/mtmd/mtmd-audio.cpp: std::cref / std::ref are undeclared because libc++ 23.1.3's <thread> no longer pulls in <functional>. Upstream llama.cpp already includes <functional> in that file, and 8585da4 ports it.

My earlier sweep only checked <cstdlib> functions, so this time I syntax-checked every TU against the MSYS2 libc++ 23.1.3 and mingw-w64 headers and kept the errors located in repo code. That check reproduces exactly the three mtmd-audio.cpp errors CI reported, and with the include added it finds no other missing standard headers. The errors it filters out come from my local clang 18 being older than libc++ 23 supports, not from repo code; the same files compiled in CI.

🤖 Generated with Claude Code


Generated by Claude Code

With context shift disabled, process_token() stops generation one token
before the slot is full, but only the later n_past >= n_ctx check set
truncated, so a completion that filled the slot reported
truncated = false. test_ctx_shift_disabled_short_prompt[-1-248-True]
expects true. Upstream llama.cpp sets slot.truncated in this branch too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

server-build (Release) on 8585da4: with the 248 expectation from 15f295a, test_ctx_shift_disabled_short_prompt[-1-248-True] gets past the token count and now fails on the next assert, truncated (assert False == True). The old 120 expectation had been failing first and hid this. With context shift disabled, process_token() stops one token before the slot is full (n_past + 1 >= n_ctx) without setting slot.truncated. Upstream llama.cpp sets slot.truncated = true in that same branch, which is the server half of the change whose test half I ported in 15f295a. 2954f6c ports that line.

Verified locally against stories260K.gguf: unit/test_ctx_shift.py passes 5/5. In unit/test_completion.py, which also asserts on truncated, 32 tests pass and 1 is skipped. The one failure, test_completion_stream_with_openai_library_stops, uses a preset that downloads its model over HTTPS, which my local build doesn't support, so it never ran.

🤖 Generated with Claude Code


Generated by Claude Code

Several ccache'd Linux jobs crashed with SIGILL in ggml tests
(test-quantize-fns, test-barrier, test-thread-safety, test-opt,
test-tokenizer-0-*). They build with GGML_NATIVE on, and Ubuntu 22.04's
ccache 4.5.1 hashes the literal -march=native flag, so objects compiled
on a runner with AVX-512 were restored on runners without it.

- ubuntu-cpu-cmake and ubuntu-latest-cmake-sanitizer: build with
  -DGGML_NATIVE=OFF (x86 keeps SSE4.2/AVX/AVX2/FMA/F16C), as upstream
  llama.cpp's ccache'd CPU build does.
- ggml-ci-{x64,arm64}-cpu-*: ci/run.sh builds natively on purpose, so key
  their ccache on a hash of the runner's CPU model and feature flags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Output feedback ran different dynamics in training and inference:
training fed back the softmax of the initial random readout through a W_fb
that already included feedback_scaling, while llm_build_esn fed back the
trained readout's raw logits and applied feedback_scaling a second time.
Feedback now means one thing on both sides: y(t-1) is the one-hot of the
token emitted at t-1, which is the input token at t (the true token in
training, the sampled one in generation). W_fb is stored as one row per
token and applied as a get_rows on the input tokens, scaled once.
Feeding back the readout's own prediction was tried instead: refitting
W_out on states regenerated with the previous readout did not converge.
Since W_out no longer drives the reservoir, feedback models now get the
temperature calibration too. GGUF files with feedback written before the
new esn.feedback_token key are refused at load.

Bidirectional training added backward-pass states to the readout
features, and at position t those have already read token t+1, the
target; inference runs forward only. esn_training.py now rejects
--bidirectional, and the loader warns on GGUF files that set it.

On train.txt/held_out.txt (R=1024, feedback 0.5), llama.cpp measured
13.06 bits/byte before (Python validation: 35% accuracy, 7.72 bits) and
4.89 bits/byte after (Python validation: 4.82). A --bidirectional model
reported 0.87 bits/byte in validation and measured 10.15 in llama.cpp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav

drzo commented Oct 19, 2026

Copy link
Copy Markdown
Author

Pushed 7f3fe16 (SIGILL in the ccache'd native jobs) and 586dead (ESN output feedback and bidirectional training now match inference); both are described in the updated PR description.

First failures on 586dead:

  • windows-latest-cmake (openblas-x64): not this PR's. It fails in the libCURL download step (tar.exe: Error opening archive: Unrecognized archive format) before anything compiles, the same infra failure as the other Windows jobs covered above. On 2954f6c this job was cancelled before reaching that step. No fix exists in this repo. GitHub refuses to re-run it while its workflow run is still going; I'll re-run it once when the run finishes.
  • editorconfig, android-build, server-windows: unchanged and covered in earlier comments. editorconfig reports the same 16 errors as master; in docs/esn.md only their line numbers moved, and none are on lines this push adds.

🤖 Generated with Claude Code


Generated by Claude Code

@drzo
drzo marked this pull request as ready for review October 20, 2026 22:10
@drzo
drzo merged commit a9ebc05 into master Oct 20, 2026
51 of 76 checks passed
drzo pushed a commit that referenced this pull request Oct 21, 2026
No file changes: master's tree equals this branch's. Merged instead of
force-pushing so the branch can carry the next PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ETGJBpWVh57qbY3fnTFwav
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devops documentation Improvements or additions to documentation mtmd server testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants