diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index db885907cdae..58078da6dd0b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -237,6 +237,7 @@ jobs: id: cmake_build run: | cmake -B build \ + -DGGML_NATIVE=OFF \ -DLLAMA_FATAL_WARNINGS=ON \ -DGGML_RPC=ON cmake --build build --config Release -j $(nproc) @@ -301,6 +302,7 @@ jobs: run: | cmake -B build \ -DLLAMA_FATAL_WARNINGS=ON \ + -DGGML_NATIVE=OFF \ -DLLAMA_SANITIZE_${{ matrix.sanitizer }}=ON \ -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} cmake --build build --config ${{ matrix.build_type }} -j $(nproc) @@ -311,6 +313,7 @@ jobs: run: | cmake -B build \ -DLLAMA_FATAL_WARNINGS=ON \ + -DGGML_NATIVE=OFF \ -DLLAMA_SANITIZE_${{ matrix.sanitizer }}=ON \ -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \ -DGGML_OPENMP=OFF @@ -1314,10 +1317,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # ci/run.sh 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: ggml-ci-x64-cpu-low-perf + key: ggml-ci-x64-cpu-low-perf-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Dependencies @@ -1339,10 +1349,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # ci/run.sh 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: ggml-ci-arm64-cpu-low-perf + key: ggml-ci-arm64-cpu-low-perf-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Dependencies @@ -1364,10 +1381,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # ci/run.sh 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: ggml-ci-x64-cpu-high-perf + key: ggml-ci-x64-cpu-high-perf-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Dependencies @@ -1389,10 +1413,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # ci/run.sh 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: ggml-ci-arm64-cpu-high-perf + key: ggml-ci-arm64-cpu-high-perf-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Dependencies @@ -1414,10 +1445,17 @@ jobs: id: checkout uses: actions/checkout@v4 + - name: CPU fingerprint + id: cpu + # ci/run.sh 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: ggml-ci-arm64-cpu-high-perf-sve + key: ggml-ci-arm64-cpu-high-perf-sve-${{ steps.cpu.outputs.fingerprint }} evict-old-files: 1d - name: Dependencies diff --git a/CLAUDE.md b/CLAUDE.md index baf7405a220e..ce903e0508c0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ 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 | Bidirectional reservoir processing | +| `esn_bidirectional` | false | Not supported (inference is forward-only) | ### Tensor Layout @@ -47,7 +47,7 @@ esn_input_weights.weight [reservoir_size, n_embd] esn_reservoir_weights.weight [reservoir_size, reservoir_size] output_norm.weight [reservoir_size] esn_output_weights.weight [n_vocab, reservoir_size] -esn_feedback_weights.weight [reservoir_size, n_vocab] (optional) +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) ``` @@ -118,8 +118,16 @@ 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 +python scripts/esn_training.py --reservoir-size 8192 --reg-grid 1,10,100,1000 \ + --outtype f16 --train-data corpus.txt --output model.gguf ``` +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`). + ## Common Tasks ### Debugging ESN Issues diff --git a/docs/esn-completion.md b/docs/esn-completion.md index a96d240054bf..07e89aefd47a 100644 --- a/docs/esn-completion.md +++ b/docs/esn-completion.md @@ -71,13 +71,15 @@ sign off on criteria 1–4, 6, 7 by inspection of the file set; criterion | Feedback path is wired | `src/llama-model.cpp` | `W_fb · y(t-1)` added when `esn_feedback_scaling != 0` | | Logits are produced | `src/llama-model.cpp` | `W_out · x(t)` emitted as `result_output` | -**Verified by**: `bin/test-esn-inference` runs assertions A–I against the +**Verified by**: `bin/test-esn-inference` runs assertions A–J against the C API: load (A), context init (B), multi-token prompt decode (C), single-token step (D), all-finite logits (E), **determinism — same prompt in a fresh context yields bit-identical logits (F)**, **prompt sensitivity — different prompts yield different logits (G)**, **state advancement — -different input bytes yield different logits (H)**, and softmax well- -definedness (I). These are numerical runtime properties, not smoke +different input bytes yield different logits (H)**, softmax well- +definedness (I), and **batch consistency — a multi-token batch with every +position as an output, alone or alongside a second sequence, matches +token-by-token decoding (J)**. These are numerical runtime properties, not smoke checks. Passes on two independently-trained models (R=2048 and R=1024, different seeds and hyperparameters). @@ -117,6 +119,12 @@ trained models with different seeds, reservoir sizes, embedding dims, spectral radii, leaking rates, and sparsities. The forward pass is numerically correct, not luck. +These models predate readout calibration. With the calibrated readout and +held-out λ selection now in `scripts/esn_training.py`, held-out entropy on a +9 602-byte held-out file is 5.77 bits/byte at R=2048 and 5.65 bits/byte at +R=8192, at equal or better argmax accuracy; see "Measured Effect of the Training +and Inference Optimizations" in `docs/esn.md`. + ### 6. Documentation describes what's shipped | Requirement | Satisfied by | Evidence | @@ -152,7 +160,7 @@ work. Their absence does not block this contract: - [x] Arch registry (criterion 1) — `ctest -R test-esn` 8/8 - [x] Model loading (criterion 2) — two independently-trained GGUFs load -- [x] Forward pass single + multi-token (criterion 3) — `test-esn-inference` PASSED (A..I, incl. determinism, prompt sensitivity, state advancement) +- [x] Forward pass single + multi-token (criterion 3) — `test-esn-inference` PASSED (A..J, incl. determinism, prompt sensitivity, state advancement, batch consistency) - [x] Training produces usable models (criterion 4) — ridge acc 0.5216 (R=2048), two independently-trained models - [x] Beats uniform on real text (criterion 5) — 7.77 bits/byte on full held-out, confirmed on both models - [x] Docs cover shipped functionality (criterion 6) — `docs/esn.md`, `CLAUDE.md`, this file diff --git a/docs/esn.md b/docs/esn.md index 5fa388938ce6..5d213eee21b6 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -33,14 +33,19 @@ Where: - `y(t)` is the output projection at time t - `W_res` is the reservoir weight matrix (with spectral radius < 1) - `W_in` is the input weight matrix -- `W_fb` is the optional output-to-reservoir feedback matrix +- `W_fb` is the optional output-to-reservoir feedback matrix, applied to + `y(t-1)`, the one-hot of the token emitted at t-1 - `W_out` is the trained output readout matrix - `b` are the optional input/reservoir bias vectors - `f` is the activation function (tanh, sigmoid, or leaky-relu) - `α` is the leaking rate (controls memory vs. adaptation trade-off) The feedback term `W_fb * y(t-1)` is only included when `esn_feedback_scaling > 0` -and the `esn_feedback_weights` tensor is present in the GGUF file. +and the `esn_feedback_weights` tensor is present in the GGUF file. The token +emitted at t-1 is the input token at t: the sampled token in generation and +the true next token in training (teacher forcing). So `W_fb * y(t-1)` is the +row of `W_fb` for the input token, scaled by `esn_feedback_scaling`, and +training and inference run the same recurrence. ### Model Components @@ -56,7 +61,7 @@ and the `esn_feedback_weights` tensor is present in the GGUF file. | `esn_feedback_scaling` | Output-to-reservoir feedback (0 = disabled) | 0.0 | >= 0 | | `esn_noise_level` | Noise injection for regularization | 0.0 | >= 0 | | `esn_activation_type` | Activation function (0=tanh, 1=sigmoid, 2=leaky_relu) | 0 | {0,1,2} | -| `esn_bidirectional` | Enable bidirectional processing | false | bool | +| `esn_bidirectional` | Not supported (inference is forward-only; see limitations) | false | bool | #### Tensors @@ -65,7 +70,7 @@ and the `esn_feedback_weights` tensor is present in the GGUF file. | `esn_input_weights` | `[reservoir_size, n_embd]` | Maps input embeddings to reservoir | | `esn_reservoir_weights` | `[reservoir_size, reservoir_size]` | Recurrent reservoir connections | | `esn_output_weights` | `[n_vocab, reservoir_size]` | Maps reservoir to output vocabulary | -| `esn_feedback_weights` | `[reservoir_size, n_vocab]` | Output-to-reservoir feedback (optional) | +| `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) | @@ -86,19 +91,23 @@ 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` -2. **State Retrieval**: Get previous reservoir state via +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()` -3. **Recurrent Projection**: `W_res * x(t)` -4. **Optional Feedback**: When `esn_feedback_scaling > 0` and - `esn_feedback_weights` is loaded, add - `esn_feedback_scaling * W_fb * (W_out * x(t))` to the pre-activation +4. **Recurrent Projection**: `W_res * x(t)` 5. **Optional Reservoir Bias**: Add `esn_reservoir_bias` 6. **Activation**: Apply the selected activation (`esn_activation_type`: - tanh, sigmoid, or gelu as a leaky-relu proxy) -7. **Leaky Integration**: `x(t+1) = (1-α)*x(t) + α*f(...)` + 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 `kv_head * reservoir_size` -9. **Output Normalization & Projection**: RMS norm, then +9. **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 `W_out * reservoir_state → vocabulary_logits` Notes on features that live outside the inference path: @@ -106,9 +115,9 @@ Notes on features that live outside the inference path: - **`esn_noise_level`**: injected into the reservoir update during Python training (`scripts/esn_training.py`) for regularization; omitted from the deterministic inference graph -- **`esn_bidirectional`**: affects how `W_res` is initialized at training - time; inference remains strictly causal/forward to preserve streaming - semantics +- **`esn_bidirectional`**: not supported. Inference is causal, and the + training script rejects `--bidirectional`; the loader warns when a GGUF + 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 @@ -239,6 +248,21 @@ ESNs exhibit favorable scaling properties: 2. **Initialization**: Reservoir weights should satisfy echo state property 3. **Hyperparameter Sensitivity**: Performance depends critically on spectral radius 4. **Limited Context**: No explicit attention mechanism for long-range dependencies +5. **Output feedback is the emitted token, not the readout**: `W_fb` is + applied to the one-hot of the token emitted at t-1, which training + (teacher forcing) and inference both know exactly. Feeding back the + readout's own prediction instead would put `W_out` inside the recurrence + whose states it is fit to: ridge regression has no closed form for that, + and refitting on states regenerated with the previous readout did not + converge in tests. GGUF files with feedback written before + `esn.feedback_token` (which fed back raw `W_out * x` logits at inference + and something else in training) are refused at load and need retraining. +6. **No bidirectional reservoirs**: the readout predicts the next token, and + 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 + that set `esn.bidirectional`. ### Best Practices @@ -319,8 +343,8 @@ extension of `_write_tokenizer()` — call `writer.add_tokenizer_model(...)`, - Inference-time (consumed by `llm_build_esn`): activation choice, feedback (when `esn_feedback_scaling > 0` and `esn_feedback_weights` are in the GGUF), input bias, reservoir bias, leaky integration, input scaling. -- Training-time-only: noise injection, bidirectional reservoir - initialization, spectral radius scaling, sparsity masking. +- Training-time-only: noise injection, spectral radius scaling, sparsity + masking. ## Testing @@ -382,15 +406,70 @@ python scripts/esn_training.py --init-only --reservoir-size 2048 --output untrai | Leaking Rate | `--leaking-rate` | 0.3 | Memory vs adaptation trade-off | | Regularization | `--regularization` | 1e-6 | Ridge regression lambda | | Washout | `--washout` | 100 | Initial timesteps to discard | +| 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 | ### Training Process ESN training uses ridge regression on output weights only: -1. **Initialization**: Random reservoir and input weights (fixed) -2. **State Collection**: Run input sequences through reservoir -3. **Ridge Regression**: `W_out = Y^T * X * (X^T * X + λI)^(-1)` -4. **GGUF Export**: Save trained model for llama.cpp inference +1. **Initialization**: Random reservoir and input weights (fixed). The + reservoir is rescaled to the target spectral radius, computed exactly up + to R=2048 and estimated with a 128-step Arnoldi iteration above that + (`np.linalg.eigvals` is O(R³) and took longer than training at R=8192). +2. **State Collection**: Run input sequences through the reservoir in + batches (one matrix-matrix product per timestep for the whole batch), + accumulating `XᵀX` and `XᵀY` without materializing `X` +3. **Ridge Regression**: `W_out = Y^T * X * (X^T * X + λI)^(-1)`; with + `--reg-grid`, the λ with the lowest held-out NLL is used +4. **Calibration**: ridge regression to one-hot targets produces + probability-scale outputs, so using them directly as logits gives a + nearly uniform softmax. A single logit scale β is fitted on the + held-out sequences (NLL is convex in β) and folded into `W_out`. It does + not change the argmax. +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. + +### Measured Effect of the Training and Inference Optimizations + +Byte-level models (`--tokenizer byte --embedding-dim 128 --spectral-radius +0.9 --leaking-rate 0.3 --sparsity 0.1 --seq-length 256 --washout 32`) +trained on ~86 kB of this repository's markdown and evaluated with +`test-esn-perplexity` on a separate ~9.6 kB held-out file; 4-thread CPU. +"Before" is the previous training script and graph builder. + +| | 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 | +| prompt processing, pp512 (tok/s) | 1236 | 3571 | 162 | 247 | 443 | +| generation, tg128 (tok/s) | 2879 | 2701 | 203 | 229 | 404 | + +The R=2048 throughput numbers are an A/B of the old and new graph builder +on the same model and machine (`llama-bench -r 10`); generation is +unchanged within noise there, since a single-token step does no output +stacking. At R=8192 generation is bound by reading `W_res` once per token +(256 MiB in F32), so the F16 reservoir nearly doubles it. Fixing λ at +R=8192 matters as much as calibration: at λ=1e-2 the readout overfits +(93.7 % training vs 24.1 % validation accuracy) and calibration alone +reaches only 6.70 bits/byte. + +With the Arnoldi spectral-radius estimate, R=16384 is now practical on the +same 4-core machine: an F16 model (λ searched over 10/100/1000) trains in +584 s, reaches 5.635 bits/byte (perplexity 49.7, argmax 29.9 %) on the same +held-out file, and generates at 70 tok/s from a 536 MiB GGUF. The previous +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. ## Related research directions (not part of this implementation) diff --git a/scripts/esn_training.py b/scripts/esn_training.py index 71534a35b67a..63e9cdd9729d 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -13,7 +13,6 @@ - Multiple activation functions (tanh, sigmoid, leaky_relu) - Output feedback connections for generative tasks - Bias vectors for input and reservoir -- Bidirectional reservoir processing - Ridge regression training with regularization Usage: @@ -27,6 +26,7 @@ import argparse import json +import logging import numpy as np from pathlib import Path from typing import Optional, Tuple, Dict, Any, Callable @@ -42,13 +42,15 @@ sys.path.insert(0, str(_GGUF_PY)) try: - from gguf import GGUFWriter, GGMLQuantizationType + from gguf import GGUFWriter except ImportError as e: raise SystemExit( "The 'gguf' package is required. Install the one bundled with this\n" "repository by running: pip install -e gguf-py" ) from e +logger = logging.getLogger("esn-training") + # Activation type constants (must match llama-hparams.h) ACTIVATION_TANH = 0 ACTIVATION_SIGMOID = 1 @@ -96,8 +98,8 @@ def __init__( 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. - print(f"[ESNConfig] tokenizer='byte' requires vocab_size=256; " - f"overriding vocab_size {self.vocab_size} -> 256") + logger.warning(f"[ESNConfig] tokenizer='byte' requires vocab_size=256; " + f"overriding vocab_size {self.vocab_size} -> 256") self.vocab_size = 256 @classmethod @@ -126,6 +128,75 @@ def get_activation_fn(activation_type: int) -> Callable: return np.tanh +# Up to this size, exact np.linalg.eigvals (O(R^3)) is cheap; above it, it +# dominates initialization (minutes at R=8192, hours at R=16384). +_EXACT_EIGVALS_MAX_SIZE = 2048 + +# Bound on the floats held per batch of reservoir states during training. +_STATE_BATCH_FLOATS = 1 << 27 + + +def spectral_radius(W: np.ndarray, krylov_dim: int = 128, seed: int = 0) -> float: + """Largest eigenvalue modulus of a square matrix. + + Exact for small matrices; above _EXACT_EIGVALS_MAX_SIZE uses the outermost + Ritz value of a `krylov_dim`-step Arnoldi factorization (within 0.2% of + exact at R=4096 for ESN reservoirs, at O(krylov_dim * R^2) cost). + """ + n = W.shape[0] + if n <= _EXACT_EIGVALS_MAX_SIZE: + return float(np.max(np.abs(np.linalg.eigvals(W)))) + + m = min(krylov_dim, n) + rng = np.random.default_rng(seed) + Q = np.zeros((m + 1, n), dtype=np.float64) + H = np.zeros((m + 1, m), dtype=np.float64) + q = rng.standard_normal(n) + Q[0] = q / np.linalg.norm(q) + for j in range(m): + v = (W @ Q[j].astype(W.dtype)).astype(np.float64) + for _ in range(2): # classical Gram-Schmidt, applied twice for stability + h = Q[: j + 1] @ v + v -= h @ Q[: j + 1] + H[: j + 1, j] += h + H[j + 1, j] = np.linalg.norm(v) + if H[j + 1, j] < 1e-12: # invariant subspace found + m = j + 1 + break + Q[j + 1] = v / H[j + 1, j] + return float(np.max(np.abs(np.linalg.eigvals(H[:m, :m])))) + + +def softmax_nll(Z: np.ndarray, y: np.ndarray, beta: float) -> float: + """Mean negative log-likelihood (nats) of targets y under softmax(beta * Z).""" + S = beta * Z.astype(np.float64) + m = S.max(axis=1, keepdims=True) + lse = m[:, 0] + np.log(np.exp(S - m).sum(axis=1)) + return float(np.mean(lse - S[np.arange(len(y)), y])) + + +def fit_temperature(Z: np.ndarray, y: np.ndarray) -> float: + """Scale beta > 0 minimizing softmax_nll(Z, y, beta). + + The NLL is convex in beta, hence unimodal in log(beta), so a golden-section + search over a wide bracket finds the global minimum. + """ + lo, hi = np.log(1e-2), np.log(1e4) + g = (np.sqrt(5.0) - 1.0) / 2.0 + a, b = hi - g * (hi - lo), lo + g * (hi - lo) + fa, fb = softmax_nll(Z, y, np.exp(a)), softmax_nll(Z, y, np.exp(b)) + for _ in range(60): + if fa < fb: + hi, b, fb = b, a, fa + a = hi - g * (hi - lo) + fa = softmax_nll(Z, y, np.exp(a)) + else: + lo, a, fa = a, b, fb + b = lo + g * (hi - lo) + fb = softmax_nll(Z, y, np.exp(b)) + return float(np.exp((lo + hi) / 2.0)) + + class ESN: """ Echo State Network implementation for training. @@ -139,43 +210,56 @@ class ESN: - Multiple activation functions - Output feedback connections - Bias vectors - - Bidirectional processing """ def __init__(self, config: ESNConfig): + if config.bidirectional: + # At position t a backward pass has already read token t+1, the + # readout's target, while llm_build_esn runs forward only. + raise ValueError( + "bidirectional reservoirs are not supported: the readout predicts " + "the next token, which backward-pass states have already seen") self.config = config self.rng = np.random.default_rng(config.seed) self.activation_fn = get_activation_fn(config.activation_type) - # Initialize weights - self.W_in = None # Input weights - self.W_res = None # Reservoir weights - self.W_out = None # Output weights (trained) - self.W_fb = None # Feedback weights (optional) - self.b_in = None # Input bias (optional) - self.b_res = None # Reservoir bias (optional) - self.tok_embd = None # Token embeddings - self.output_norm = None # Output normalization + # Weights. initialize() sets every non-optional one; until then they + # are empty placeholders, so their type is a plain ndarray. + self.W_in: np.ndarray = np.empty((0, 0), dtype=np.float32) # Input weights + self.W_res: np.ndarray = np.empty((0, 0), dtype=np.float32) # Reservoir weights + self.W_out: np.ndarray = np.empty((0, 0), dtype=np.float32) # Output weights (trained) + self.W_fb: Optional[np.ndarray] = None # Feedback weights [vocab, reservoir] (optional) + self.b_in: Optional[np.ndarray] = None # Input bias (optional) + self.b_res: Optional[np.ndarray] = None # Reservoir bias (optional) + self.tok_embd: np.ndarray = np.empty((0, 0), dtype=np.float32) # Token embeddings + self.output_norm: np.ndarray = np.empty(0, dtype=np.float32) # Output normalization + # Ridge regression fits W_out to one-hot targets, so W_out @ x is on a + # 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 self._initialized = False def initialize(self) -> None: """Initialize all weight matrices according to ESN principles.""" - print(f"Initializing ESN with reservoir size {self.config.reservoir_size}") - print(f" Activation: {['tanh', 'sigmoid', 'leaky_relu'][self.config.activation_type]}") - print(f" Feedback scaling: {self.config.feedback_scaling}") - print(f" Bidirectional: {self.config.bidirectional}") - print(f" Use bias: {self.config.use_bias}") + logger.info(f"Initializing ESN with reservoir size {self.config.reservoir_size}") + logger.info(f" Activation: {['tanh', 'sigmoid', 'leaky_relu'][self.config.activation_type]}") + logger.info(f" Feedback scaling: {self.config.feedback_scaling}") + logger.info(f" Use bias: {self.config.use_bias}") # Token embeddings (random initialization, to be learned or loaded) self.tok_embd = self.rng.standard_normal( (self.config.embedding_dim, self.config.vocab_size) ).astype(np.float32) * 0.02 - # Input weights: dense random matrix scaled by input_scaling + # Input weights: dense random matrix. input_scaling is applied in the + # forward pass, as llm_build_esn does with esn.input_scaling; baking it + # in here as well would apply it twice at inference. self.W_in = self.rng.standard_normal( (self.config.reservoir_size, self.config.embedding_dim) - ).astype(np.float32) * self.config.input_scaling + ).astype(np.float32) # Reservoir weights: sparse random matrix with specified connectivity self._init_reservoir_weights() @@ -192,12 +276,14 @@ def initialize(self) -> None: (self.config.vocab_size, self.config.reservoir_size) ).astype(np.float32) * 0.02 - # Optional: feedback weights + # Optional: feedback weights, one row per token since the fed-back + # output is a one-hot (see _input_drive). Unscaled, like W_in: + # feedback_scaling is applied once, in the forward pass. if self.config.feedback_scaling > 0: self.W_fb = self.rng.standard_normal( - (self.config.reservoir_size, self.config.vocab_size) - ).astype(np.float32) * self.config.feedback_scaling - print(f" Initialized feedback weights") + (self.config.vocab_size, self.config.reservoir_size) + ).astype(np.float32) + logger.info(" Initialized feedback weights") # Optional: bias vectors if self.config.use_bias: @@ -205,10 +291,10 @@ def initialize(self) -> None: self.b_res = self.rng.standard_normal( self.config.reservoir_size ).astype(np.float32) * 0.1 - print(f" Initialized bias vectors") + logger.info(" Initialized bias vectors") self._initialized = True - print("ESN initialization complete") + logger.info("ESN initialization complete") def _init_reservoir_weights(self) -> None: """ @@ -218,34 +304,66 @@ def _init_reservoir_weights(self) -> None: size = self.config.reservoir_size sparsity = self.config.sparsity - # Create sparse connectivity mask - connectivity = self.rng.random((size, size)) < sparsity + # Draw in row chunks to avoid full-size float64 temporaries. Chunked + # draws consume the RNG stream exactly like one (size, size) draw, so + # a given seed yields the same reservoir as before. + chunk = max(1, (1 << 24) // size) + connectivity = np.empty((size, size), dtype=bool) + for r in range(0, size, chunk): + connectivity[r:r + chunk] = self.rng.random((min(chunk, size - r), size)) < sparsity - # Random weights for connected elements - weights = self.rng.standard_normal((size, size)).astype(np.float32) - weights *= connectivity # Apply sparsity mask + weights = np.empty((size, size), dtype=np.float32) + for r in range(0, size, chunk): + weights[r:r + chunk] = self.rng.standard_normal((min(chunk, size - r), size)) + weights[r:r + chunk] *= connectivity[r:r + chunk] + del connectivity - # Scale to desired spectral radius - eigenvalues = np.linalg.eigvals(weights) - current_spectral_radius = np.max(np.abs(eigenvalues)) - - if current_spectral_radius > 0: - scale = self.config.spectral_radius / current_spectral_radius - weights *= scale + radius = spectral_radius(weights) + if radius > 0: + weights *= self.config.spectral_radius / radius self.W_res = weights - # Verify spectral radius - eigenvalues = np.linalg.eigvals(self.W_res) - actual_sr = np.max(np.abs(eigenvalues)) - print(f" Reservoir spectral radius: {actual_sr:.4f} (target: {self.config.spectral_radius})") - print(f" Reservoir sparsity: {1 - np.count_nonzero(self.W_res) / self.W_res.size:.2%} zeros") + method = "exact" if size <= _EXACT_EIGVALS_MAX_SIZE else "Arnoldi estimate" + logger.info(f" Reservoir spectral radius: {self.config.spectral_radius} " + f"(unscaled radius {radius:.4f}, {method})") + logger.info(f" Reservoir sparsity: {1 - np.count_nonzero(self.W_res) / self.W_res.size:.2%} zeros") + + def _input_drive(self, embeddings: np.ndarray, tokens: Optional[np.ndarray]) -> np.ndarray: + """ + The part of the reservoir pre-activation that does not depend on the + state: s·W_in·u(t) + b_in + b_res, plus the output feedback. + + The fed-back output y(t-1) is the one-hot of the token emitted at + t-1, which is the input token at t: the true next token in training + (teacher forcing) and the sampled token in generation. W_fb·y(t-1) + is therefore the row W_fb[token_t], and training and llm_build_esn + run the same recurrence. (Feeding back the readout's own prediction + would make the states depend on W_out, which is fit to those states.) + + Args: + embeddings: Input embeddings [..., embedding_dim] + tokens: Token IDs of the inputs [...]; required with feedback + + Returns: + drive: [..., reservoir_size] + """ + drive = (embeddings @ self.W_in.T) * self.config.input_scaling + if self.b_in is not None: + drive += self.b_in + if self.b_res is not None: + drive += self.b_res + if self.W_fb is not None: + if tokens is None: + raise ValueError("output feedback is enabled: pass the input token IDs") + drive += self.config.feedback_scaling * self.W_fb[tokens] + return drive def forward( self, embeddings: np.ndarray, state: Optional[np.ndarray] = None, - prev_output: Optional[np.ndarray] = None + tokens: Optional[np.ndarray] = None, ) -> Tuple[np.ndarray, np.ndarray]: """ ESN forward pass. @@ -253,7 +371,8 @@ def forward( Args: embeddings: Input embeddings [n_tokens, embedding_dim] state: Previous reservoir state [reservoir_size] or None - prev_output: Previous output for feedback [vocab_size] or None + tokens: Token IDs of the inputs [n_tokens]; required when output + feedback is enabled (see _input_drive) Returns: states: Reservoir states for all timesteps [n_tokens, reservoir_size] @@ -265,29 +384,14 @@ def forward( n_tokens = embeddings.shape[0] alpha = self.config.leaking_rate - if state is None: - state = np.zeros(self.config.reservoir_size, dtype=np.float32) + x = np.zeros(self.config.reservoir_size, dtype=np.float32) if state is None else state + drive = self._input_drive(embeddings, tokens) states = np.zeros((n_tokens, self.config.reservoir_size), dtype=np.float32) for t in range(n_tokens): - # Project input to reservoir space - input_proj = self.W_in @ embeddings[t] - - # Add input bias if present - if self.b_in is not None: - input_proj += self.b_in - # Reservoir recurrence - reservoir_input = self.W_res @ state + input_proj - - # Add feedback if enabled - if self.W_fb is not None and prev_output is not None: - reservoir_input += self.W_fb @ prev_output - - # Add reservoir bias if present - if self.b_res is not None: - reservoir_input += self.b_res + reservoir_input = self.W_res @ x + drive[t] # Add noise if specified if self.config.noise_level > 0: @@ -299,43 +403,68 @@ def forward( activated = self.activation_fn(reservoir_input) # Leaky integration: x(t+1) = (1-α)*x(t) + α*f(...) - state = (1 - alpha) * state + alpha * activated + x = (1 - alpha) * x + alpha * activated - states[t] = state + states[t] = x - # Update prev_output for next iteration (if using feedback) - if self.W_fb is not None: - # Simple softmax to get output distribution - logits = self.W_out @ state - prev_output = np.exp(logits - np.max(logits)) - prev_output /= prev_output.sum() + return states, x - return states, state - - def forward_bidirectional( - self, - embeddings: np.ndarray, - ) -> np.ndarray: + def forward_batch(self, embeddings: np.ndarray, tokens: Optional[np.ndarray] = None) -> np.ndarray: """ - Bidirectional ESN forward pass. + Forward pass over a batch of equal-length sequences, from a zero state. - Processes sequence in both directions and concatenates states. + Equivalent to forward() on each sequence up to float rounding, but + runs one matrix-matrix product per timestep for the whole batch + instead of one matrix-vector product per sequence. With noise + enabled, noise is drawn per timestep for the whole batch, so the + noise values differ from forward()'s. Args: - embeddings: Input embeddings [n_tokens, embedding_dim] + embeddings: Input embeddings [batch, n_tokens, embedding_dim] + tokens: Token IDs of the inputs [batch, n_tokens]; required when + output feedback is enabled Returns: - states: Combined bidirectional states [n_tokens, 2*reservoir_size] + states: Reservoir states [batch, n_tokens, reservoir_size] """ - # Forward pass - states_fwd, _ = self.forward(embeddings) + if not self._initialized: + raise RuntimeError("ESN not initialized. Call initialize() first.") - # Backward pass - states_bwd, _ = self.forward(embeddings[::-1]) - states_bwd = states_bwd[::-1] # Reverse to align with forward + batch, n_tokens, _ = embeddings.shape + size = self.config.reservoir_size + alpha = self.config.leaking_rate + + # The input drive does not depend on the state: one product for all steps. + drive = self._input_drive(embeddings, tokens) - # Concatenate - return np.concatenate([states_fwd, states_bwd], axis=1) + 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 += drive[:, t] + if self.config.noise_level > 0: + pre += (self.rng.standard_normal((batch, size)).astype(np.float32) + * self.config.noise_level) + state = (1 - alpha) * state + alpha * self.activation_fn(pre) + states[:, t] = state + + return states + + def _state_batches(self, token_sequences: np.ndarray): + """Yield (start, states [batch, seq_length, reservoir_size]) over token_sequences.""" + n_tokens = token_sequences.shape[1] + batch = max(1, _STATE_BATCH_FLOATS // (n_tokens * self.config.reservoir_size)) + embd = self.tok_embd.T # [vocab_size, embedding_dim] + for start in range(0, len(token_sequences), batch): + tokens = token_sequences[start:start + batch] + yield start, self.forward_batch(embd[tokens], tokens) + + def _readout_features(self, states: np.ndarray) -> np.ndarray: + """Map states [n, reservoir_size] to the RMS-normalized vectors W_out + reads, matching llm_build_esn's output_norm.""" + X = states / np.sqrt(np.mean(states ** 2, axis=-1, keepdims=True) + 1e-6) + X *= self.output_norm + return X def collect_states(self, token_sequences: np.ndarray) -> np.ndarray: """ @@ -347,26 +476,49 @@ def collect_states(self, token_sequences: np.ndarray) -> np.ndarray: Returns: all_states: Collected states [total_tokens, reservoir_size] """ - all_states = [] - - for seq in token_sequences: - # Convert tokens to embeddings - embeddings = self.tok_embd[:, seq].T # [seq_length, embedding_dim] - - # Get reservoir states - if self.config.bidirectional: - states = self.forward_bidirectional(embeddings) - else: - states, _ = self.forward(embeddings) - all_states.append(states) - - return np.vstack(all_states) + return np.concatenate( + [s.reshape(-1, s.shape[-1]) for _, s in self._state_batches(token_sequences)]) + + def _normal_equations(self, inputs, targets, washout, keep_rows): + """Accumulate X^T X and X^T Y over readout features, batch by batch, + without materializing X. Also returns the first keep_rows (X, y).""" + size, vocab = self.config.reservoir_size, self.config.vocab_size + XtX = np.zeros((size, size), dtype=np.float64) + XtY = np.zeros((size, vocab), dtype=np.float64) + kept_X, kept_y, n_rows = [], [], 0 + for start, states in self._state_batches(inputs): + logger.info(f" Processing sequence {start}/{len(inputs)}") + X = self._readout_features(states[:, washout:].reshape(-1, states.shape[-1])) + y = targets[start:start + len(states), washout:].reshape(-1) + Y = np.zeros((len(y), vocab), dtype=np.float32) + Y[np.arange(len(y)), y] = 1.0 + XtX += X.T @ X + XtY += X.T @ Y + take = min(keep_rows - min(n_rows, keep_rows), len(y)) + if take > 0: + kept_X.append(X[:take].copy()) + kept_y.append(y[:take]) + n_rows += len(y) + return XtX, XtY, n_rows, np.concatenate(kept_X), np.concatenate(kept_y) + + @staticmethod + def _ridge_solve(XtX: np.ndarray, XtY: np.ndarray, lam: float) -> np.ndarray: + """W_out [V, R] = ((X^T X + lam I)^-1 X^T Y)^T; XtX is left unchanged.""" + idx = np.diag_indices_from(XtX) + diag = XtX[idx].copy() + XtX[idx] += lam + W = np.linalg.solve(XtX, XtY) + XtX[idx] = diag + return W.T.astype(np.float32) def train( self, token_sequences: np.ndarray, target_sequences: np.ndarray, - washout: int = 100 + washout: int = 100, + val_fraction: float = 0.1, + calibrate: bool = True, + reg_grid: Optional[list] = None, ) -> float: """ Train output weights using batch ridge regression. @@ -374,82 +526,90 @@ def train( This is the key insight of ESNs: only the output layer needs to be trained, and it can be done with a simple linear method. + With at least 10 sequences, the last val_fraction of them are held + out (after a one-sequence gap, since text windows overlap by half) to + choose the ridge penalty from reg_grid and to fit the output + temperature; the readout is then refit on train + validation data. + Args: token_sequences: Input token IDs [n_sequences, seq_length] target_sequences: Target token IDs [n_sequences, seq_length] washout: Number of initial timesteps to discard + val_fraction: Fraction of sequences held out for selection + calibrate: Fit the logit scale on held-out data (output_temperature) + reg_grid: Candidate ridge penalties, chosen by held-out NLL Returns: - training_accuracy: Accuracy after training + training_accuracy: Accuracy on (a sample of) the training data """ if not self._initialized: raise RuntimeError("ESN not initialized. Call initialize() first.") - - print(f"Collecting reservoir states (washout={washout})...") - - # Collect reservoir states and targets - all_states = [] - all_targets = [] - - for seq_idx, (in_seq, tgt_seq) in enumerate(zip(token_sequences, target_sequences)): - if seq_idx % 100 == 0: - print(f" Processing sequence {seq_idx}/{len(token_sequences)}") - - # Convert tokens to embeddings - embeddings = self.tok_embd[:, in_seq].T - - # Get reservoir states - if self.config.bidirectional: - states = self.forward_bidirectional(embeddings) - else: - states, _ = self.forward(embeddings) - - # Remove washout period - states = states[washout:] - targets = tgt_seq[washout:] - - all_states.append(states) - all_targets.extend(targets) - - X = np.vstack(all_states) # [n_samples, reservoir_size] or [n_samples, 2*reservoir_size] - y = np.array(all_targets) # [n_samples] - - state_dim = X.shape[1] - print(f"Training output weights on {X.shape[0]} samples (state dim: {state_dim})...") - - # Apply RMS normalization to states - rms = np.sqrt(np.mean(X ** 2, axis=-1, keepdims=True) + 1e-6) - X_norm = X / rms - - # For bidirectional, we need to adjust the output weights - if self.config.bidirectional: - # Combine forward and backward contributions - X_norm = X_norm[:, :self.config.reservoir_size] + X_norm[:, self.config.reservoir_size:] - - X_norm *= self.output_norm - - # Convert targets to one-hot - Y = np.zeros((len(y), self.config.vocab_size), dtype=np.float32) - for i, target in enumerate(y): - Y[i, target] = 1.0 - - # Ridge regression: W_out = Y^T * X * (X^T * X + λI)^(-1) - reg = self.config.regularization * np.eye(self.config.reservoir_size) - XtX = X_norm.T @ X_norm + reg - XtY = X_norm.T @ Y - - # Solve linear system - self.W_out = np.linalg.solve(XtX, XtY).T - - # Calculate training accuracy - predictions = X_norm @ self.W_out.T - pred_tokens = np.argmax(predictions, axis=-1) - accuracy = np.mean(pred_tokens == y) - - print(f"Training complete. Accuracy: {accuracy:.4f}") + if washout >= token_sequences.shape[1]: + raise ValueError( + f"washout ({washout}) must be smaller than the sequence length " + f"({token_sequences.shape[1]}), or no states are left to train on") + + n_seq = len(token_sequences) + n_val = 0 + if (calibrate or reg_grid) and val_fraction > 0 and n_seq >= 10: + n_val = max(1, int(round(n_seq * val_fraction))) + n_train = n_seq - n_val - (1 if n_val else 0) + keep_rows = max(1, _STATE_BATCH_FLOATS // self.config.reservoir_size) + + logger.info(f"Collecting reservoir states (washout={washout})...") + XtX, XtY, n_rows, X_fit, y_fit = self._normal_equations( + token_sequences[:n_train], target_sequences[:n_train], washout, keep_rows) + + lam = self.config.regularization + if n_val: + val_XtX, val_XtY, n_val_rows, X_val, y_val = self._normal_equations( + token_sequences[n_seq - n_val:], target_sequences[n_seq - n_val:], + washout, keep_rows) + bits = 1.0 / np.log(2.0) + + if reg_grid: + logger.info(" ridge penalty validation NLL (bits/token, temperature-fitted)") + scores = [] + for cand in reg_grid: + Z = X_val @ self._ridge_solve(XtX, XtY, cand).T + scores.append(softmax_nll(Z, y_val, fit_temperature(Z, y_val)) * bits) + logger.info(f" {cand:13.3g} {scores[-1]:.4f}") + lam = float(reg_grid[int(np.argmin(scores))]) + self.config.regularization = lam + logger.info(f" selected ridge penalty {lam:.3g}") + + Z = X_val @ self._ridge_solve(XtX, XtY, lam).T + if calibrate: + self.output_temperature = fit_temperature(Z, y_val) + logger.info(f"Validation ({n_val_rows} tokens): " + f"accuracy {np.mean(np.argmax(Z, axis=1) == y_val):.4f}, " + f"NLL {softmax_nll(Z, y_val, 1.0) * bits:.4f} -> " + f"{softmax_nll(Z, y_val, self.output_temperature) * bits:.4f} bits/token " + f"at logit scale {self.output_temperature:.4g}") + + XtX += val_XtX + XtY += val_XtY + n_rows += n_val_rows + del val_XtX, val_XtY + elif calibrate: + logger.info("Skipping readout calibration: need at least 10 sequences to hold out from") + + 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) + + accuracy = float(np.mean(np.argmax(X_fit @ self.W_out.T, axis=1) == y_fit)) + logger.info(f"Training complete. Accuracy: {accuracy:.4f}" + + (f" (first {len(y_fit)} samples)" if len(y_fit) < n_rows else "")) 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) + # ------------------------------------------------------------------ # Online / incremental learning (Phase 3 of ESLLM roadmap) # ------------------------------------------------------------------ @@ -466,7 +626,7 @@ def init_rls(self) -> None: lam = max(self.config.regularization, 1e-9) # Inverse correlation matrix P: P = (1/λ) I self._rls_P = np.eye(rsz, dtype=np.float32) * (1.0 / lam) - print(f"RLS initialised: reservoir_size={rsz}, λ={lam:.2e}") + logger.info(f"RLS initialised: reservoir_size={rsz}, λ={lam:.2e}") def rls_update( self, @@ -595,17 +755,13 @@ def online_train_sequence( self.init_rls() embeddings = self.tok_embd[:, token_sequence].T # [T, E] + drive = self._input_drive(embeddings, token_sequence) state = np.zeros(self.config.reservoir_size, dtype=np.float32) losses = [] - for t, (emb, tgt) in enumerate(zip(embeddings, target_sequence)): + for t, tgt in enumerate(target_sequence): # Update reservoir state - input_proj = self.W_in @ emb - if self.b_in is not None: - input_proj += self.b_in - res_in = self.W_res @ state + input_proj - if self.b_res is not None: - res_in += self.b_res + res_in = self.W_res @ state + drive[t] activated = self.activation_fn(res_in) state = (1 - self.config.leaking_rate) * state + self.config.leaking_rate * activated @@ -641,9 +797,10 @@ def save_gguf(self, path: str) -> None: - ``esn.leaking_rate`` (float32, required) - ``esn.input_scaling`` (float32, required) - ``esn.feedback_scaling`` (float32, optional) + - ``esn.feedback_token`` (bool, with feedback: fed-back output is the input token) - ``esn.noise_level`` (float32, optional) - ``esn.activation_type`` (uint32, optional: 0=tanh, 1=sigmoid, 2=leaky_relu) - - ``esn.bidirectional`` (bool, optional) + - ``esn.bidirectional`` (bool, optional; always false) - ``esn.attention.layernorm_rms_eps`` (float32, required by loader) Tensors emitted (``.weight`` suffix per llama.cpp convention): @@ -652,19 +809,22 @@ def save_gguf(self, path: str) -> None: - ``esn_reservoir_weights.weight`` [reservoir_size, reservoir_size] - ``output_norm.weight`` [reservoir_size] - ``esn_output_weights.weight`` [reservoir_size, n_vocab] - - ``esn_feedback_weights.weight`` (optional) + - ``esn_feedback_weights.weight`` [reservoir_size, n_vocab] (optional) - ``esn_input_bias.weight`` (optional) - ``esn_reservoir_bias.weight`` (optional) """ if not self._initialized: raise RuntimeError("ESN not initialized. Call initialize() first.") - print(f"Saving model to {path}") + logger.info(f"Saving model to {path}") writer = GGUFWriter(path=path, arch="esn") # 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) # Base model dimensions — use the standard key helpers so llama.cpp's # auto-derived KV keys resolve correctly (they map arch -> key). @@ -695,6 +855,10 @@ def save_gguf(self, path: str) -> None: writer.add_float32("esn.leaking_rate", self.config.leaking_rate) writer.add_float32("esn.input_scaling", self.config.input_scaling) writer.add_float32("esn.feedback_scaling", self.config.feedback_scaling) + if self.W_fb is not None: + # Marks the feedback definition of _input_drive; llama.cpp refuses + # feedback models without it, whose training did not match inference. + writer.add_bool("esn.feedback_token", True) 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) @@ -726,18 +890,23 @@ def save_gguf(self, path: str) -> None: # output_norm.weight C++ {reservoir} [1-D] # esn_output_weights.weight C++ {reservoir, n_vocab} # -> numpy (n_vocab, reservoir) [matches training layout] - # esn_feedback_weights.weight C++ {n_vocab, reservoir} - # -> numpy (reservoir, n_vocab) [matches training layout] + # esn_feedback_weights.weight C++ {reservoir, n_vocab} + # -> numpy (n_vocab, reservoir) [matches training layout] # esn_input_bias.weight C++ {reservoir} [1-D] # esn_reservoir_bias.weight C++ {reservoir} [1-D] 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. 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", _f32(self.W_res)) + writer.add_tensor("esn_reservoir_weights.weight", + np.ascontiguousarray(self.W_res, dtype=self.reservoir_dtype)) writer.add_tensor("output_norm.weight", _f32(self.output_norm)) - writer.add_tensor("esn_output_weights.weight", _f32(self.W_out)) + writer.add_tensor("esn_output_weights.weight", + _f32(self.W_out * self.output_temperature)) if self.W_fb is not None: writer.add_tensor("esn_feedback_weights.weight", _f32(self.W_fb)) @@ -751,7 +920,7 @@ def _f32(x: np.ndarray) -> np.ndarray: writer.write_tensors_to_file() writer.close() - print(f"Model saved successfully ({os.path.getsize(path) / 1e6:.1f} MB)") + logger.info(f"Model saved successfully ({os.path.getsize(path) / 1e6:.1f} MB)") def _write_tokenizer(self, writer: GGUFWriter) -> None: """Write the tokenizer section to the GGUF file. @@ -874,7 +1043,7 @@ def load_text_training_data( inputs_arr = np.stack(inputs, axis=0) targets_arr = np.stack(targets, axis=0) - print( + logger.info( f"Loaded {len(inputs_arr)} windows of length {seq_length} from " f"{path} ({len(data)} bytes)" ) @@ -896,9 +1065,6 @@ def main(): # Generative ESN with feedback python esn_training.py --reservoir-size 1024 --feedback-scaling 0.5 - # Bidirectional ESN - python esn_training.py --reservoir-size 512 --bidirectional - # Online RLS training (infer-train / ESLLM) python esn_training.py --reservoir-size 1024 --online --online-mode rls \\ --forgetting-factor 0.999 --output online_model.gguf @@ -935,7 +1101,8 @@ def main(): parser.add_argument("--noise-level", type=float, default=0.0, help="Noise injection level for regularization") parser.add_argument("--bidirectional", action="store_true", - help="Use bidirectional reservoir processing") + help="Not supported: backward-pass states have seen the " + "next token the readout predicts") parser.add_argument("--use-bias", action="store_true", help="Use bias vectors for input and reservoir") @@ -945,6 +1112,16 @@ def main(): help="Number of sequences for sample data") 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, + help="Fraction of sequences held out to select the " + "regularization and fit the softmax temperature") + parser.add_argument("--reg-grid", type=str, default=None, + help="Comma-separated regularization values to try " + "(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") # Tokenizer parser.add_argument("--tokenizer", choices=["byte", "none"], default="byte", @@ -978,6 +1155,11 @@ def main(): help="Save config to JSON file") args = parser.parse_args() + logging.basicConfig(level=logging.INFO, format="%(message)s") + 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 " + "inference runs forward only") # Map activation name to type activation_map = { @@ -1012,18 +1194,20 @@ def main(): # Save config if requested if args.save_config: config.to_json(args.save_config) - print(f"Config saved to {args.save_config}") + logger.info(f"Config saved to {args.save_config}") - print(f"ESN Configuration: {config}") + logger.info(f"ESN Configuration: {config}") # Create and initialize ESN esn = ESN(config) esn.initialize() + if args.outtype == "f16": + esn.set_reservoir_dtype(np.float16) if not args.init_only: # Load or create training data if args.train_data: - print(f"Loading training data from {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, @@ -1031,7 +1215,7 @@ def main(): max_sequences=args.n_sequences, ) else: - print("Using sample training data (for testing only)") + 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 ) @@ -1040,7 +1224,7 @@ def main(): # ---------------------------------------------------------- # # Online / incremental training (Phase 3 – ESLLM infer-train) # # ---------------------------------------------------------- # - print(f"\nOnline training mode: {args.online_mode.upper()}") + logger.info(f"\nOnline training mode: {args.online_mode.upper()}") if args.online_mode == "rls": # Override regularisation for RLS initialisation config.regularization = args.online_reg @@ -1062,12 +1246,12 @@ def main(): total_loss += stats["mean_loss"] * stats["n_updates"] if seq_idx % 100 == 0: mean_so_far = total_loss / max(total_updates, 1) - print(f" Seq {seq_idx}/{len(input_seqs)} " - f"mean_loss={mean_so_far:.4f} updates={total_updates}") + logger.info(f" Seq {seq_idx}/{len(input_seqs)} " + f"mean_loss={mean_so_far:.4f} updates={total_updates}") mean_loss = total_loss / max(total_updates, 1) - print(f"\nOnline training complete. " - f"Total updates: {total_updates} Mean loss: {mean_loss:.4f}") + 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: @@ -1085,17 +1269,23 @@ def main(): config.freeze_reservoir = True config.replay_window = 256 esn.config = config - print("Online learning metadata will be embedded in GGUF.") + logger.info("Online learning metadata will be embedded in GGUF.") else: # Batch ridge regression (original mode) - accuracy = esn.train(input_seqs, target_seqs, washout=args.washout) - print(f"Final training accuracy: {accuracy:.4f}") + reg_grid = None + if args.reg_grid: + reg_grid = [float(v) for v in args.reg_grid.split(",") if v.strip()] + accuracy = esn.train(input_seqs, target_seqs, washout=args.washout, + val_fraction=args.val_fraction, + calibrate=not args.no_calibrate, + reg_grid=reg_grid) + logger.info(f"Final training accuracy: {accuracy:.4f}") # Save to GGUF esn.save_gguf(args.output) - print(f"\nModel saved to {args.output}") - print("\nTo use with llama.cpp:") - print(f" ./llama-cli -m {args.output} -p \"Your prompt here\"") + 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\"") if __name__ == "__main__": diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index dbe7b853a95a..c5de881cf6a1 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -269,6 +269,7 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_ESN_LEAKING_RATE, "esn.leaking_rate" }, { LLM_KV_ESN_INPUT_SCALING, "esn.input_scaling" }, { LLM_KV_ESN_FEEDBACK_SCALING, "esn.feedback_scaling" }, + { LLM_KV_ESN_FEEDBACK_TOKEN, "esn.feedback_token" }, { LLM_KV_ESN_NOISE_LEVEL, "esn.noise_level" }, { LLM_KV_ESN_ACTIVATION_TYPE, "esn.activation_type" }, { LLM_KV_ESN_BIDIRECTIONAL, "esn.bidirectional" }, @@ -2472,7 +2473,7 @@ static const std::map LLM_TENSOR_INFOS = { {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_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}}, }; diff --git a/src/llama-arch.h b/src/llama-arch.h index 8afd3098f2a6..90a005ac68a2 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -274,6 +274,7 @@ enum llm_kv { LLM_KV_ESN_LEAKING_RATE, LLM_KV_ESN_INPUT_SCALING, LLM_KV_ESN_FEEDBACK_SCALING, + LLM_KV_ESN_FEEDBACK_TOKEN, LLM_KV_ESN_NOISE_LEVEL, LLM_KV_ESN_ACTIVATION_TYPE, LLM_KV_ESN_BIDIRECTIONAL, diff --git a/src/llama-graph.h b/src/llama-graph.h index 34b984afeb04..269428d6e1f2 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -6,6 +6,7 @@ #include "llama-adapter.h" #include +#include #include #include #include diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp index 36884c370b1f..ca73291c69c9 100644 --- a/src/llama-hparams.cpp +++ b/src/llama-hparams.cpp @@ -264,6 +264,15 @@ void llama_hparams::validate_esn_params() const { std::to_string(esn_feedback_scaling)); } + // Models written before esn.feedback_token fed back W_out·x at inference + // and something else in training; refuse them rather than run them. + if (esn_feedback_scaling > 0.0f && !esn_feedback_token) { + throw std::invalid_argument( + "ESN: this model uses an output-feedback definition that its training " + "did not match (esn.feedback_token is not set); retrain it with " + "scripts/esn_training.py"); + } + // noise_level must be non-negative if (esn_noise_level < 0.0f) { throw std::invalid_argument( diff --git a/src/llama-hparams.h b/src/llama-hparams.h index 13d79a21ea3d..6b8286f92cf9 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -143,9 +143,10 @@ struct llama_hparams { float esn_leaking_rate = 1.0f; float esn_input_scaling = 1.0f; float esn_feedback_scaling = 0.0f; // output-to-reservoir feedback (0 = disabled) + 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; // bidirectional reservoir processing + bool esn_bidirectional = false; // unsupported (inference is causal); loader warns // ESN online learning / infer-train (Phase 3) bool esn_online_learning = false; // enable online readout adaptation diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp index aa3a65f87a54..a03d74996fe3 100644 --- a/src/llama-model-loader.cpp +++ b/src/llama-model-loader.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include diff --git a/src/llama-model.cpp b/src/llama-model.cpp index d11d137b7cb1..994cb985b3c9 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -2060,6 +2060,7 @@ void llama_model::load_hparams(llama_model_loader & ml) { // Optional ESN parameters with defaults ml.get_key(LLM_KV_ESN_FEEDBACK_SCALING, hparams.esn_feedback_scaling, false); + ml.get_key(LLM_KV_ESN_FEEDBACK_TOKEN, hparams.esn_feedback_token, false); 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); @@ -2085,6 +2086,12 @@ 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; @@ -6050,10 +6057,10 @@ bool llama_model::load_tensors(llama_model_loader & ml) { // W_out.ne[1]=n_vocab. output = create_tensor(tn(LLM_TENSOR_ESN_OUTPUT_WEIGHTS, "weight"), {reservoir_size, n_vocab}, 0); - // Optional: W_fb used as ggml_mul_mat(W_fb, y_prev) where - // y_prev.ne[0]=n_vocab, so W_fb.ne[0]=n_vocab, - // W_fb.ne[1]=reservoir_size. - layers[0].wv = create_tensor(tn(LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, "weight"), {n_vocab, reservoir_size}, TENSOR_NOT_REQUIRED); + // 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); // Optional: bias vectors (same length as reservoir). layers[0].bq = create_tensor(tn(LLM_TENSOR_ESN_INPUT_BIAS, "weight"), {reservoir_size}, TENSOR_NOT_REQUIRED); @@ -19391,26 +19398,26 @@ struct llm_build_apertus : public llm_graph_context { // x(t+1) = (1-α)*x(t) + α*f(W_res*x(t) + W_in*u(t) + W_fb*y(t-1) + b) // // Features: -// - Configurable activation (tanh / sigmoid / gelu as leaky-relu proxy) -// - Optional output-to-reservoir feedback (feedback_scaling > 0, W_fb present) +// - Configurable activation (tanh / sigmoid / leaky-relu) +// - Optional feedback of the emitted token (feedback_scaling > 0, W_fb present) // - Optional input and reservoir bias tensors // - Leaky integration via leaking_rate // // Features set at training time (via scripts/esn_training.py), not needed in // the inference path: // - esn_noise_level: noise injection during training for regularization -// - esn_bidirectional: reservoir weights initialized for bidirectional -// processing; inference remains causal/forward-only to preserve -// streaming semantics // - esn_spectral_radius / esn_sparsity: baked into W_res at training time +// +// esn_bidirectional is not supported: inference is causal, and a readout +// trained on backward-pass states has seen the token it predicts. struct llm_build_esn : public llm_graph_context_mamba { // Helper function to apply activation based on type ggml_tensor * apply_esn_activation(ggml_tensor * x, uint32_t activation_type) { switch (activation_type) { case 1: // sigmoid return ggml_sigmoid(ctx0, x); - case 2: // leaky_relu (approximated with gelu for now) - return ggml_gelu(ctx0, x); + case 2: // leaky_relu, same 0.01 slope as scripts/esn_training.py + return ggml_leaky_relu(ctx0, x, 0.01f, false); default: // 0 = tanh (default) return ggml_tanh(ctx0, x); } @@ -19452,6 +19459,19 @@ struct llm_build_esn : public llm_graph_context_mamba { if (model.layers[0].bq) { u = ggml_add(ctx0, u, model.layers[0].bq); } + + // 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"); + // {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)); + } cb(u, "esn_input_proj", -1); // u is laid out as [reservoir_size, n_seq_tokens * n_seqs]. Reshape @@ -19486,35 +19506,23 @@ struct llm_build_esn : public llm_graph_context_mamba { // -> [reservoir_size, n_seqs] ggml_tensor * rec = ggml_mul_mat(ctx0, model.layers[0].wk, state); - // Pre-activation = W_res·x + W_in·u (+ feedback + bias) + // Pre-activation = W_res·x + W_in·u + W_fb·y (+ bias) ggml_tensor * pre = ggml_add(ctx0, rec, u_t); - // Optional output-to-reservoir feedback. We approximate y(t-1) - // by projecting the current state (= the state BEFORE this - // step's update) through W_out, then back through W_fb — this - // is the standard "projection surrogate" trick that avoids - // needing a cached y state in the recurrent memory. - if (model.layers[0].wv && feedback_scaling > 0.0f) { - // W_out · x : [reservoir_size, n_vocab] * [reservoir_size, n_seqs] - // -> [n_vocab, n_seqs] - ggml_tensor * y_prev = ggml_mul_mat(ctx0, model.output, state); - // W_fb · y : [n_vocab, reservoir_size] * [n_vocab, n_seqs] - // -> [reservoir_size, n_seqs] - ggml_tensor * fb = ggml_mul_mat(ctx0, model.layers[0].wv, y_prev); - fb = ggml_scale(ctx0, fb, feedback_scaling); - pre = ggml_add(ctx0, pre, fb); - } - if (model.layers[0].bk) { pre = ggml_add(ctx0, pre, model.layers[0].bk); } ggml_tensor * activated = apply_esn_activation(pre, activation_type); - // Leaky integration. - 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); + // 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); + } per_token.push_back(state); } @@ -19538,13 +19546,27 @@ struct llm_build_esn : public llm_graph_context_mamba { 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. - cur = ggml_reshape_3d(ctx0, per_token[0], reservoir_size, 1, n_seqs); - for (int64_t t = 1; t < n_seq_tokens; ++t) { - ggml_tensor * nxt = ggml_reshape_3d(ctx0, per_token[t], reservoir_size, 1, n_seqs); - cur = ggml_concat(ctx0, cur, nxt, 1); + // 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, cur, reservoir_size, n_tokens); + cur = ggml_reshape_2d(ctx0, level[0], reservoir_size, n_tokens); } cb(cur, "esn_reservoir_seq", -1); diff --git a/tests/test-esn-inference.cpp b/tests/test-esn-inference.cpp index bb0e73bfb703..7e75268aafe2 100644 --- a/tests/test-esn-inference.cpp +++ b/tests/test-esn-inference.cpp @@ -19,6 +19,10 @@ // state is not frozen). // I. Softmax is well-defined: exp(logits - max) sums to a finite, // strictly-positive value. +// J. Batch consistency: decoding a prompt in one batch with every +// position as an output — alone, and alongside a second sequence in +// the same batch — yields the same per-position logits as feeding it +// one token at a time. // // Invocation (from the build dir): // bin/test-esn-inference @@ -39,12 +43,12 @@ static void silent_log(enum ggml_log_level, const char *, void *) {} -static llama_context * make_ctx(llama_model * model) { +static llama_context * make_ctx(llama_model * model, uint32_t n_seq_max = 1) { llama_context_params cparams = llama_context_default_params(); cparams.n_ctx = 64; cparams.n_batch = 64; cparams.n_ubatch = 64; - cparams.n_seq_max = 1; + cparams.n_seq_max = n_seq_max; cparams.no_perf = true; return llama_init_from_model(model, cparams); } @@ -93,6 +97,67 @@ static double max_abs_diff(const std::vector & a, const std::vector & v) { + double m = 0.0; + for (float x : v) m = std::fmax(m, std::fabs((double) x)); + return m; +} + +// Per-position logits from feeding tokens one decode call at a time. +static std::vector> stepwise_logits(llama_model * model, const std::vector & tokens, + int32_t n_vocab) { + llama_context * ctx = make_ctx(model); + assert(ctx && "J: init stepwise context"); + std::vector> out; + for (llama_token t : tokens) { + const bool ok = decode_step(ctx, t); + assert(ok && "J: stepwise decode"); + out.push_back(snapshot_logits(ctx, n_vocab)); + } + llama_free(ctx); + return out; +} + +// 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, + const std::vector>> & refs, int32_t n_vocab) { + int32_t n_total = 0; + for (const auto & s : seqs) n_total += (int32_t) s.size(); + + llama_context * ctx = make_ctx(model, (uint32_t) seqs.size()); + assert(ctx && "J: init batched context"); + llama_batch batch = llama_batch_init(n_total, 0, 1); + for (size_t s = 0; s < seqs.size(); ++s) { + for (size_t t = 0; t < seqs[s].size(); ++t) { + const int32_t i = batch.n_tokens++; + batch.token[i] = seqs[s][t]; + batch.pos[i] = (llama_pos) t; + batch.n_seq_id[i] = 1; + batch.seq_id[i][0] = (llama_seq_id) s; + batch.logits[i] = 1; + } + } + const int32_t rc = llama_decode(ctx, batch); + assert(rc == 0 && "J: batched decode"); + + double worst = 0.0; + int32_t i = 0; + for (size_t s = 0; s < seqs.size(); ++s) { + for (size_t t = 0; t < seqs[s].size(); ++t, ++i) { + const float * p = llama_get_logits_ith(ctx, i); + assert(p != nullptr && "J: batched logits"); + 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))); + } + } + llama_batch_free(batch); + llama_free(ctx); + return worst; +} + int main(int argc, char ** argv) { if (argc < 2) { fprintf(stderr, "usage: %s \n", argv[0]); @@ -184,9 +249,29 @@ int main(int argc, char ** argv) { assert(std::isfinite(z) && z > 0.0 && "I: softmax denominator must be finite and positive"); fprintf(stderr, "test-esn-inference: I OK (softmax Z = %.6g, lmax = %.6g)\n", z, (double) lmax); + // --- J. batch consistency --------------------------------------------- + // An odd, non-power-of-two length so the multi-token output stacking + // sees uneven splits. + std::vector seq_p, seq_q; + for (int t = 0; t < 23; ++t) { + seq_p.push_back((llama_token) ((7 * t + 3) % n_vocab)); + seq_q.push_back((llama_token) ((11 * t + 5) % n_vocab)); + } + 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"); + fprintf(stderr, "test-esn-inference: J OK (batched vs stepwise, rel. max|Δ|: 1 seq %.3g, 2 seqs %.3g)\n", + err_one, err_two); + llama_model_free(model); llama_backend_free(); - fprintf(stderr, "test-esn-inference: PASSED (A..I)\n"); + fprintf(stderr, "test-esn-inference: PASSED (A..J)\n"); return EXIT_SUCCESS; } diff --git a/tests/test-esn.cpp b/tests/test-esn.cpp index b88c40d050f5..e95dd1eceadf 100644 --- a/tests/test-esn.cpp +++ b/tests/test-esn.cpp @@ -74,7 +74,7 @@ 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.op == GGML_OP_MUL_MAT); + 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.op == GGML_OP_ADD); @@ -445,7 +445,22 @@ int main() { std::cout << "PASSED\n"; } - std::cout << "\nAll " << 23 << " ESN tests passed successfully!\n"; + // ------------------------------------------------------------------ // + // Test 24: feedback requires the esn.feedback_token definition + // ------------------------------------------------------------------ // + { + std::cout << "Test 24: validate_esn_params() – feedback without feedback_token rejected... "; + llama_hparams h = make_valid_esn_hparams(); + h.esn_feedback_scaling = 0.5f; + bool threw = false; + try { h.validate_esn_params(); } catch (const std::invalid_argument &) { threw = true; } + assert(threw); + h.esn_feedback_token = true; + h.validate_esn_params(); + std::cout << "PASSED\n"; + } + + std::cout << "\nAll " << 24 << " ESN tests passed successfully!\n"; // Summary of ESN architecture capabilities std::cout << "\nESN Architecture Features:\n"; diff --git a/tests/test-sampling.cpp b/tests/test-sampling.cpp index 7cd96c5cd351..3e4490906afb 100644 --- a/tests/test-sampling.cpp +++ b/tests/test-sampling.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include diff --git a/tools/mtmd/deprecation-warning.cpp b/tools/mtmd/deprecation-warning.cpp index dded0a56af96..c352ceee50ae 100644 --- a/tools/mtmd/deprecation-warning.cpp +++ b/tools/mtmd/deprecation-warning.cpp @@ -1,4 +1,5 @@ #include +#include #include int main(int argc, char** argv) { diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index 4d053895cdae..e813a4ecf4f8 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -8,6 +8,7 @@ #include #include #include +#include // most of the code here is copied from whisper.cpp diff --git a/tools/server/server.cpp b/tools/server/server.cpp index a21147613db0..122ce4eb1dde 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -2575,6 +2575,7 @@ struct server_context { // if context shifting is disabled, make sure that we don't run out of context if (!params_base.ctx_shift && slot.n_past + 1 >= slot.n_ctx) { + slot.truncated = true; slot.stop = STOP_TYPE_LIMIT; slot.has_next_token = false; diff --git a/tools/server/tests/unit/test_ctx_shift.py b/tools/server/tests/unit/test_ctx_shift.py index 92e49f2bb05a..a1eaa9646d3e 100644 --- a/tools/server/tests/unit/test_ctx_shift.py +++ b/tools/server/tests/unit/test_ctx_shift.py @@ -40,7 +40,7 @@ def test_ctx_shift_enabled(): @pytest.mark.parametrize("n_predict,n_token_output,truncated", [ (64, 64, False), - (-1, 120, True), + (-1, 248, True), # 8 tokens prompt + 248 tokens generated = 256 tokens total ]) def test_ctx_shift_disabled_short_prompt(n_predict: int, n_token_output: int, truncated: bool): global server