Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ esn_output_weights.weight [n_vocab, reservoir_size]
esn_feedback_weights.weight [n_vocab, reservoir_size] (optional, row per fed-back token)
esn_input_bias.weight [reservoir_size] (optional)
esn_reservoir_bias.weight [reservoir_size] (optional)
esn_input_table.weight [n_vocab, reservoir_size] (optional, input drive per token)
```

## Build Commands
Expand Down Expand Up @@ -125,6 +126,11 @@ python scripts/esn_training.py --reservoir-size 8192 --reg-grid 1,10,100,1000 \
--outtype q4_0 --train-data corpus.txt --output model.gguf
```

`esn_training.py` stores each token's whole input drive as `esn_input_table`
(`--no-input-table` to omit it); with token inputs the graph reads it instead
of computing W_in·E + biases + feedback. The CPU `tanh`/`sigmoid` are
branch-free so they vectorize (`tests/test-esn-activations.cpp` checks them).

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`).
Expand Down
58 changes: 55 additions & 3 deletions docs/esn.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ training and inference run the same recurrence.
| `esn_feedback_weights` | `[n_vocab, reservoir_size]` | Output-to-reservoir feedback, one row per token (optional) |
| `esn_input_bias` | `[reservoir_size]` | Input projection bias (optional) |
| `esn_reservoir_bias` | `[reservoir_size]` | Reservoir activation bias (optional) |
| `esn_input_table` | `[n_vocab, reservoir_size]` | Whole input drive of each token, read instead of computing it from the tensors above (optional; see below) |

## Implementation Details

Expand All @@ -96,6 +97,10 @@ The ESN forward pass (`llm_build_esn` in `src/llama-model.cpp`) consists of:
`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)

With token inputs, steps 1 and 2 depend on the token alone. When the
model has `esn_input_table`, its row for each token replaces them (one
`get_rows`); embedding inputs still take steps 1 and 2
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)`, added to the input drive
Expand Down Expand Up @@ -367,11 +372,16 @@ build/bin/test-esn-inference /tmp/esn-smoke.gguf
Static test coverage (`tests/test-esn.cpp`):
- Architecture recognition and name mapping
- Recurrent / hybrid / diffusion classification
- Tensor info mappings for all 6 ESN tensors (weights + biases + feedback)
- Tensor info mappings for all 7 ESN tensors (weights + biases + feedback
+ input table)
- Hyperparameter defaults (base + extended)
- Tensor name generation
- `n_embd_s()` returns `reservoir_size` for ESN models

Activation accuracy (`tests/test-esn-activations.cpp`, a CTest): the CPU
backend's `tanh` and `sigmoid` against double-precision references, special
values, and multi-row / multi-thread consistency.

End-to-end inference coverage (`tests/test-esn-inference.cpp`):
- GGUF metadata & tensor-shape loading for `arch=esn`
- `llama_memory_recurrent` allocation sized by `n_embd_s()`
Expand Down Expand Up @@ -411,6 +421,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 |
| No input table | `--no-input-table` | (off) | Do not store `esn_input_table` (`n_vocab * reservoir_size` floats; inference then computes the input drive) |
| Reservoir type | `--outtype` | `f32` | `f16`, `q8_0` or `q4_0` (16, 8.5 or 4.5 bits per weight) shrink the reservoir and its per-token read; the quantized types need a reservoir size that is a multiple of 32 |

### Training Process
Expand Down Expand Up @@ -514,13 +525,54 @@ Both leave the logits bit-identical. Stacking costs nothing measurable when
the states stay in cache (R = 256) or when reading `W_res` dominates
(R = 8192).

Batched and token-by-token decoding of the same text take different matmul
kernels for `W_in`, so their logits differ by rounding (~1e-5 with an F32
Without an input table, batched and token-by-token decoding of the same
text take different matmul kernels for `W_in`, so their logits differ by rounding (~1e-5 with an F32
reservoir). With a Q8_0 or Q4_0 reservoir that rounding can flip the
quantization of one state value, after which the later logits of that
sequence differ visibly (up to 0.1 relative to the largest logit in one
`test-esn-inference` sequence).

### Vectorized Activations and the Input Table

At small and medium reservoirs, a token's time went mostly to two things
other than reading `W_res`:

- **The activation.** The CPU backend computed `tanh` with libm's scalar
`tanhf`, about 20 ns per element here: at R = 1024 it was 14 % of the
single-thread instructions, more than everything but the `W_res` matvec.
A state is one row, so the op also ran on one thread while the others
waited. `tanh` and `sigmoid` in `ggml/src/ggml-cpu/unary-ops.cpp` are now
branch-free (a minimax polynomial below |x| = 0.625, an inline `exp`
above), so the compiler vectorizes them: 0.8 ns per element with AVX2,
within 1.2 ulp of `tanh` and 2 ulp of the logistic function
(`tests/test-esn-activations.cpp`), like libm's. This applies to every
model that uses `ggml_tanh` or `ggml_sigmoid` on the CPU.
- **Graph nodes.** A decode step is a short chain of small ops, and each
op ends with a barrier across threads. The input drive took up to seven
of them (projection, scale, two bias adds, feedback lookup, scale, add)
although it depends on the token alone; `scripts/esn_training.py` now
stores it per token as `esn_input_table` (`--no-input-table` to omit it),
and the graph reads it with one `get_rows`. A scale by 1 is also no
longer emitted. For the default 256-token byte vocabulary the table adds
1 KiB per reservoir unit to the GGUF (+60 % at R = 256 Q4_0, +11 % at
R = 2048 F32).

Before (libm `tanhf`, no table) → after, on the same machine (4-thread CPU,
medians of eight interleaved `llama-bench -r 3` runs; `--use-bias
--leaking-rate 0.5` reservoirs, Q4_0 at R ≤ 1024, F32 at R = 2048, and the
R = 8192 Q4_0 model of the next table without a table):

| R | 256 | 1024 | 2048 | 8192 |
|---|---:|---:|---:|---:|
| pp512 (tok/s) | 64846 → 123743 | 20361 → 37590 | 4784 → 6000 | 893 → 970 |
| tg256 (tok/s) | 25659 → 32764 | 11956 → 18560 | 3470 → 4440 | 766 → 852 |

Most of this is the activation (pp512 +64 % and tg256 +27 % at R = 1024
from it alone); the table adds 16-18 % to R = 1024 decoding and is within
this machine's noise at R = 256. Logits move by rounding only (≤ 1.1e-6
relative to the largest logit for F32 reservoirs; held-out perplexity and
the C++/Python parity are unchanged).

### Quantized Reservoirs

The same corpus and held-out file, with `--embedding-dim 64 --spectral-radius
Expand Down
49 changes: 47 additions & 2 deletions ggml/src/ggml-cpu/unary-ops.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
#include "unary-ops.h"

#include <cstdint>
#include <cstring>

static inline float op_abs(float x) {
return fabsf(x);
}
Expand All @@ -16,8 +19,49 @@ static inline float op_step(float x) {
return (x > 0.f) ? 1.f : 0.f;
}

// expf without a libm call, so that the loops in tanh and sigmoid below
// auto-vectorize: x = n*ln2 + r with |r| <= ln2/2, exp(r) by the Cephes
// polynomial and n added to the exponent bits. Within 1 ulp of exp on the
// clamped range [-86.6, 88.3], which keeps 2^n a normal float; NaN maps to
// the lower bound (callers that care propagate it themselves).
static inline float op_expf_poly(float x) {
x = x > -86.6f ? x : -86.6f;
x = x < 88.3f ? x : 88.3f;
const float n = (x * 1.44269504088896341f + 12582912.0f) - 12582912.0f; // round to nearest
const float r = (x - n * 0.693359375f) + n * 2.12194440e-4f; // x - n*ln2 in two parts
float p = 1.9875691500e-4f;
p = p * r + 1.3981999507e-3f;
p = p * r + 8.3334519073e-3f;
p = p * r + 4.1665795894e-2f;
p = p * r + 1.6666665459e-1f;
p = p * r + 5.0000001201e-1f;
p = (p * r) * r + r + 1.0f;
int32_t bits;
memcpy(&bits, &p, sizeof(bits));
bits += (int32_t) n << 23;
memcpy(&p, &bits, sizeof(p));
return p;
}

// Branch-free tanh, within 1 ulp like libm's tanhf but vectorizable (scalar
// tanhf dominates small recurrent graphs, e.g. echo state networks).
// |x| < 0.625: x*P(x^2), a minimax fit of tanh(x)/x; above it
// 1 - 2/(exp(2|x|) + 1), whose cancellation is harmless there. |x| is capped
// at 10, past where tanh rounds to 1.
static inline float op_tanh(float x) {
return tanhf(x);
const float ax = fabsf(x);
const float a = ax < 10.0f ? ax : 10.0f;
const float a2 = a * a;
float q = 2.1286243572831154e-3f;
q = q * a2 - 8.15926119685173e-3f;
q = q * a2 + 2.169189229607582e-2f;
q = q * a2 - 5.394471436738968e-2f;
q = q * a2 + 1.3333183526992798e-1f;
q = q * a2 - 3.33333283662796e-1f;
const float small = (q * a2) * a + a;
const float large = 1.0f - 2.0f / (op_expf_poly(2.0f * a) + 1.0f);
const float t = copysignf(a < 0.625f ? small : large, x);
return x != x ? x : t;
}

static inline float op_elu(float x) {
Expand All @@ -29,7 +73,8 @@ static inline float op_relu(float x) {
}

static inline float op_sigmoid(float x) {
return 1.f / (1.f + expf(-x));
const float s = 1.f / (1.f + op_expf_poly(-x));
return x != x ? x : s;
}

static inline float op_hardsigmoid(float x) {
Expand Down
26 changes: 24 additions & 2 deletions scripts/esn_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,16 @@ def _input_drive(self, embeddings: np.ndarray, tokens: Optional[np.ndarray]) ->
drive += self.config.feedback_scaling * self.W_fb[tokens]
return drive

def input_table(self) -> np.ndarray:
"""
The input drive of every token, [vocab_size, reservoir_size].

With token inputs, _input_drive depends on the token alone, so
save_gguf stores it per token and llm_build_esn reads each token's
drive with one row lookup instead of computing it.
"""
return self._input_drive(self.tok_embd.T, np.arange(self.config.vocab_size))

def forward(
self,
embeddings: np.ndarray,
Expand Down Expand Up @@ -851,7 +861,7 @@ def online_train_sequence(
"final_state": state.copy(),
}

def save_gguf(self, path: str) -> None:
def save_gguf(self, path: str, input_table: bool = True) -> None:
"""
Save the ESN model as a GGUF file compatible with esn.cpp's
``llm_build_esn`` graph builder.
Expand Down Expand Up @@ -880,6 +890,8 @@ def save_gguf(self, path: str) -> None:
- ``esn_feedback_weights.weight`` [reservoir_size, n_vocab] (optional)
- ``esn_input_bias.weight`` (optional)
- ``esn_reservoir_bias.weight`` (optional)
- ``esn_input_table.weight`` [reservoir_size, n_vocab]
(unless input_table=False; see input_table())
"""
if not self._initialized:
raise RuntimeError("ESN not initialized. Call initialize() first.")
Expand Down Expand Up @@ -960,6 +972,8 @@ def save_gguf(self, path: str) -> None:
# -> numpy (n_vocab, reservoir) [matches training layout]
# esn_input_bias.weight C++ {reservoir} [1-D]
# esn_reservoir_bias.weight C++ {reservoir} [1-D]
# esn_input_table.weight C++ {reservoir, n_vocab}
# -> numpy (n_vocab, reservoir)
def _f32(x: np.ndarray) -> np.ndarray:
return np.ascontiguousarray(x, dtype=np.float32)

Expand All @@ -983,6 +997,10 @@ def _f32(x: np.ndarray) -> np.ndarray:
writer.add_tensor("esn_input_bias.weight", _f32(self.b_in))
if self.b_res is not None:
writer.add_tensor("esn_reservoir_bias.weight", _f32(self.b_res))
if input_table:
# Read instead of W_in, the biases and W_fb for token inputs; those
# stay in the file for embedding inputs.
writer.add_tensor("esn_input_table.weight", _f32(self.input_table()))

writer.write_header_to_file()
writer.write_kv_data_to_file()
Expand Down Expand Up @@ -1189,6 +1207,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("--no-input-table", action="store_true",
help="Do not store the per-token input drive (vocab_size x "
"reservoir_size floats) that inference reads instead of "
"computing it")
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 "
Expand Down Expand Up @@ -1352,7 +1374,7 @@ def main():
logger.info(f"Final training accuracy: {accuracy:.4f}")

# Save to GGUF
esn.save_gguf(args.output)
esn.save_gguf(args.output, input_table=not args.no_input_table)
logger.info(f"\nModel saved to {args.output}")
logger.info("\nTo use with llama.cpp:")
logger.info(f" ./llama-cli -m {args.output} -p \"Your prompt here\"")
Expand Down
2 changes: 2 additions & 0 deletions src/llama-arch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2184,6 +2184,7 @@ static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_N
{ LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, "esn_feedback_weights" },
{ LLM_TENSOR_ESN_INPUT_BIAS, "esn_input_bias" },
{ LLM_TENSOR_ESN_RESERVOIR_BIAS, "esn_reservoir_bias" },
{ LLM_TENSOR_ESN_INPUT_TABLE, "esn_input_table" },
},
},
{
Expand Down Expand Up @@ -2476,6 +2477,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{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}},
};

LLM_KV::LLM_KV(llm_arch arch, const char * suffix) : arch(arch), suffix(suffix) {}
Expand Down
1 change: 1 addition & 0 deletions src/llama-arch.h
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ enum llm_tensor {
LLM_TENSOR_ESN_FEEDBACK_WEIGHTS, // output-to-reservoir feedback
LLM_TENSOR_ESN_INPUT_BIAS, // reservoir input bias
LLM_TENSOR_ESN_RESERVOIR_BIAS, // reservoir bias
LLM_TENSOR_ESN_INPUT_TABLE, // precomputed per-token input drive
};

enum llm_tensor_layer {
Expand Down
68 changes: 43 additions & 25 deletions src/llama-model.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6065,6 +6065,11 @@ bool llama_model::load_tensors(llama_model_loader & ml) {
// 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);

// 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);
} break;
default:
throw std::runtime_error("unknown architecture");
Expand Down Expand Up @@ -19470,32 +19475,45 @@ struct llm_build_esn : public llm_graph_context_mamba {
reservoir_state = ggml_reshape_2d(ctx0, reservoir_state, reservoir_size, n_seqs);
cb(reservoir_state, "esn_state", -1);

// 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.)
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
// generation and the true one in training (teacher forcing), so
// scripts/esn_training.py runs the same recurrence. Being a row lookup
// that does not depend on the state, it is added to the input drive
// for all timesteps at once.
if (model.layers[0].wv && feedback_scaling > 0.0f) {
GGML_ASSERT(res->t_tokens != nullptr && "ESN output feedback needs token inputs, not embeddings");
// The input drive s_in·W_in·u(t) + b_in + b_res + s_fb·W_fb·y(t-1)
// does not depend on the state, so it is computed for all timesteps
// at once. y(t-1), the one-hot of the token emitted at t-1, is this
// step's input token: the sampled token in generation and the true
// one in training (teacher forcing), so scripts/esn_training.py runs
// the same recurrence.
//
// With token inputs the drive depends on the token alone, and a model
// 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.
ggml_tensor * u = nullptr;
if (model.layers[0].esn_input_table && res->t_tokens) {
// {reservoir_size, n_vocab} rows -> {reservoir_size, n_tokens}
ggml_tensor * fb = ggml_get_rows(ctx0, model.layers[0].wv, res->t_tokens);
u = ggml_add(ctx0, u, ggml_scale(ctx0, fb, feedback_scaling));
u = 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);
if (hparams.esn_input_scaling != 1.0f) {
u = ggml_scale(ctx0, u, hparams.esn_input_scaling);
}
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);
}
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);
if (feedback_scaling != 1.0f) {
fb = ggml_scale(ctx0, fb, feedback_scaling);
}
u = ggml_add(ctx0, u, fb);
}
}
cb(u, "esn_input_proj", -1);

Expand Down
3 changes: 3 additions & 0 deletions src/llama-model.h
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,9 @@ struct llama_layer {
struct ggml_tensor * ssm_conv1d_b = nullptr;
struct ggml_tensor * ssm_dt_b = nullptr;

// esn
struct ggml_tensor * esn_input_table = nullptr;

// rwkv
struct ggml_tensor * time_mix_w1 = nullptr;
struct ggml_tensor * time_mix_w2 = nullptr;
Expand Down
Loading
Loading