diff --git a/CLAUDE.md b/CLAUDE.md index ce903e0508c0..b30fe4fea4fa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,9 +119,10 @@ python scripts/esn_training.py --config config.json # Initialize only (no training) python scripts/esn_training.py --init-only --output untrained.gguf -# Large reservoir: pick λ on held-out data, store W_res as F16 +# Large reservoir: pick λ on held-out data, store W_res as Q4_0 (f16 and +# q8_0 also work; the readout is trained on the rounded reservoir) python scripts/esn_training.py --reservoir-size 8192 --reg-grid 1,10,100,1000 \ - --outtype f16 --train-data corpus.txt --output model.gguf + --outtype q4_0 --train-data corpus.txt --output model.gguf ``` Batch training holds out `--val-fraction` (default 10%) of the sequences to diff --git a/docs/esn.md b/docs/esn.md index 5d213eee21b6..e3247286c1ee 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -90,24 +90,24 @@ ESNs are implemented as a recurrent architecture in llama.cpp, leveraging the ex The ESN forward pass (`llm_build_esn` in `src/llama-model.cpp`) consists of: 1. **Input Projection**: `W_in * input_embeddings`, scaled by `esn_input_scaling`, - plus optional `esn_input_bias` + plus the optional `esn_input_bias` and `esn_reservoir_bias` (both are + constant over time, so they are added once per batch, not per timestep) 2. **Optional Feedback**: when `esn_feedback_scaling > 0` and `esn_feedback_weights` is loaded, add `esn_feedback_scaling` times the `W_fb` row of each input token (a `get_rows`, done for the whole batch before the recurrence because it does not depend on the state) 3. **State Retrieval**: Get previous reservoir state via `llama_memory_recurrent_context::get_s_l(0)` and `build_rs()` -4. **Recurrent Projection**: `W_res * x(t)` -5. **Optional Reservoir Bias**: Add `esn_reservoir_bias` -6. **Activation**: Apply the selected activation (`esn_activation_type`: +4. **Recurrent Projection**: `W_res * x(t)`, added to the input drive +5. **Activation**: Apply the selected activation (`esn_activation_type`: tanh, sigmoid, or leaky ReLU with slope 0.01, matching the training script) -7. **Leaky Integration**: `x(t+1) = (1-α)*x(t) + α*f(...)` (skipped when α = 1) -8. **State Storage**: `ggml_cpy` new state back to `esn_states_all` at +6. **Leaky Integration**: `x(t+1) = (1-α)*x(t) + α*f(...)` (skipped when α = 1) +7. **State Storage**: `ggml_cpy` new state back to `esn_states_all` at `kv_head * reservoir_size` -9. **Output Stacking**: for multi-token batches, the per-token states are +8. **Output Stacking**: for multi-token batches, the per-token states are concatenated in a balanced binary tree (O(n log n) bytes copied rather than O(n²) for a left-to-right chain) -10. **Output Normalization & Projection**: RMS norm, then +9. **Output Normalization & Projection**: RMS norm, then `W_out * reservoir_state → vocabulary_logits` Notes on features that live outside the inference path: @@ -146,7 +146,7 @@ esn.vocab_size = esn.embedding_length = esn.context_length = -# ESN hyperparameters +# ESN hyperparameters esn.reservoir_size = esn.spectral_radius = esn.sparsity = @@ -162,7 +162,7 @@ esn.attention.layernorm_rms_eps = ``` # Core tensors token_embd.weight # [n_embd, n_vocab] -output_norm.weight # [reservoir_size] +output_norm.weight # [reservoir_size] esn_input_weights.weight # [reservoir_size, n_embd] esn_reservoir_weights.weight # [reservoir_size, reservoir_size] esn_output_weights.weight # [n_vocab, reservoir_size] @@ -190,7 +190,7 @@ if (llama_model_arch(model) == LLM_ARCH_ESN) { ```cpp // Create context with recurrent memory -auto ctx_params = llama_context_default_params(); +auto ctx_params = llama_context_default_params(); ctx_params.n_ctx = 2048; auto* ctx = llama_new_context_with_model(model, ctx_params); @@ -227,7 +227,7 @@ float* logits = llama_get_logits_ith(ctx, batch.n_tokens - 1); ### Memory Usage ESN memory usage scales with: -- Reservoir size squared (for W_res) +- Reservoir size squared (for W_res) - Reservoir × embedding dimension (for W_in) - Vocabulary × reservoir size (for W_out) - Recurrent state storage per sequence @@ -267,7 +267,7 @@ ESNs exhibit favorable scaling properties: ### Best Practices 1. **Spectral Radius**: Keep < 1.0 for stability, typically 0.8-0.95 -2. **Reservoir Size**: Should be 10-100x larger than input/output dimensions +2. **Reservoir Size**: Should be 10-100x larger than input/output dimensions 3. **Sparsity**: 5-20% connectivity often optimal 4. **Leaking Rate**: Use < 1.0 for better temporal processing @@ -276,7 +276,7 @@ ESNs exhibit favorable scaling properties: ### Supported Features - ✅ Standard model loading and inference -- ✅ Batch processing +- ✅ Batch processing - ✅ Sequence management (copy, clear, remove) - ✅ State serialization/deserialization - ✅ Multi-backend support (CPU, GPU) @@ -288,7 +288,7 @@ ESNs exhibit favorable scaling properties: ESN models integrate seamlessly with: - **llama-server**: OpenAI-compatible API - **llama-cli**: Command-line interface -- **llama-bench**: Performance benchmarking +- **llama-bench**: Performance benchmarking - **llama-quantize**: Model quantization - **Python bindings**: Through llama-cpp-python @@ -409,7 +409,7 @@ python scripts/esn_training.py --init-only --reservoir-size 2048 --output untrai | Validation split | `--val-fraction` | 0.1 | Sequences held out to pick lambda and fit the temperature | | Lambda search | `--reg-grid` | (off) | Comma-separated lambdas, chosen by held-out NLL | | No calibration | `--no-calibrate` | (off) | Export raw ridge outputs as logits | -| Reservoir type | `--outtype` | `f32` | `f16` halves the reservoir's size and its per-token read | +| Reservoir type | `--outtype` | `f32` | `f16`, `q8_0` or `q4_0` (16, 8.5 or 4.5 bits per weight) shrink the reservoir and its per-token read; the quantized types need a reservoir size that is a multiple of 32 | ### Training Process @@ -432,8 +432,23 @@ ESN training uses ridge regression on output weights only: 5. **Refit and Export**: the readout is refit on training + held-out data with the chosen λ and saved as GGUF for llama.cpp inference -With `--outtype f16`, `W_res` is rounded to F16 before state collection, so -the readout is trained on exactly the reservoir inference runs. +With `--outtype f16`, `q8_0` or `q4_0`, `W_res` is rounded to that type +before state collection, so the readout is trained on the reservoir +inference runs. The reservoir is random, so rounding it costs little; what +matters is that the readout sees the rounded one. Quantizing an F32-trained +model afterwards (as `llama-quantize` would) puts a different reservoir +under the readout: at R=2048 that took held-out entropy from 4.77 to 6.86 +bits/byte, where training on the Q4_0 reservoir gives 4.78. + +ggml's CPU backend also rounds the state vector before each `W_res` +product: to F16 for an F16 reservoir, and to Q8_0 blocks (`rint(x * 127 / +amax)` per 32 values, with the scale stored as F16) for Q8_0 and Q4_0 ones. +State collection rounds it the same way, so the Python validation numbers +are what llama.cpp computes on CPU: logits agree to ~1e-6 for Q8_0 and Q4_0 +reservoirs, where unrounded states differed by ~5e-3 and changed the +next-byte argmax at 2-22 % of positions. An F16 reservoir still differs by +~1e-4 at some positions, where a state element sits on an F16 rounding +boundary. Other backends round the vector their own way. ### Measured Effect of the Training and Inference Optimizations @@ -471,6 +486,27 @@ script had not finished initializing it after 30 minutes. That this barely improves on R=8192 shows the ~67k-sample corpus, not the reservoir, is the limit at this scale. +### Quantized Reservoirs + +The same corpus and held-out file, with `--embedding-dim 64 --spectral-radius +0.9 --leaking-rate 0.5 --use-bias --seq-length 256 --washout 32 --reg-grid +0.1,1,10,100` (674 windows; λ=1 was selected for every model), 4-thread CPU, +`llama-bench -r 3`: + +| | R=2048 F32 | R=2048 F16 | R=2048 Q8_0 | R=2048 Q4_0 | R=8192 F32 | R=8192 F16 | R=8192 Q8_0 | R=8192 Q4_0 | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| GGUF size | 19 MB | 11 MB | 7 MB | 5 MB | 267 MB | 139 MB | 79 MB | 47 MB | +| held-out bits/byte | 4.772 | 4.772 | 4.779 | 4.783 | 4.331 | 4.330 | 4.336 | 4.346 | +| held-out perplexity | 27.3 | 27.3 | 27.5 | 27.5 | 20.1 | 20.1 | 20.2 | 20.3 | +| held-out argmax accuracy | 38.5 % | 38.5 % | 38.7 % | 38.6 % | 46.5 % | 46.4 % | 46.2 % | 46.4 % | +| pp512 (tok/s) | 4935 | 6982 | 6979 | 7976 | 244 | 592 | 826 | 951 | +| tg128 (tok/s) | 3796 | 5174 | 5770 | 6677 | 220 | 548 | 758 | 922 | + +Training time does not depend on the type (47-48 s at R=2048, 448-480 s +at R=8192). At R=8192 a token's work is mostly reading `W_res`, so Q4_0 +generates 4.2x faster than F32 and 1.7x faster than F16, for 0.015 +bits/byte. + ## Related research directions (not part of this implementation) The items below are a **separate research roadmap**, not pending work on @@ -551,4 +587,4 @@ Token t arrives 1. Jaeger, H. (2001). The "echo state" approach to analysing and training recurrent neural networks. GMD Technical Report 148. 2. Lukoševičius, M., & Jaeger, H. (2009). Reservoir computing approaches to recurrent neural network training. Computer Science Review, 3(3), 127-149. -3. Verstraeten, D., Schrauwen, B., D'Haene, M., & Stroobandt, D. (2007). An experimental unification of reservoir computing methods. Neural networks, 20(3), 391-403. \ No newline at end of file +3. Verstraeten, D., Schrauwen, B., D'Haene, M., & Stroobandt, D. (2007). An experimental unification of reservoir computing methods. Neural networks, 20(3), 391-403. diff --git a/scripts/esn_training.py b/scripts/esn_training.py index 63e9cdd9729d..10a8ed561544 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -42,7 +42,7 @@ sys.path.insert(0, str(_GGUF_PY)) try: - from gguf import GGUFWriter + from gguf import GGML_QUANT_SIZES, GGMLQuantizationType, GGUFWriter, LlamaFileType, quants except ImportError as e: raise SystemExit( "The 'gguf' package is required. Install the one bundled with this\n" @@ -60,6 +60,18 @@ class ESNConfig: """Configuration for Echo State Network.""" + # Online-learning metadata, set by main() only when it is to be embedded in + # the GGUF. Class-level defaults keep them out of __dict__ (and so out of + # to_json/from_json) unless they are actually set. + online_learning: bool = False + online_lr: float = 0.0 + online_reg: float = 0.0 + online_buffer_size: int = 0 + online_update_mode: int = 0 + online_decay_rate: float = 0.0 + freeze_reservoir: bool = False + replay_window: int = 0 + def __init__( self, vocab_size: int = 32000, @@ -135,6 +147,50 @@ def get_activation_fn(activation_type: int) -> Callable: # Bound on the floats held per batch of reservoir states during training. _STATE_BATCH_FLOATS = 1 << 27 +# Storage types for W_res (--outtype), with the general.file_type each gives +# the model: W_res holds nearly all of its parameters. +RESERVOIR_TYPES = { + "f32": (GGMLQuantizationType.F32, LlamaFileType.ALL_F32), + "f16": (GGMLQuantizationType.F16, LlamaFileType.MOSTLY_F16), + "q8_0": (GGMLQuantizationType.Q8_0, LlamaFileType.MOSTLY_Q8_0), + "q4_0": (GGMLQuantizationType.Q4_0, LlamaFileType.MOSTLY_Q4_0), +} + +# Rows of W_res quantized at a time, bounding gguf-py's float temporaries. +_QUANT_CHUNK_FLOATS = 1 << 24 + + +def quantize_rows(W: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray: + """W [rows, cols] in qtype's GGUF storage layout, chunked by rows.""" + if qtype == GGMLQuantizationType.F32: + return np.ascontiguousarray(W, dtype=np.float32) + if qtype == GGMLQuantizationType.F16: + return np.ascontiguousarray(W, dtype=np.float16) + chunk = max(1, _QUANT_CHUNK_FLOATS // W.shape[1]) + return np.concatenate([quants.quantize(np.ascontiguousarray(W[r:r + chunk], dtype=np.float32), qtype) + for r in range(0, len(W), chunk)]) + + +def round_like_vec_dot(x: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray: + """ + Round reservoir states x [..., R] the way ggml's CPU backend converts the + vector side of ggml_mul_mat(W_res, x) to W_res's vec_dot_type, so that + training sees the states inference computes: F16 for an F16 reservoir, + Q8_0 blocks for Q8_0 and Q4_0 ones (quantize_row_q8_0: q = rint(x * 127 / + amax), scale amax / 127 stored as F16). + """ + if qtype == GGMLQuantizationType.F32: + return x + if qtype == GGMLQuantizationType.F16: + return x.astype(np.float16).astype(np.float32) + blocks = x.reshape(*x.shape[:-1], -1, 32) + amax = np.abs(blocks).max(axis=-1, keepdims=True) + with np.errstate(divide="ignore"): + iscale = np.where(amax > 0, np.float32(127) / amax, np.float32(0)) + q = np.rint(blocks * iscale) + scale = (amax / np.float32(127)).astype(np.float16).astype(np.float32) + return (q * scale).reshape(x.shape) + def spectral_radius(W: np.ndarray, krylov_dim: int = 128, seed: int = 0) -> float: """Largest eigenvalue modulus of a square matrix. @@ -237,8 +293,8 @@ def __init__(self, config: ESNConfig): # probability scale; inference treats it as logits. train() fits this # scale on held-out data and save_gguf() folds it into W_out. self.output_temperature = 1.0 - # dtype the reservoir matrix is stored in by save_gguf(). - self.reservoir_dtype = np.float32 + # Type the reservoir matrix is stored in by save_gguf(). + self.reservoir_type = "f32" self._initialized = False @@ -391,7 +447,7 @@ def forward( for t in range(n_tokens): # Reservoir recurrence - reservoir_input = self.W_res @ x + drive[t] + reservoir_input = self.W_res @ self._vec_dot_state(x) + drive[t] # Add noise if specified if self.config.noise_level > 0: @@ -440,7 +496,7 @@ def forward_batch(self, embeddings: np.ndarray, tokens: Optional[np.ndarray] = N state = np.zeros((batch, size), dtype=np.float32) states = np.empty((batch, n_tokens, size), dtype=np.float32) for t in range(n_tokens): - pre = state @ self.W_res.T + pre = self._vec_dot_state(state) @ self.W_res.T pre += drive[:, t] if self.config.noise_level > 0: pre += (self.rng.standard_normal((batch, size)).astype(np.float32) @@ -604,11 +660,23 @@ def train( return accuracy - def set_reservoir_dtype(self, dtype) -> None: - """Store W_res as dtype in the GGUF, and round it now so the readout is - trained on the same reservoir that inference will run.""" - self.reservoir_dtype = np.dtype(dtype) - self.W_res = self.W_res.astype(self.reservoir_dtype).astype(np.float32) + def set_reservoir_type(self, name: str) -> None: + """ + Store W_res as one of RESERVOIR_TYPES in the GGUF, and round it now so + the readout is trained on the reservoir that inference will run. From + then on the states fed to W_res are rounded as llama.cpp's CPU backend + rounds them (round_like_vec_dot). + """ + qtype = RESERVOIR_TYPES[name][0] + block = GGML_QUANT_SIZES[qtype][0] + if self.config.reservoir_size % block: + raise ValueError(f"--outtype {name} needs a reservoir size that is a multiple of {block}") + self.reservoir_type = name + if qtype != GGMLQuantizationType.F32: + self.W_res = quants.dequantize(quantize_rows(self.W_res, qtype), qtype).astype(np.float32) + + def _vec_dot_state(self, x: np.ndarray) -> np.ndarray: + return round_like_vec_dot(x, RESERVOIR_TYPES[self.reservoir_type][0]) # ------------------------------------------------------------------ # Online / incremental learning (Phase 3 of ESLLM roadmap) @@ -761,7 +829,7 @@ def online_train_sequence( for t, tgt in enumerate(target_sequence): # Update reservoir state - res_in = self.W_res @ state + drive[t] + res_in = self.W_res @ self._vec_dot_state(state) + drive[t] activated = self.activation_fn(res_in) state = (1 - self.config.leaking_rate) * state + self.config.leaking_rate * activated @@ -822,9 +890,7 @@ def save_gguf(self, path: str) -> None: # General metadata writer.add_name("ESN Model") - # llama_ftype: W_res holds nearly all parameters, so an F16 reservoir - # makes the model MOSTLY_F16 (1); otherwise ALL_F32 (0). - writer.add_file_type(1 if self.reservoir_dtype == np.float16 else 0) + writer.add_file_type(RESERVOIR_TYPES[self.reservoir_type][1]) # Base model dimensions — use the standard key helpers so llama.cpp's # auto-derived KV keys resolve correctly (they map arch -> key). @@ -863,7 +929,7 @@ def save_gguf(self, path: str) -> None: writer.add_uint32("esn.activation_type", self.config.activation_type) writer.add_bool("esn.bidirectional", self.config.bidirectional) - if getattr(self.config, "online_learning", False): + if self.config.online_learning: writer.add_bool("esn.online_learning.enabled", True) writer.add_float32("esn.online_learning.rate", self.config.online_lr) writer.add_float32("esn.online_learning.reg", self.config.online_reg) @@ -898,12 +964,15 @@ def _f32(x: np.ndarray) -> np.ndarray: return np.ascontiguousarray(x, dtype=np.float32) # W_res is the only tensor read once per token for every token, so it - # may be stored as F16 (see set_reservoir_dtype). The fitted softmax - # temperature is folded into W_out so inference needs no extra op. + # may be stored as F16 or quantized (see set_reservoir_type); it was + # already rounded to that type, so this re-quantization is exact. The + # fitted softmax temperature is folded into W_out so inference needs + # no extra op. + res_qtype = RESERVOIR_TYPES[self.reservoir_type][0] writer.add_tensor("token_embd.weight", _f32(self.tok_embd.T)) writer.add_tensor("esn_input_weights.weight", _f32(self.W_in)) - writer.add_tensor("esn_reservoir_weights.weight", - np.ascontiguousarray(self.W_res, dtype=self.reservoir_dtype)) + writer.add_tensor("esn_reservoir_weights.weight", quantize_rows(self.W_res, res_qtype), + raw_dtype=res_qtype) writer.add_tensor("output_norm.weight", _f32(self.output_norm)) writer.add_tensor("esn_output_weights.weight", _f32(self.W_out * self.output_temperature)) @@ -1120,8 +1189,10 @@ def main(): "(picked by held-out NLL); default: --regularization only") parser.add_argument("--no-calibrate", action="store_true", help="Do not fit a softmax temperature (export raw ridge outputs as logits)") - parser.add_argument("--outtype", choices=["f32", "f16"], default="f32", - help="Storage type of the reservoir matrix in the GGUF") + parser.add_argument("--outtype", choices=list(RESERVOIR_TYPES), default="f32", + help="Storage type of the reservoir matrix in the GGUF. The readout " + "is trained on the rounded reservoir; q8_0 and q4_0 need a " + "reservoir size that is a multiple of 32") # Tokenizer parser.add_argument("--tokenizer", choices=["byte", "none"], default="byte", @@ -1201,8 +1272,7 @@ def main(): # Create and initialize ESN esn = ESN(config) esn.initialize() - if args.outtype == "f16": - esn.set_reservoir_dtype(np.float16) + esn.set_reservoir_type(args.outtype) if not args.init_only: # Load or create training data diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 994cb985b3c9..3db88ccefafa 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -19456,9 +19456,14 @@ struct llm_build_esn : public llm_graph_context_mamba { // the create_tensor block above.) ggml_tensor * u = ggml_mul_mat(ctx0, model.layers[0].wq, inpL); u = ggml_scale(ctx0, u, hparams.esn_input_scaling); + // Both biases are constant over time, so they are added to the input + // drive once per ubatch rather than once per timestep. if (model.layers[0].bq) { u = ggml_add(ctx0, u, model.layers[0].bq); } + if (model.layers[0].bk) { + u = ggml_add(ctx0, u, model.layers[0].bk); + } // Output feedback W_fb·y(t-1). y(t-1) is the one-hot of the token // emitted at t-1, i.e. this step's input token: the sampled token in @@ -19506,13 +19511,9 @@ struct llm_build_esn : public llm_graph_context_mamba { // -> [reservoir_size, n_seqs] ggml_tensor * rec = ggml_mul_mat(ctx0, model.layers[0].wk, state); - // Pre-activation = W_res·x + W_in·u + W_fb·y (+ bias) + // Pre-activation = W_res·x + (W_in·u + W_fb·y + b) ggml_tensor * pre = ggml_add(ctx0, rec, u_t); - if (model.layers[0].bk) { - pre = ggml_add(ctx0, pre, model.layers[0].bk); - } - ggml_tensor * activated = apply_esn_activation(pre, activation_type); // Leaky integration (a no-op blend at leaking_rate == 1). diff --git a/tests/test-esn.cpp b/tests/test-esn.cpp index e95dd1eceadf..0e256f03d14f 100644 --- a/tests/test-esn.cpp +++ b/tests/test-esn.cpp @@ -60,7 +60,7 @@ int main() { 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.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").