Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
1957cc9
Wire feedback weights into ESN forward pass
claude Oct 8, 2026
81c670d
Document end-to-end ESN pipeline
claude Oct 8, 2026
3b89b7a
Make ESN end-to-end inference actually work
claude Oct 8, 2026
ec54463
ESN: unroll the recurrence per token in llm_build_esn
claude Oct 8, 2026
f6d1c9f
ESN: real byte-level tokenizer + enough graph nodes for the unrolled …
claude Oct 8, 2026
9bd61fd
ESN: real text training-data loader + verified predictive output
claude Oct 8, 2026
46be38b
ESN: clarify W_out initialization comment
claude Oct 8, 2026
1bbc3fc
tests: add held-out byte-level perplexity benchmark for ESN
claude Oct 8, 2026
3e387e2
docs: pin ESN completion contract (criteria + evidence)
claude Oct 8, 2026
00dca0d
tests+docs: harden inference asserts; broaden perplexity evidence
claude Oct 8, 2026
dee2e1d
docs: scope-fence future-work; anchor contract to upstream pattern
claude Oct 8, 2026
e47429a
Merge remote-tracking branch 'origin/master' into claude/esn-implemen…
Copilot Oct 9, 2026
31610ca
ESN: calibrated readout, faster training, F16 reservoir, O(n log n) p…
claude Oct 19, 2026
ff30811
Merge remote branch history of merged PR #3 (no file changes)
claude Oct 19, 2026
8826f99
esn_training.py: use logging instead of print to pass flake8 Lint
claude Oct 19, 2026
f688a26
Fix msys2 CLANG64 build; type ESN weight attributes for pyright
claude Oct 19, 2026
2ab1907
Include <cstdlib> where getenv/atoi/rand/EXIT_FAILURE are used
claude Oct 19, 2026
15f295a
server tests: expect 248 tokens in ctx-shift-disabled short-prompt case
claude Oct 19, 2026
8585da4
mtmd-audio: include <functional> for std::cref/std::ref
claude Oct 19, 2026
2954f6c
server: mark completion truncated when it stops at the context limit
claude Oct 19, 2026
7f3fe16
ci: stop reusing -march=native ccache objects across runner CPUs
claude Oct 19, 2026
586dead
esn: make output feedback and bidirectional training match inference
claude Oct 19, 2026
bf123c7
Merge master (squash of #4) into claude/esn-implementation-docs-GoNIs
claude Oct 20, 2026
0f292a5
esn: train and export quantized (Q8_0/Q4_0) reservoirs; fold biases i…
claude Oct 21, 2026
de3f5f4
docs/tests: strip trailing whitespace in ESN files for editorconfig
claude Oct 21, 2026
5c1ca9c
esn_training.py: declare online-learning config fields for pyright
claude Oct 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,10 @@ python scripts/esn_training.py --config config.json
# Initialize only (no training)
python scripts/esn_training.py --init-only --output untrained.gguf

# Large reservoir: pick λ on held-out data, store W_res as F16
# Large reservoir: pick λ on held-out data, store W_res as Q4_0 (f16 and
# q8_0 also work; the readout is trained on the rounded reservoir)
python scripts/esn_training.py --reservoir-size 8192 --reg-grid 1,10,100,1000 \
--outtype f16 --train-data corpus.txt --output model.gguf
--outtype q4_0 --train-data corpus.txt --output model.gguf
```

Batch training holds out `--val-fraction` (default 10%) of the sequences to
Expand Down
74 changes: 55 additions & 19 deletions docs/esn.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,24 +90,24 @@ ESNs are implemented as a recurrent architecture in llama.cpp, leveraging the ex
The ESN forward pass (`llm_build_esn` in `src/llama-model.cpp`) consists of:

1. **Input Projection**: `W_in * input_embeddings`, scaled by `esn_input_scaling`,
plus optional `esn_input_bias`
plus the optional `esn_input_bias` and `esn_reservoir_bias` (both are
constant over time, so they are added once per batch, not per timestep)
2. **Optional Feedback**: when `esn_feedback_scaling > 0` and
`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)
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)`
5. **Optional Reservoir Bias**: Add `esn_reservoir_bias`
6. **Activation**: Apply the selected activation (`esn_activation_type`:
4. **Recurrent Projection**: `W_res * x(t)`, added to the input drive
5. **Activation**: Apply the selected activation (`esn_activation_type`:
tanh, sigmoid, or leaky ReLU with slope 0.01, matching the training script)
7. **Leaky Integration**: `x(t+1) = (1-α)*x(t) + α*f(...)` (skipped when α = 1)
8. **State Storage**: `ggml_cpy` new state back to `esn_states_all` at
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`
9. **Output Stacking**: for multi-token batches, the per-token states are
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)
10. **Output Normalization & Projection**: RMS norm, then
9. **Output Normalization & Projection**: RMS norm, then
`W_out * reservoir_state → vocabulary_logits`

Notes on features that live outside the inference path:
Expand Down Expand Up @@ -146,7 +146,7 @@ esn.vocab_size = <vocabulary size>
esn.embedding_length = <input embedding dimension>
esn.context_length = <maximum sequence length>

# ESN hyperparameters
# ESN hyperparameters
esn.reservoir_size = <number of reservoir neurons>
esn.spectral_radius = <reservoir spectral radius>
esn.sparsity = <connection sparsity>
Expand All @@ -162,7 +162,7 @@ esn.attention.layernorm_rms_eps = <RMS norm epsilon>
```
# Core tensors
token_embd.weight # [n_embd, n_vocab]
output_norm.weight # [reservoir_size]
output_norm.weight # [reservoir_size]
esn_input_weights.weight # [reservoir_size, n_embd]
esn_reservoir_weights.weight # [reservoir_size, reservoir_size]
esn_output_weights.weight # [n_vocab, reservoir_size]
Expand Down Expand Up @@ -190,7 +190,7 @@ if (llama_model_arch(model) == LLM_ARCH_ESN) {

```cpp
// Create context with recurrent memory
auto ctx_params = llama_context_default_params();
auto ctx_params = llama_context_default_params();
ctx_params.n_ctx = 2048;
auto* ctx = llama_new_context_with_model(model, ctx_params);

Expand Down Expand Up @@ -227,7 +227,7 @@ float* logits = llama_get_logits_ith(ctx, batch.n_tokens - 1);
### Memory Usage

ESN memory usage scales with:
- Reservoir size squared (for W_res)
- Reservoir size squared (for W_res)
- Reservoir × embedding dimension (for W_in)
- Vocabulary × reservoir size (for W_out)
- Recurrent state storage per sequence
Expand Down Expand Up @@ -267,7 +267,7 @@ ESNs exhibit favorable scaling properties:
### Best Practices

1. **Spectral Radius**: Keep < 1.0 for stability, typically 0.8-0.95
2. **Reservoir Size**: Should be 10-100x larger than input/output dimensions
2. **Reservoir Size**: Should be 10-100x larger than input/output dimensions
3. **Sparsity**: 5-20% connectivity often optimal
4. **Leaking Rate**: Use < 1.0 for better temporal processing

Expand All @@ -276,7 +276,7 @@ ESNs exhibit favorable scaling properties:
### Supported Features

- ✅ Standard model loading and inference
- ✅ Batch processing
- ✅ Batch processing
- ✅ Sequence management (copy, clear, remove)
- ✅ State serialization/deserialization
- ✅ Multi-backend support (CPU, GPU)
Expand All @@ -288,7 +288,7 @@ ESNs exhibit favorable scaling properties:
ESN models integrate seamlessly with:
- **llama-server**: OpenAI-compatible API
- **llama-cli**: Command-line interface
- **llama-bench**: Performance benchmarking
- **llama-bench**: Performance benchmarking
- **llama-quantize**: Model quantization
- **Python bindings**: Through llama-cpp-python

Expand Down Expand Up @@ -409,7 +409,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 |
| Reservoir type | `--outtype` | `f32` | `f16` halves the reservoir's size and its per-token read |
| 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

Expand All @@ -432,8 +432,23 @@ ESN training uses ridge regression on output weights only:
5. **Refit and Export**: the readout is refit on training + held-out data
with the chosen λ and saved as GGUF for llama.cpp inference

With `--outtype f16`, `W_res` is rounded to F16 before state collection, so
the readout is trained on exactly the reservoir inference runs.
With `--outtype f16`, `q8_0` or `q4_0`, `W_res` is rounded to that type
before state collection, so the readout is trained on the reservoir
inference runs. The reservoir is random, so rounding it costs little; what
matters is that the readout sees the rounded one. Quantizing an F32-trained
model afterwards (as `llama-quantize` would) puts a different reservoir
under the readout: at R=2048 that took held-out entropy from 4.77 to 6.86
bits/byte, where training on the Q4_0 reservoir gives 4.78.

ggml's CPU backend also rounds the state vector before each `W_res`
product: to F16 for an F16 reservoir, and to Q8_0 blocks (`rint(x * 127 /
amax)` per 32 values, with the scale stored as F16) for Q8_0 and Q4_0 ones.
State collection rounds it the same way, so the Python validation numbers
are what llama.cpp computes on CPU: logits agree to ~1e-6 for Q8_0 and Q4_0
reservoirs, where unrounded states differed by ~5e-3 and changed the
next-byte argmax at 2-22 % of positions. An F16 reservoir still differs by
~1e-4 at some positions, where a state element sits on an F16 rounding
boundary. Other backends round the vector their own way.

### Measured Effect of the Training and Inference Optimizations

Expand Down Expand Up @@ -471,6 +486,27 @@ 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.

### Quantized Reservoirs

The same corpus and held-out file, with `--embedding-dim 64 --spectral-radius
0.9 --leaking-rate 0.5 --use-bias --seq-length 256 --washout 32 --reg-grid
0.1,1,10,100` (674 windows; λ=1 was selected for every model), 4-thread CPU,
`llama-bench -r 3`:

| | R=2048 F32 | R=2048 F16 | R=2048 Q8_0 | R=2048 Q4_0 | R=8192 F32 | R=8192 F16 | R=8192 Q8_0 | R=8192 Q4_0 |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| GGUF size | 19 MB | 11 MB | 7 MB | 5 MB | 267 MB | 139 MB | 79 MB | 47 MB |
| held-out bits/byte | 4.772 | 4.772 | 4.779 | 4.783 | 4.331 | 4.330 | 4.336 | 4.346 |
| held-out perplexity | 27.3 | 27.3 | 27.5 | 27.5 | 20.1 | 20.1 | 20.2 | 20.3 |
| held-out argmax accuracy | 38.5 % | 38.5 % | 38.7 % | 38.6 % | 46.5 % | 46.4 % | 46.2 % | 46.4 % |
| pp512 (tok/s) | 4935 | 6982 | 6979 | 7976 | 244 | 592 | 826 | 951 |
| tg128 (tok/s) | 3796 | 5174 | 5770 | 6677 | 220 | 548 | 758 | 922 |

Training time does not depend on the type (47-48 s at R=2048, 448-480 s
at R=8192). At R=8192 a token's work is mostly reading `W_res`, so Q4_0
generates 4.2x faster than F32 and 1.7x faster than F16, for 0.015
bits/byte.

## Related research directions (not part of this implementation)

The items below are a **separate research roadmap**, not pending work on
Expand Down Expand Up @@ -551,4 +587,4 @@ Token t arrives

1. Jaeger, H. (2001). The "echo state" approach to analysing and training recurrent neural networks. GMD Technical Report 148.
2. Lukoševičius, M., & Jaeger, H. (2009). Reservoir computing approaches to recurrent neural network training. Computer Science Review, 3(3), 127-149.
3. Verstraeten, D., Schrauwen, B., D'Haene, M., & Stroobandt, D. (2007). An experimental unification of reservoir computing methods. Neural networks, 20(3), 391-403.
3. Verstraeten, D., Schrauwen, B., D'Haene, M., & Stroobandt, D. (2007). An experimental unification of reservoir computing methods. Neural networks, 20(3), 391-403.
116 changes: 93 additions & 23 deletions scripts/esn_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
sys.path.insert(0, str(_GGUF_PY))

try:
from gguf import GGUFWriter
from gguf import GGML_QUANT_SIZES, GGMLQuantizationType, GGUFWriter, LlamaFileType, quants
except ImportError as e:
raise SystemExit(
"The 'gguf' package is required. Install the one bundled with this\n"
Expand All @@ -60,6 +60,18 @@
class ESNConfig:
"""Configuration for Echo State Network."""

# Online-learning metadata, set by main() only when it is to be embedded in
# the GGUF. Class-level defaults keep them out of __dict__ (and so out of
# to_json/from_json) unless they are actually set.
online_learning: bool = False
online_lr: float = 0.0
online_reg: float = 0.0
online_buffer_size: int = 0
online_update_mode: int = 0
online_decay_rate: float = 0.0
freeze_reservoir: bool = False
replay_window: int = 0

def __init__(
self,
vocab_size: int = 32000,
Expand Down Expand Up @@ -135,6 +147,50 @@ def get_activation_fn(activation_type: int) -> Callable:
# Bound on the floats held per batch of reservoir states during training.
_STATE_BATCH_FLOATS = 1 << 27

# Storage types for W_res (--outtype), with the general.file_type each gives
# the model: W_res holds nearly all of its parameters.
RESERVOIR_TYPES = {
"f32": (GGMLQuantizationType.F32, LlamaFileType.ALL_F32),
"f16": (GGMLQuantizationType.F16, LlamaFileType.MOSTLY_F16),
"q8_0": (GGMLQuantizationType.Q8_0, LlamaFileType.MOSTLY_Q8_0),
"q4_0": (GGMLQuantizationType.Q4_0, LlamaFileType.MOSTLY_Q4_0),
}

# Rows of W_res quantized at a time, bounding gguf-py's float temporaries.
_QUANT_CHUNK_FLOATS = 1 << 24


def quantize_rows(W: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
"""W [rows, cols] in qtype's GGUF storage layout, chunked by rows."""
if qtype == GGMLQuantizationType.F32:
return np.ascontiguousarray(W, dtype=np.float32)
if qtype == GGMLQuantizationType.F16:
return np.ascontiguousarray(W, dtype=np.float16)
chunk = max(1, _QUANT_CHUNK_FLOATS // W.shape[1])
return np.concatenate([quants.quantize(np.ascontiguousarray(W[r:r + chunk], dtype=np.float32), qtype)
for r in range(0, len(W), chunk)])


def round_like_vec_dot(x: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
"""
Round reservoir states x [..., R] the way ggml's CPU backend converts the
vector side of ggml_mul_mat(W_res, x) to W_res's vec_dot_type, so that
training sees the states inference computes: F16 for an F16 reservoir,
Q8_0 blocks for Q8_0 and Q4_0 ones (quantize_row_q8_0: q = rint(x * 127 /
amax), scale amax / 127 stored as F16).
"""
if qtype == GGMLQuantizationType.F32:
return x
if qtype == GGMLQuantizationType.F16:
return x.astype(np.float16).astype(np.float32)
blocks = x.reshape(*x.shape[:-1], -1, 32)
amax = np.abs(blocks).max(axis=-1, keepdims=True)
with np.errstate(divide="ignore"):
iscale = np.where(amax > 0, np.float32(127) / amax, np.float32(0))
q = np.rint(blocks * iscale)
scale = (amax / np.float32(127)).astype(np.float16).astype(np.float32)
return (q * scale).reshape(x.shape)


def spectral_radius(W: np.ndarray, krylov_dim: int = 128, seed: int = 0) -> float:
"""Largest eigenvalue modulus of a square matrix.
Expand Down Expand Up @@ -237,8 +293,8 @@ 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
# dtype the reservoir matrix is stored in by save_gguf().
self.reservoir_dtype = np.float32
# Type the reservoir matrix is stored in by save_gguf().
self.reservoir_type = "f32"

self._initialized = False

Expand Down Expand Up @@ -391,7 +447,7 @@ def forward(

for t in range(n_tokens):
# Reservoir recurrence
reservoir_input = self.W_res @ x + drive[t]
reservoir_input = self.W_res @ self._vec_dot_state(x) + drive[t]

# Add noise if specified
if self.config.noise_level > 0:
Expand Down Expand Up @@ -440,7 +496,7 @@ def forward_batch(self, embeddings: np.ndarray, tokens: Optional[np.ndarray] = N
state = np.zeros((batch, size), dtype=np.float32)
states = np.empty((batch, n_tokens, size), dtype=np.float32)
for t in range(n_tokens):
pre = state @ self.W_res.T
pre = self._vec_dot_state(state) @ self.W_res.T
pre += drive[:, t]
if self.config.noise_level > 0:
pre += (self.rng.standard_normal((batch, size)).astype(np.float32)
Expand Down Expand Up @@ -604,11 +660,23 @@ def train(

return accuracy

def set_reservoir_dtype(self, dtype) -> None:
"""Store W_res as dtype in the GGUF, and round it now so the readout is
trained on the same reservoir that inference will run."""
self.reservoir_dtype = np.dtype(dtype)
self.W_res = self.W_res.astype(self.reservoir_dtype).astype(np.float32)
def set_reservoir_type(self, name: str) -> None:
"""
Store W_res as one of RESERVOIR_TYPES in the GGUF, and round it now so
the readout is trained on the reservoir that inference will run. From
then on the states fed to W_res are rounded as llama.cpp's CPU backend
rounds them (round_like_vec_dot).
"""
qtype = RESERVOIR_TYPES[name][0]
block = GGML_QUANT_SIZES[qtype][0]
if self.config.reservoir_size % block:
raise ValueError(f"--outtype {name} needs a reservoir size that is a multiple of {block}")
self.reservoir_type = name
if qtype != GGMLQuantizationType.F32:
self.W_res = quants.dequantize(quantize_rows(self.W_res, qtype), qtype).astype(np.float32)

def _vec_dot_state(self, x: np.ndarray) -> np.ndarray:
return round_like_vec_dot(x, RESERVOIR_TYPES[self.reservoir_type][0])

# ------------------------------------------------------------------
# Online / incremental learning (Phase 3 of ESLLM roadmap)
Expand Down Expand Up @@ -761,7 +829,7 @@ def online_train_sequence(

for t, tgt in enumerate(target_sequence):
# Update reservoir state
res_in = self.W_res @ state + drive[t]
res_in = self.W_res @ self._vec_dot_state(state) + drive[t]
activated = self.activation_fn(res_in)
state = (1 - self.config.leaking_rate) * state + self.config.leaking_rate * activated

Expand Down Expand Up @@ -822,9 +890,7 @@ def save_gguf(self, path: str) -> None:

# General metadata
writer.add_name("ESN Model")
# llama_ftype: W_res holds nearly all parameters, so an F16 reservoir
# makes the model MOSTLY_F16 (1); otherwise ALL_F32 (0).
writer.add_file_type(1 if self.reservoir_dtype == np.float16 else 0)
writer.add_file_type(RESERVOIR_TYPES[self.reservoir_type][1])

# Base model dimensions — use the standard key helpers so llama.cpp's
# auto-derived KV keys resolve correctly (they map arch -> key).
Expand Down Expand Up @@ -863,7 +929,7 @@ def save_gguf(self, path: str) -> None:
writer.add_uint32("esn.activation_type", self.config.activation_type)
writer.add_bool("esn.bidirectional", self.config.bidirectional)

if getattr(self.config, "online_learning", False):
if self.config.online_learning:
writer.add_bool("esn.online_learning.enabled", True)
writer.add_float32("esn.online_learning.rate", self.config.online_lr)
writer.add_float32("esn.online_learning.reg", self.config.online_reg)
Expand Down Expand Up @@ -898,12 +964,15 @@ def _f32(x: np.ndarray) -> np.ndarray:
return np.ascontiguousarray(x, dtype=np.float32)

# W_res is the only tensor read once per token for every token, so it
# may be stored as F16 (see set_reservoir_dtype). The fitted softmax
# temperature is folded into W_out so inference needs no extra op.
# may be stored as F16 or quantized (see set_reservoir_type); it was
# already rounded to that type, so this re-quantization is exact. The
# fitted softmax temperature is folded into W_out so inference needs
# no extra op.
res_qtype = RESERVOIR_TYPES[self.reservoir_type][0]
writer.add_tensor("token_embd.weight", _f32(self.tok_embd.T))
writer.add_tensor("esn_input_weights.weight", _f32(self.W_in))
writer.add_tensor("esn_reservoir_weights.weight",
np.ascontiguousarray(self.W_res, dtype=self.reservoir_dtype))
writer.add_tensor("esn_reservoir_weights.weight", quantize_rows(self.W_res, res_qtype),
raw_dtype=res_qtype)
writer.add_tensor("output_norm.weight", _f32(self.output_norm))
writer.add_tensor("esn_output_weights.weight",
_f32(self.W_out * self.output_temperature))
Expand Down Expand Up @@ -1120,8 +1189,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("--outtype", choices=["f32", "f16"], default="f32",
help="Storage type of the reservoir matrix in the GGUF")
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 "
"reservoir size that is a multiple of 32")

# Tokenizer
parser.add_argument("--tokenizer", choices=["byte", "none"], default="byte",
Expand Down Expand Up @@ -1201,8 +1272,7 @@ def main():
# Create and initialize ESN
esn = ESN(config)
esn.initialize()
if args.outtype == "f16":
esn.set_reservoir_dtype(np.float16)
esn.set_reservoir_type(args.outtype)

if not args.init_only:
# Load or create training data
Expand Down
Loading
Loading