diff --git a/CLAUDE.md b/CLAUDE.md index b30fe4fea4fa..c59efe25eeb8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 @@ -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`). diff --git a/docs/esn.md b/docs/esn.md index c6a63d3463f0..d41ed63e7595 100644 --- a/docs/esn.md +++ b/docs/esn.md @@ -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 @@ -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 @@ -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()` @@ -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 @@ -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 diff --git a/ggml/src/ggml-cpu/unary-ops.cpp b/ggml/src/ggml-cpu/unary-ops.cpp index cf1a4615d042..a170c4325834 100644 --- a/ggml/src/ggml-cpu/unary-ops.cpp +++ b/ggml/src/ggml-cpu/unary-ops.cpp @@ -1,5 +1,8 @@ #include "unary-ops.h" +#include +#include + static inline float op_abs(float x) { return fabsf(x); } @@ -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) { @@ -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) { diff --git a/scripts/esn_training.py b/scripts/esn_training.py index 10a8ed561544..9007ccb5d1d9 100644 --- a/scripts/esn_training.py +++ b/scripts/esn_training.py @@ -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, @@ -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. @@ -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.") @@ -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) @@ -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() @@ -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 " @@ -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\"") diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index c5de881cf6a1..9c9f61368dad 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -2184,6 +2184,7 @@ static const std::map> 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" }, }, }, { @@ -2476,6 +2477,7 @@ static const std::map 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) {} diff --git a/src/llama-arch.h b/src/llama-arch.h index 90a005ac68a2..0a28953d05eb 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -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 { diff --git a/src/llama-model.cpp b/src/llama-model.cpp index d062e459dd33..a222da284444 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -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"); @@ -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); diff --git a/src/llama-model.h b/src/llama-model.h index eec564e70b69..c99a0d48a202 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -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; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f42506e5e1a8..25f762838f1d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -145,6 +145,10 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) llama_build_and_test(test-grammar-integration.cpp) llama_build_and_test(test-llama-grammar.cpp) llama_build_and_test(test-esn.cpp) + if (NOT GGML_BACKEND_DL) + # calls the CPU backend directly + llama_build_and_test(test-esn-activations.cpp) + endif() # 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-activations.cpp b/tests/test-esn-activations.cpp new file mode 100644 index 000000000000..dd1cb3515f0a --- /dev/null +++ b/tests/test-esn-activations.cpp @@ -0,0 +1,130 @@ +// Accuracy of the ESN reservoir activations on the CPU backend. +// +// ggml-cpu computes tanh and sigmoid branch-free (no libm call) so the loops +// vectorize; the reservoir applies one of them to every state element at +// every timestep. This checks them against double-precision references: +// +// A. tanh within 2 ulp over [-12, 12], and exact at the special values +// (±0, ±inf, NaN, tiny inputs). +// B. sigmoid within 4 ulp over [-80, 80], saturating at ±inf, NaN kept. +// C. The same results with several threads and rows, so the vectorized +// body and the scalar tail of each row agree. + +#ifdef NDEBUG +#undef NDEBUG +#endif + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include + +// Distance in units in the last place of `want` (rounded to float). +static double ulp_err(float got, double want) { + const float w = (float) want; + if (std::isnan(w)) { + return std::isnan(got) ? 0.0 : INFINITY; + } + if (std::isinf(w)) { + return got == w ? 0.0 : INFINITY; + } + const float up = std::nextafter(std::fabs(w), INFINITY) - std::fabs(w); + return std::fabs((double) got - want) / up; +} + +enum class act { tanh, sigmoid }; + +// Apply the activation with ggml to x laid out as [ncols, nrows]. +static std::vector run(act a, const std::vector & x, int64_t ncols, int n_threads) { + const int64_t nrows = (int64_t) x.size() / ncols; + ggml_init_params ip = { /*mem_size*/ 2 * x.size() * sizeof(float) + 4 * ggml_tensor_overhead() + ggml_graph_overhead(), + /*mem_buffer*/ nullptr, /*no_alloc*/ false }; + ggml_context * ctx = ggml_init(ip); + ggml_tensor * in = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ncols, nrows); + memcpy(in->data, x.data(), x.size() * sizeof(float)); + ggml_tensor * out = a == act::tanh ? ggml_tanh(ctx, in) : ggml_sigmoid(ctx, in); + ggml_cgraph * gf = ggml_new_graph(ctx); + ggml_build_forward_expand(gf, out); + const ggml_status st = ggml_graph_compute_with_ctx(ctx, gf, n_threads); + assert(st == GGML_STATUS_SUCCESS); + std::vector y((const float *) out->data, (const float *) out->data + x.size()); + ggml_free(ctx); + return y; +} + +// Evenly spaced bit patterns of the non-negative floats up to `hi`, mirrored. +static std::vector sweep(float hi, int n) { + uint32_t top; + memcpy(&top, &hi, sizeof(top)); + std::vector x; + for (int i = 0; i < n; ++i) { + uint32_t b = (uint32_t) ((uint64_t) top * i / (n - 1)); + float v; + memcpy(&v, &b, sizeof(v)); + x.push_back(v); + x.push_back(-v); + } + return x; +} + +static double ref(act a, float x) { + return a == act::tanh ? std::tanh((double) x) : 1.0 / (1.0 + std::exp(-(double) x)); +} + +static void check(act a, const char * name, float hi, double max_ulp) { + const std::vector x = sweep(hi, 1 << 18); + const std::vector y = run(a, x, (int64_t) x.size(), 1); + double worst = 0.0; + float worst_x = 0.0f; + for (size_t i = 0; i < x.size(); ++i) { + const double e = ulp_err(y[i], ref(a, x[i])); + if (e > worst) { + worst = e; + worst_x = x[i]; + } + } + printf(" %-7s max error %.2f ulp (at x = %g, limit %.0f)\n", name, worst, worst_x, max_ulp); + assert(worst <= max_ulp); + + // C: several rows with an odd length, so each row has a scalar tail, and + // several threads; every element must match the single-row result. + const int64_t ncols = 1027; + const std::vector xs(x.begin(), x.begin() + ncols * 64); + const std::vector one = run(a, xs, (int64_t) xs.size(), 1); + const std::vector rows = run(a, xs, ncols, 4); + assert(memcmp(one.data(), rows.data(), one.size() * sizeof(float)) == 0); +} + +int main() { + printf("test-esn-activations:\n"); + + check(act::tanh, "tanh", 12.0f, 2.0); + { + const std::vector x = { 0.0f, -0.0f, INFINITY, -INFINITY, NAN, 1e-30f, -1e-30f, 1e-40f, 20.0f, -20.0f }; + const std::vector y = run(act::tanh, x, (int64_t) x.size(), 1); + assert(y[0] == 0.0f && !std::signbit(y[0])); + assert(y[1] == 0.0f && std::signbit(y[1])); + assert(y[2] == 1.0f && y[3] == -1.0f); + assert(std::isnan(y[4])); + assert(y[5] == 1e-30f && y[6] == -1e-30f && y[7] == 1e-40f); + assert(y[8] == 1.0f && y[9] == -1.0f); + } + + check(act::sigmoid, "sigmoid", 80.0f, 4.0); + { + const std::vector x = { 0.0f, INFINITY, -INFINITY, NAN, 100.0f }; + const std::vector y = run(act::sigmoid, x, (int64_t) x.size(), 1); + assert(y[0] == 0.5f); + assert(y[1] == 1.0f && y[2] >= 0.0f && y[2] < 1e-37f); + assert(std::isnan(y[3])); + assert(y[4] == 1.0f); + } + + printf("test-esn-activations: PASSED (A..C)\n"); + return 0; +} diff --git a/tests/test-esn.cpp b/tests/test-esn.cpp index 0e256f03d14f..6a08e3fa0de1 100644 --- a/tests/test-esn.cpp +++ b/tests/test-esn.cpp @@ -81,6 +81,9 @@ int main() { 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.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.op == GGML_OP_GET_ROWS); // row per input token std::cout << "PASSED\n"; } @@ -148,6 +151,7 @@ int main() { std::string feedback_name = tn(LLM_TENSOR_ESN_FEEDBACK_WEIGHTS); std::string input_bias = tn(LLM_TENSOR_ESN_INPUT_BIAS); std::string reservoir_bias = tn(LLM_TENSOR_ESN_RESERVOIR_BIAS); + std::string input_table = tn(LLM_TENSOR_ESN_INPUT_TABLE); assert(input_name == "esn_input_weights"); assert(reservoir_name == "esn_reservoir_weights"); @@ -155,6 +159,7 @@ int main() { assert(feedback_name == "esn_feedback_weights"); assert(input_bias == "esn_input_bias"); assert(reservoir_bias == "esn_reservoir_bias"); + assert(input_table == "esn_input_table"); std::cout << "PASSED\n"; }