feat(nisps/ml): MLP library with fixed-architecture template + spread-aware RL (meml-wmh)
Stream 2 of the clean-slate rewrite: nisps/ml/ replaces src/memlp/ with a
header-only, heap-free MLP that satisfies nisps::core::MLEngine.
Files (nisps/ml/):
- activations.hpp — ReLU (leaky 0.01 for parity), sigmoid, tanh
- loss.hpp — MSE per-sample (fixes meml-ues double-scaling: returns the
sample's MSE without an extra 1/N multiplication; the training loop
averages explicitly)
- init.hpp — uniform/Xavier/spread-aware weight init
- training.hpp — gradient clip helper (±10.0 matches legacy)
- rl.hpp — move_weights with per-layer Xavier scaling, weight decay
(10% * spread), gaussian noise via the deterministic Rng (matches the
legacy JS sum-of-three-uniforms shape); draw_weights also spread-aware
- stats.hpp — per-layer mean/max/dead/saturating diagnostics
- mlp.hpp — 4-layer (3 hidden + sigmoid output) MLP class with
std::array-backed weights, biases, gradient accumulators, dataset
ring buffer (default 128 examples), loss history (default 4096 iters).
Bias is a separate per-layer parameter — no input-vector mutation.
Flat get_weights/set_weights layout: weights all layers (row-major,
layer order), then biases all layers.
Tests (tests/cpp/, all 50 passing under -Wall -Wextra -Werror -Wpedantic):
- test_mlp_init.cpp — deterministic seeding, spread regimes,
static_assert MLEngine concept satisfied
- test_mlp_inference.cpp — golden hand-computed forward pass match,
sigmoid output range, set_input bounds
- test_mlp_training.cpp — XOR convergence (loss < 0.01 in <2k iters),
ring-buffer eviction
- test_mlp_loss.cpp — meml-ues regression test: reported loss equals
hand-computed average MSE without extra 1/N scaling; sample weights
honoured
- test_mlp_rl.cpp — move_weights respects output_pin_mask (final-layer
rows + biases preserved); spread regimes; grad clear after draw_weights
- test_mlp_serialize.cpp — get_weights/set_weights round-trip preserves
inference exactly; eval_loss is non-mutating; infer_batch matches
individual inference
Verification:
- Clean build, no warnings
- 50 tests pass (22 prior + 28 new)
- No std::vector / new / malloc in nisps/ml/
- All float literals .f-suffixed in code (comments excepted)
2026-04-29 14:55:43 +02:00
|
|
|
// tests/cpp/test_mlp_training.cpp — convergence test on XOR.
|
|
|
|
|
//
|
|
|
|
|
// XOR is the classic minimum non-linear problem: a 2-layer linear net
|
|
|
|
|
// cannot solve it; an MLP with one hidden layer (and a non-linear
|
|
|
|
|
// activation) can. Our 4-layer MLP with sigmoid output is more than enough.
|
|
|
|
|
//
|
|
|
|
|
// We check loss < 0.01 within a generous iteration budget. If this test
|
|
|
|
|
// regresses to taking >1000 iterations, something is wrong with the
|
|
|
|
|
// gradient or weight-update path.
|
|
|
|
|
|
|
|
|
|
#include <array>
|
|
|
|
|
|
|
|
|
|
#include "test_helpers.hpp"
|
|
|
|
|
|
|
|
|
|
#include "../../nisps/ml/mlp.hpp"
|
|
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
|
|
|
|
|
NISPS_TEST(mlp_xor_converges) {
|
|
|
|
|
// Modest network: 2 inputs, [4, 4, 4] hidden, 1 output.
|
|
|
|
|
using M = nisps::ml::MLP<2, 4, 4, 4, 1, 4, 1024>;
|
|
|
|
|
M m(7ull);
|
|
|
|
|
m.draw_weights(1.f); // Xavier-ish; needed for sigmoid output to start reasonable
|
|
|
|
|
|
|
|
|
|
// XOR truth table.
|
|
|
|
|
std::array<std::array<float, 2>, 4> X = {{
|
|
|
|
|
{0.f, 0.f},
|
|
|
|
|
{0.f, 1.f},
|
|
|
|
|
{1.f, 0.f},
|
|
|
|
|
{1.f, 1.f},
|
|
|
|
|
}};
|
|
|
|
|
std::array<std::array<float, 1>, 4> Y = {{
|
|
|
|
|
{0.f},
|
|
|
|
|
{1.f},
|
|
|
|
|
{1.f},
|
|
|
|
|
{0.f},
|
|
|
|
|
}};
|
|
|
|
|
|
|
|
|
|
for (std::size_t i = 0; i < 4u; ++i) {
|
|
|
|
|
m.add_example(std::span<const float>(X[i]), std::span<const float>(Y[i]));
|
|
|
|
|
}
|
|
|
|
|
NISPS_EXPECT(m.example_count() == 4u);
|
|
|
|
|
|
|
|
|
|
// Train. Higher LR + more iterations is fine — the test is "did it
|
|
|
|
|
// converge AT ALL within a generous budget".
|
|
|
|
|
const float final_loss = m.train(/*lr=*/0.5f, /*max_iter=*/2000u, /*min_err=*/0.01f);
|
|
|
|
|
NISPS_EXPECT(final_loss < 0.01f);
|
|
|
|
|
|
|
|
|
|
// Sanity: outputs should be near labels for each input.
|
|
|
|
|
for (std::size_t i = 0; i < 4u; ++i) {
|
|
|
|
|
m.set_input(0, X[i][0]);
|
|
|
|
|
m.set_input(1, X[i][1]);
|
|
|
|
|
m.process();
|
|
|
|
|
const float o = m.outputs()[0];
|
|
|
|
|
NISPS_EXPECT_NEAR(o, Y[i][0], 0.2);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Loss history should record at least one entry.
|
|
|
|
|
NISPS_EXPECT(m.loss_history().size() >= 1u);
|
|
|
|
|
}
|
|
|
|
|
|
feat: curve truth, DriverConfig, real telemetry, engine benchmark
Four items from one workflow, committed together because their build and CI
wiring genuinely interleaves — nisps/CMakeLists.txt, run-all-tests.sh and
ci.yml each carry hunks from two of them, and the stage renumbering (1/5 ->
1/6) touches every line. Splitting would produce commits that do not build,
which is worse than a commit that does four things and says so.
S26 part 2 — the curve declaration now matches reality. params[].curve stays
the mode-wide DEFAULT; a voice_spaces entry may now be {name, curve_overrides}
declaring only the slots where THAT voice space deviates. The 6 modes with one
voice space are byte-identical. The values were derived MECHANICALLY by a new
codegen/curve-audit.ts that models the four idioms a p[N]*p[N] regex misses
(alias form, memlcelium's implicit-counter sq() lambda, loop-generated indices,
smooth_params_), inlines helpers, and RAISES rather than guessing when it
cannot reduce an expression. A drift gate cross-checks 1179 (voice space x
param) slots against engine source on every run and was proved to fail loudly
on three drift classes. Application stays in the engine: nisps/engines,
nisps/pipeline and nisps/core are untouched, generated output is pure insertion
(755 insertions, 0 deletions), and the rebuilt nisps.wasm was byte-identical.
S4 / 7.2 — firmware reads the active mode's driver config at mode start, and
mic/line is real. My brief assumed the engine owns this; the code disagreed and
the code was right. sound_analysis_midi's EngineT is NoOpEngine — the mic lives
on a separately-composed AnalysisEngine member — so engine-level wiring would
have compiled, passed every gate, and left the one mic mode on line input.
Hence a mode-level seam defaulting to engine().driver_config(). Separately,
DriverConfig's defaults (line_level 0, output_volume 1.0) had drifted from
memllib's actual 3/0.8 because nothing had ever read them; wiring them as-is
would have made every silent mode louder and its line input maximally
insensitive — a behaviour change disguised as plumbing. Now pinned by a test.
Also: GetSysClockSpeed() panic()s on unsupported sample rates and runs on the
first line of setup(), so sample_rate needed a fallback ahead of clock setup.
CI's firmware env list gains soundanalysismidi — it is the only mic variant and
nothing else compiles that path.
Plan 5e — telemetry is real. A loss_history C-API entry across the full 5-layer
chain lets the browser read the per-iteration loss the core already records.
The audit named one fabrication site; there were two — wasm-iml.ts's
synchronous train() published lossHistory: [loss] as well. A third, ctx.loss,
was not merely dead but actively synthetic (fallbacks of prev * 0.82 and a
literal 0.5, rendered by nothing) and is deleted. The firmware buffer stays
untouched, per the L25 call. EngineApi.lossHistory() reads spine state rather
than the MLP handle, because trainAsync() fits on the worker's mirror net and
the handle would give a subtly-wrong second answer.
Plan 5f — engine throughput is measurable. One source compiled twice (CMake
natively, emcc for WASM) so the targets compare directly and no WASM export is
added. Sequencers are driven into a working state, and every row prints its own
working-state evidence so a number produced by an idle engine is visible rather
than plausible. Reports, never asserts: a wall-clock threshold on shared
hardware is meaningless or flaky, same call as the firmware size job.
ALIGNMENT: the telemetry defect is deleted (built, not deferred); the
performance defect is rewritten to what is actually left — these are HOST
numbers, and nothing measures the RP2350 at 150 MHz, which is the target the
mission's constraint is about. Q4 (memllib ownership) and Q5 (legacy feedback
modes) are closed.
Corrections to my own earlier claims, both found by agents contradicting the
brief: manifold/ONBOARDING.md was NOT "now accurate" — its primitives list
still named five deleted primitives and cited a seededGradient() that does not
exist. And the parity harness misses the sequencer engines because it runs 128
frames while their sequencers evaluate every 400-500 samples, NOT because
all-params-0.5 fails to trigger them (it does trigger: 0.5 maps to ratio 2,
firing three times per bar). The fix is a longer window, not different params.
Gates: run-all-tests.sh ALL GREEN — 4/4 ctest, parity PASS, lint clean, curve
drift 1179 slots ok, 39 e2e (was 33). Firmware: 5 envs built including the mic
variant.
2026-07-21 22:02:23 +02:00
|
|
|
// The loss history is the ONLY on-device record of how a fit went (firmware)
|
|
|
|
|
// and the source the browser's training-health panel reads through
|
|
|
|
|
// `nisps_ml_loss_history` (simplification-plan §6.5e). Pin its contract:
|
|
|
|
|
// one entry per iteration actually run, last entry == the value train()
|
|
|
|
|
// returned, and a fresh run replaces rather than appends.
|
|
|
|
|
NISPS_TEST(mlp_loss_history_records_every_iteration) {
|
|
|
|
|
using M = nisps::ml::MLP<2, 4, 4, 4, 1, 4, 64>;
|
|
|
|
|
M m(11ull);
|
|
|
|
|
m.draw_weights(1.f);
|
|
|
|
|
|
|
|
|
|
std::array<float, 2> x{0.25f, 0.75f};
|
|
|
|
|
std::array<float, 1> y{0.9f};
|
|
|
|
|
m.add_example(std::span<const float>(x), std::span<const float>(y));
|
|
|
|
|
|
|
|
|
|
// min_err = 0 ⇒ the early-out never fires, so we run exactly max_iter.
|
|
|
|
|
const float loss = m.train(/*lr=*/0.2f, /*max_iter=*/12u, /*min_err=*/0.f);
|
|
|
|
|
NISPS_EXPECT(m.loss_history().size() == 12u);
|
|
|
|
|
NISPS_EXPECT_NEAR(m.loss_history()[11], loss, 1e-6);
|
|
|
|
|
// A real fit descends.
|
|
|
|
|
NISPS_EXPECT(m.loss_history()[11] < m.loss_history()[0]);
|
|
|
|
|
|
|
|
|
|
// A second run REPLACES the curve (it describes exactly one training run).
|
|
|
|
|
m.train(/*lr=*/0.2f, /*max_iter=*/3u, /*min_err=*/0.f);
|
|
|
|
|
NISPS_EXPECT(m.loss_history().size() == 3u);
|
|
|
|
|
|
|
|
|
|
// The single-step geometric-dislike path does NOT record — a dislike must
|
|
|
|
|
// not overwrite the last fit's curve with a 1-point one.
|
|
|
|
|
std::array<float, 1> target{0.1f};
|
|
|
|
|
m.train_targets(std::span<const float>(x), std::span<const float>(target), 0.05f);
|
|
|
|
|
NISPS_EXPECT(m.loss_history().size() == 3u);
|
|
|
|
|
|
|
|
|
|
// Early convergence truncates: an absurd min_err stops after iteration 1.
|
|
|
|
|
m.train(/*lr=*/0.2f, /*max_iter=*/50u, /*min_err=*/1e9f);
|
|
|
|
|
NISPS_EXPECT(m.loss_history().size() == 1u);
|
|
|
|
|
|
|
|
|
|
// Bounded by the storage cap, never past it.
|
|
|
|
|
M capped(11ull);
|
|
|
|
|
capped.add_example(std::span<const float>(x), std::span<const float>(y));
|
|
|
|
|
capped.train(/*lr=*/0.2f, /*max_iter=*/200u, /*min_err=*/0.f);
|
|
|
|
|
NISPS_EXPECT(capped.loss_history().size() == 64u);
|
|
|
|
|
}
|
|
|
|
|
|
feat(nisps/ml): MLP library with fixed-architecture template + spread-aware RL (meml-wmh)
Stream 2 of the clean-slate rewrite: nisps/ml/ replaces src/memlp/ with a
header-only, heap-free MLP that satisfies nisps::core::MLEngine.
Files (nisps/ml/):
- activations.hpp — ReLU (leaky 0.01 for parity), sigmoid, tanh
- loss.hpp — MSE per-sample (fixes meml-ues double-scaling: returns the
sample's MSE without an extra 1/N multiplication; the training loop
averages explicitly)
- init.hpp — uniform/Xavier/spread-aware weight init
- training.hpp — gradient clip helper (±10.0 matches legacy)
- rl.hpp — move_weights with per-layer Xavier scaling, weight decay
(10% * spread), gaussian noise via the deterministic Rng (matches the
legacy JS sum-of-three-uniforms shape); draw_weights also spread-aware
- stats.hpp — per-layer mean/max/dead/saturating diagnostics
- mlp.hpp — 4-layer (3 hidden + sigmoid output) MLP class with
std::array-backed weights, biases, gradient accumulators, dataset
ring buffer (default 128 examples), loss history (default 4096 iters).
Bias is a separate per-layer parameter — no input-vector mutation.
Flat get_weights/set_weights layout: weights all layers (row-major,
layer order), then biases all layers.
Tests (tests/cpp/, all 50 passing under -Wall -Wextra -Werror -Wpedantic):
- test_mlp_init.cpp — deterministic seeding, spread regimes,
static_assert MLEngine concept satisfied
- test_mlp_inference.cpp — golden hand-computed forward pass match,
sigmoid output range, set_input bounds
- test_mlp_training.cpp — XOR convergence (loss < 0.01 in <2k iters),
ring-buffer eviction
- test_mlp_loss.cpp — meml-ues regression test: reported loss equals
hand-computed average MSE without extra 1/N scaling; sample weights
honoured
- test_mlp_rl.cpp — move_weights respects output_pin_mask (final-layer
rows + biases preserved); spread regimes; grad clear after draw_weights
- test_mlp_serialize.cpp — get_weights/set_weights round-trip preserves
inference exactly; eval_loss is non-mutating; infer_batch matches
individual inference
Verification:
- Clean build, no warnings
- 50 tests pass (22 prior + 28 new)
- No std::vector / new / malloc in nisps/ml/
- All float literals .f-suffixed in code (comments excepted)
2026-04-29 14:55:43 +02:00
|
|
|
NISPS_TEST(mlp_train_with_no_examples_returns_zero) {
|
|
|
|
|
using M = nisps::ml::MLP<2, 4, 4, 4, 1, 4, 8>;
|
|
|
|
|
M m(0ull);
|
|
|
|
|
const float loss = m.train(0.5f, 100u, 0.001f);
|
|
|
|
|
NISPS_EXPECT(loss == 0.f);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
NISPS_TEST(mlp_clear_examples_works) {
|
|
|
|
|
using M = nisps::ml::MLP<2, 4, 4, 4, 1, 4, 8>;
|
|
|
|
|
M m(0ull);
|
|
|
|
|
std::array<float, 2> f{0.f, 1.f};
|
|
|
|
|
std::array<float, 1> l{0.5f};
|
|
|
|
|
m.add_example(std::span<const float>(f), std::span<const float>(l));
|
|
|
|
|
NISPS_EXPECT(m.example_count() == 1u);
|
|
|
|
|
m.clear_examples();
|
|
|
|
|
NISPS_EXPECT(m.example_count() == 0u);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
NISPS_TEST(mlp_dataset_ring_buffer_evicts_oldest) {
|
|
|
|
|
// NMaxExamples=4, add 6 examples; oldest 2 should be evicted.
|
|
|
|
|
using M = nisps::ml::MLP<1, 2, 2, 2, 1, 4, 8>;
|
|
|
|
|
M m(0ull);
|
|
|
|
|
for (int i = 0; i < 6; ++i) {
|
|
|
|
|
std::array<float, 1> f{static_cast<float>(i)};
|
|
|
|
|
std::array<float, 1> l{static_cast<float>(i) * 0.1f};
|
|
|
|
|
m.add_example(std::span<const float>(f), std::span<const float>(l));
|
|
|
|
|
}
|
|
|
|
|
NISPS_EXPECT(m.example_count() == 4u);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} // namespace
|