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