## Unit tests for the online sequential ELM (common_libs/guns/elm.nim). ## ## Covers what the guns actually rely on: fitting a known function, streaming ## convergence, the forgetting factor tracking a drifting target, the ## NaN/Inf guards, and seed reproducibility. ## ## Run: nim c -r common_libs/tests/test_elm.nim import std/[math, random, strformat] import guns/elm var failures = 0 var checks = 0 proc check(name: string, ok: bool) = inc checks if ok: echo "PASS: ", name else: echo "FAIL: ", name; inc failures proc rmse(net: ElmNet, samples: seq[tuple[x: seq[float], t: seq[float]]]): float = ## Prediction RMSE over a held-out sample set (net used read-only). var s = 0.0 for smp in samples: let p = net.predict(smp.x) for o in 0.. 2D output ─────────────────────────────────────────────── block: let n = 600 var rng = initRand(11) var net = init(inputDim = 2, hiddenDim = 20, seed = 7, outputDim = 2) proc target(x: openArray[float]): seq[float] = @[x[0] + 0.5 * x[1] - 1.0, -0.3 * x[0] + 2.0 * x[1] + 0.25] for i in 0..2D: grid RMSE = {e:.5f}" check "2D->2D: RMSE < 0.05", e < 0.05 # ── 3. online / streaming convergence ──────────────────────────────────────── proc testStreaming() = ## RLS is prequential: every sample is predicted once, then trained on. The ## net converges in a handful of samples (that is the point of RLS), so the ## trend has to be measured against the FIRST samples, not the first 100. var rng = initRand(3) var net = init(inputDim = 1, hiddenDim = 16, seed = 99) var firstErr = 0.0 var headErr = 0.0 var tailErr = 0.0 var worstTail = 0.0 for i in 0..<600: let x = @[rand(rng, 1.0) * 2.0 - 1.0] let t = @[2.0 * x[0] + 1.0] if i == 0: firstErr = (net.predict(x)[0] - t[0]) ^ 2 # untrained: predicts 0 discard net.train(x, t) let err = (net.predict(x)[0] - t[0]) ^ 2 if i < 5: headErr += err elif i >= 500: tailErr += err worstTail = max(worstTail, err) headErr /= 5.0 tailErr /= 100.0 echo &" streaming: 1st sample MSE = {firstErr:.6f}, first-5 MSE = {headErr:.6f}, " & &"last-100 MSE = {tailErr:.6f}" check "streaming: last-100 MSE << first-sample MSE (>=100x better)", tailErr < firstErr / 100.0 check "streaming: running error keeps trending down (last-100 <= first-5)", tailErr <= headErr # Floor: ~2e-6 MSE is the lambda = 1e-3 ridge bias, not a learning failure. check "streaming: last-100 MSE < 1e-4", tailErr < 1e-4 check "streaming: no single late sample worse than 100x the last-100 mean", worstTail < tailErr * 100.0 # ── 4. forgetting factor tracks a drifting target ──────────────────────────── proc testForgetting() = block: ## Target jumps sign/slope halfway through. Two numbers per net: the mean ## RMSE over all post-jump samples (transient included) and the tail RMSE ## (adaptation quality once it has settled). rho = 1 averages the whole ## history and never leaves the old function; rho > 1 must track. let n = 800 proc drift(net: var ElmNet): tuple[mean, tail: float] = var re = initRand(1) var e2 = 0.0 var eTail = 0.0 for i in 0..= n div 2: let e = (net.predict(x)[0] - t[0]) ^ 2 e2 += e if i >= n - 200: eTail += e (sqrt(e2 / float(n div 2)), sqrt(eTail / 200.0)) var plain = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.0) var forget = init(inputDim = 1, hiddenDim = 20, seed = 42, rho = 1.02) let ePlain = drift(plain) let eForget = drift(forget) echo &" drifting target, post-jump mean RMSE: rho=1.0 -> {ePlain.mean:.5f}, " & &"rho=1.02 -> {eForget.mean:.5f}" echo &" drifting target, post-jump TAIL RMSE: rho=1.0 -> {ePlain.tail:.5f}, " & &"rho=1.02 -> {eForget.tail:.5f}" check "forgetting: rho=1.02 halves the mean post-jump RMSE on a drifting target", eForget.mean < ePlain.mean * 0.5 check "forgetting: rho=1.02 tracks the new target (tail RMSE >=20x better)", eForget.tail < ePlain.tail / 20.0 check "forgetting: rho=1.02 settles on the new target (tail RMSE < 0.05)", eForget.tail < 0.05 # ── 5. numerical guards ────────────────────────────────────────────────────── proc testGuards() = block: var net = init(inputDim = 1, hiddenDim = 8, seed = 42) for i in 0..<200: let x = @[float(i) / 200.0 - 0.5] discard net.train(x, @[2.0 * x[0]]) check "guards: net is sane after 200 clean updates", net.isSane() # a NaN sample must be rejected without poisoning the net let rejected = net.train(@[0.5], @[NaN]) check "guards: NaN target is rejected", not rejected check "guards: net still sane after a rejected NaN sample", net.isSane() check "guards: NaN input is rejected", not net.train(@[Inf], @[1.0]) check "guards: net still sane after Inf input", net.isSane() # many updates with an extreme input: prediction must stay finite var wild = init(inputDim = 1, hiddenDim = 8, seed = 42, rho = 1.01) for i in 0..<5000: let x = @[sin(float(i)) * 1e6] discard wild.train(x, @[x[0]]) let p = wild.predict(x) if p[0].classify in {fcNan, fcInf, fcNegInf}: check "guards: prediction stays finite over 5000 wild updates", false return check "guards: prediction stays finite over 5000 wild updates", classify(wild.predict(@[1.0])[0]) notin {fcNan, fcInf, fcNegInf} # poisoned state is detected and reset away from var broken = init(inputDim = 1, hiddenDim = 4, seed = 42) discard broken.train(@[0.5], @[1.0]) broken.beta[0][0] = NaN check "guards: isSane detects a poisoned beta", not broken.isSane() check "guards: predict returns zeros instead of NaN", broken.predict(@[0.5]) == @[0.0] discard broken.train(@[0.5], @[1.0]) check "guards: training a poisoned net soft-resets it", broken.isSane() and broken.resets > 0 and broken.samples == 1 broken.softReset() check "guards: explicit softReset zeroes beta and P", broken.samples == 0 and broken.beta[0][0] == 0.0 and broken.P[0][0] == 1.0 / broken.lambda # ── 6. seed reproducibility ────────────────────────────────────────────────── proc testReproducible() = block: var a = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2) var b = init(inputDim = 2, hiddenDim = 12, seed = 1234, outputDim = 2) var c = init(inputDim = 2, hiddenDim = 12, seed = 4321, outputDim = 2) var rng = initRand(17) for i in 0..<50: let x = @[rand(rng, 1.0), rand(rng, 1.0)] let t = @[x[0] - x[1], 2.0 * x[0] + 3.0 * x[1]] discard a.train(x, t) discard b.train(x, t) discard c.train(x, t) let q = @[0.3, -0.7] check "seed: same seed => identical predictions", a.predict(q) == b.predict(q) check "seed: different seed => different predictions", a.predict(q) != c.predict(q) check "activation: sigmoid option is actually used", init(1, 12, seed = 1, act = eaSigmoid).act == eaSigmoid var sg = init(inputDim = 1, hiddenDim = 12, seed = 1, act = eaSigmoid) for i in 0..<300: let x = @[float(i) / 300.0 - 0.5] discard sg.train(x, @[2.0 * x[0]]) check "activation: sigmoid ELM also fits y=2x (RMSE < 0.05)", rmse(sg, @[(x: @[-0.5], t: @[-1.0]), (x: @[0.5], t: @[1.0])]) < 0.05 proc main() = echo "── linear fit ──"; testLinearFit() echo "── streaming convergence ──"; testStreaming() echo "── forgetting factor ──"; testForgetting() echo "── numerical guards ──"; testGuards() echo "── reproducibility ──"; testReproducible() echo "" if failures > 0: echo &"{failures}/{checks} check(s) FAILED" quit(1) echo &"All {checks} ELM checks passed." when isMainModule: main()