guns/elm.nim online sequential ELM (ridge/RLS), fixed random
hidden layer, one pass, no backprop
guns/waveelm.nim the WaveElm gun: a simulated omnidirectional expanding
ring of probes fired from the SHOOTER, where the ELM
learns a BIAS CORRECTION to the ring's reconstructed
position (predicting the position outright was measured
and refuted: it collapses on abrupt/burst movement)
guns/gun_knowledge.nim GUNK: a learned additive angular residual on top of
the self-consistent lead forecast. Only answers "which
absolute gun direction", nothing else
guns/docs/ the open-access OS-ELM / ELM reference set plus
fetch_papers.sh, which re-downloads it idempotently
Plus the matching test and measurement harnesses (test_waveelm*, test_elm,
test_gun_knowledge, test_knowledge_registration, gk_aim_probe,
measure_gk_{residual,virtual}.py) and the docs README with the citations.
355 lines
16 KiB
Nim
355 lines
16 KiB
Nim
## Offline tests for the TEMPORAL extensions of the WaveElm gun:
|
|
## (A) the lag-window feature map (guns/waveelm.nim, WaveLagK / waveFeatures)
|
|
## (B) the RELM recurrent hidden layer (guns/elm.nim, r / hPrev / predictStep)
|
|
## covered here, plus the per-enemy / per-episode state reset and the
|
|
## train-on-the-stored-activation path.
|
|
##
|
|
## Everything is offline and bounded: no server, no java, no runBattle, and
|
|
## every loop count is a small constant.
|
|
##
|
|
## Run: nim c -r common_libs/tests/test_waveelm_temporal.nim
|
|
|
|
import std/[math, strformat, tables]
|
|
import gun_harness/gun_interface
|
|
import guns/elm
|
|
import guns/waveelm
|
|
|
|
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 fin(x: float): bool =
|
|
classify(x) notin {fcNan, fcInf, fcNegInf}
|
|
|
|
proc allFinite(s: seq[float]): bool =
|
|
for v in s:
|
|
if not fin(v): return false
|
|
true
|
|
|
|
proc mkState(tick: int, ex, ey, eh, es: float, id = 1,
|
|
sx = 100.0, sy = 300.0): WorldState =
|
|
WorldState(
|
|
enemyX: ex, enemyY: ey, enemyHeading: eh, enemySpeed: es, enemyEnergy: 100.0,
|
|
selfX: sx, selfY: sy, selfSpeed: 0.0, selfHeading: 0.0,
|
|
selfRadarHeading: 0.0, selfEnergy: 100.0,
|
|
arenaWidth: 800.0, arenaHeight: 600.0, tick: tick,
|
|
enemies: @[EnemyInfo(id: id, x: ex, y: ey, heading: eh, speed: es,
|
|
energy: 100.0, lastSeenTick: tick)])
|
|
|
|
# ── (A) the lag window ───────────────────────────────────────────────────────
|
|
|
|
proc testLagWindow() =
|
|
check "lag: waveInputDim(2) is the legacy 10", waveInputDim(2) == 10
|
|
check "lag: waveInputDim(4) == 10 + 2*(4-2)", waveInputDim(4) == 14
|
|
check "lag: waveInputDim(8) == 10 + 2*(8-2)", waveInputDim(8) == 22
|
|
check "lag: WaveTrackCap covers the longest window", WaveTrackCap >= WaveLagKMax + 1
|
|
check "lag: init clamps the window to [2, WaveLagKMax]",
|
|
initWaveElmGun(42, lagK = 1).lagK == 2 and
|
|
initWaveElmGun(42, lagK = 99).lagK == WaveLagKMax
|
|
|
|
block:
|
|
# A straight run of scans: one tick apart, +6 px in x each tick. Every
|
|
# window slot must hold THAT tick's displacement / 16 px.
|
|
var g = initWaveElmGun(42, lagK = 4)
|
|
check "lag: the net is as wide as the window", g.net.inputDim == 14
|
|
var f: seq[float]
|
|
for t in 0..<6:
|
|
let st = mkState(t, 300.0 + 6.0 * t.float, 300.0, 0.0, 6.0)
|
|
discard g.predict(st, 17.0)
|
|
f = g.waveFeatures(st, 6.0, 0.0, 30.0)
|
|
check "lag: the feature vector is exactly waveInputDim(4) long", f.len == 14
|
|
var ok = true
|
|
for k in 0..<4:
|
|
if abs(f[4 + 2 * k] - 6.0 / 16.0) > 1e-12: ok = false
|
|
if abs(f[5 + 2 * k] - 0.0) > 1e-12: ok = false
|
|
check &"lag: all 4 window slots hold their own displacement / 16 (t={6})", ok
|
|
check "lag: the staleness/flight slots moved to the end of the window",
|
|
abs(f[4 + 2 * 4] - 0.0) < 1e-12 and f[5 + 2 * 4] > 0.0
|
|
|
|
block:
|
|
# The base 8 features must not depend on the window: a lagK=4 gun fed the
|
|
# same scans must agree with a legacy lagK=2 gun on slots 0..7.
|
|
var g4 = initWaveElmGun(42, lagK = 4)
|
|
var g2 = initWaveElmGun(42, lagK = 2)
|
|
for t in 0..<5:
|
|
let st = mkState(t, 300.0 + 5.0 * t.float, 300.0 + t.float, 12.0, 5.0)
|
|
discard g4.predict(st, 17.0)
|
|
discard g2.predict(st, 17.0)
|
|
let f4 = g4.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
|
|
let f2 = g2.waveFeatures(mkState(4, 320.0, 304.0, 12.0, 5.0), 5.0, 1.0, 30.0)
|
|
var same = true
|
|
for i in 0..<8:
|
|
if abs(f4[i] - f2[i]) > 1e-12: same = false
|
|
check "lag: the base features are unchanged by the window (slots 0..7)", same
|
|
|
|
block:
|
|
# Fewer scans than the window: the missing slots must be ZERO, not garbage.
|
|
var g = initWaveElmGun(42, lagK = 6)
|
|
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
|
|
let f = g.waveFeatures(mkState(0, 300.0, 300.0, 0.0, 5.0), 5.0, 0.0, 30.0)
|
|
check "lag: a window longer than the scan history reads zeros",
|
|
f.len == waveInputDim(6) and
|
|
(block:
|
|
var ok = true
|
|
for i in 0..<f.len:
|
|
if not fin(f[i]): ok = false
|
|
ok)
|
|
|
|
block:
|
|
# A late scan (gap = 2 ticks) must be normalised PER TICK, or the window
|
|
# silently measures the radar cadence instead of the target.
|
|
var g = initWaveElmGun(42, lagK = 2)
|
|
discard g.predict(mkState(0, 300.0, 300.0, 0.0, 5.0), 17.0)
|
|
discard g.predict(mkState(2, 312.0, 300.0, 0.0, 6.0), 17.0) # 12 px in 2 ticks
|
|
let f = g.waveFeatures(mkState(2, 312.0, 300.0, 0.0, 6.0), 6.0, 0.0, 30.0)
|
|
check &"lag: a 2-tick gap is normalised to px/tick (6/16 = {6.0/16.0})",
|
|
abs(f[4] - 6.0 / 16.0) < 1e-12
|
|
|
|
# ── (B) the RELM recurrence ──────────────────────────────────────────────────
|
|
|
|
proc testRelm() =
|
|
block:
|
|
# Gain 0 must be EXACTLY the legacy feed-forward net: g = act(W x + b).
|
|
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
|
|
recurrentGain = 0.0)
|
|
check "relm: gain 0 leaves the net non-recurrent", not net.recurrent()
|
|
check "relm: gain 0 leaves every r_j at 0",
|
|
(block:
|
|
var ok = true
|
|
for v in net.r:
|
|
if v != 0.0: ok = false
|
|
ok)
|
|
let x = @[0.3, -0.7, 0.11]
|
|
var manual = newSeq[float](8)
|
|
for h in 0..<8:
|
|
var s = net.b[h]
|
|
for i in 0..<3: s += net.W[h][i] * x[i]
|
|
manual[h] = tanh(s)
|
|
check "relm: gain 0 reproduces act(W x + b) exactly", net.hidden(x) == manual
|
|
|
|
block:
|
|
let net = init(inputDim = 3, hiddenDim = 8, seed = 42, outputDim = 1,
|
|
recurrentGain = 0.5)
|
|
check "relm: gain > 0 makes the net recurrent", net.recurrent()
|
|
check "relm: every |r_j| is inside the contraction range [0, ElmRMax]",
|
|
(block:
|
|
var ok = true
|
|
for v in net.r:
|
|
if abs(v) > ElmRMax or abs(v) >= 1.0: ok = false
|
|
ok)
|
|
check "relm: the recurrence is seeded (not all identical gains)",
|
|
(block:
|
|
var varies = false
|
|
for i in 1..<net.r.len:
|
|
if net.r[i] != net.r[0]: varies = true
|
|
varies)
|
|
|
|
block:
|
|
# predict is READ-ONLY, predictStep ADVANCES the clock exactly once.
|
|
var net = init(inputDim = 2, hiddenDim = 6, seed = 7, outputDim = 1,
|
|
recurrentGain = 0.6)
|
|
let x = @[0.5, -0.2]
|
|
# beta starts at ZERO, so an untrained net predicts 0 whatever the state
|
|
# is: train it first or this test would be comparing 0.0 to 0.0.
|
|
for i in 0..<20:
|
|
let v = float(i) / 20.0
|
|
discard net.train(@[v, -v], @[2.0 * v])
|
|
let p1 = net.predict(x)
|
|
let p2 = net.predict(x)
|
|
check "relm: predict does not advance the hidden state", p1 == p2
|
|
discard net.predictStep(x)
|
|
let p3 = net.predict(x)
|
|
check "relm: predictStep advances the state (the next prediction differs)",
|
|
p1 != p3
|
|
|
|
block:
|
|
# STABILITY: the contraction argument says |h| <= 1 and no NaN, whatever
|
|
# the input does. Wild-but-plausible inputs first (20000 steps): nothing may
|
|
# blow up at all, not even a soft reset.
|
|
var net = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
|
|
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
|
|
var sane = true
|
|
var bounded = true
|
|
for i in 0..<20000:
|
|
let m = if i mod 2 == 0: 20.0 else: -20.0
|
|
let y = net.predictStep(@[m, sin(float(i) * 0.01) * m])
|
|
discard net.train(@[m, float(i mod 7).float], @[y[0]])
|
|
if not net.isSane() or not allFinite(y): sane = false
|
|
for h in net.hPrev:
|
|
if not fin(h) or abs(h) > 1.0: bounded = false
|
|
check "relm: 20000 steps of +-20 stay finite and sane", sane
|
|
check "relm: |h| never leaves tanh's range [-1, 1] (the clamp holds)", bounded
|
|
|
|
# The pre-existing RLS guard soft-resets on an ill-conditioned stream; what
|
|
# matters is whether the RECURRENCE causes MORE of them than the identical
|
|
# feed-forward loop does. Same seed, same inputs, only r_j differs.
|
|
var ff = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
|
|
lambda = 1e-3, rho = 1.02, recurrentGain = 0.0)
|
|
for i in 0..<20000:
|
|
let m = if i mod 2 == 0: 20.0 else: -20.0
|
|
let y = ff.predictStep(@[m, sin(float(i) * 0.01) * m])
|
|
discard ff.train(@[m, float(i mod 7).float], @[y[0]])
|
|
echo &" soft resets on the same 20000 steps: RELM {net.resets}, " &
|
|
&"feed-forward {ff.resets}"
|
|
check "relm: the recurrence does not add a single soft reset",
|
|
net.resets <= ff.resets
|
|
|
|
# Absurd inputs (1e3) DO trip the pre-existing RLS blow-up guard, which
|
|
# soft-resets and carries on. What must hold is that the RECURRENCE does
|
|
# not diverge: the prediction stays finite and the state stays in range.
|
|
var net2 = init(inputDim = 2, hiddenDim = 12, seed = 3, outputDim = 1,
|
|
lambda = 1e-3, rho = 1.02, recurrentGain = ElmRMax)
|
|
var sane2 = true
|
|
var bounded2 = true
|
|
for i in 0..<20000:
|
|
let m = if i mod 2 == 0: 1.0e3 else: -1.0e3
|
|
let y = net2.predictStep(@[m, sin(float(i) * 0.01) * m])
|
|
discard net2.train(@[m, float(i mod 7).float], @[y[0]])
|
|
if not allFinite(y): sane2 = false
|
|
for h in net2.hPrev:
|
|
if not fin(h) or abs(h) > 1.0: bounded2 = false
|
|
check "relm: 20000 steps of +-1e3 stay finite", sane2
|
|
check "relm: the hidden state stays bounded even at +-1e3", bounded2
|
|
|
|
block:
|
|
# The RLS must still reject bad samples on the hidden-vector entry point.
|
|
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.4)
|
|
let g = net.hidden(@[0.5])
|
|
check "relm: trainHidden rejects a NaN hidden vector",
|
|
not net.trainHidden(@[NaN, 0.5, 0.5, 0.5], @[1.0])
|
|
check "relm: trainHidden rejects a NaN target", not net.trainHidden(g, @[NaN])
|
|
check "relm: the net survives both rejections", net.isSane() and net.samples == 0
|
|
|
|
block:
|
|
# A poisoned recurrence must be DETECTED, not propagated.
|
|
var net = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
|
|
net.r[0] = NaN
|
|
check "relm: isSane detects a NaN recurrent gain", not net.isSane()
|
|
var net2 = init(inputDim = 1, hiddenDim = 4, seed = 1, recurrentGain = 0.5)
|
|
net2.r[0] = 1.5
|
|
check "relm: isSane rejects a gain outside the contraction range",
|
|
not net2.isSane()
|
|
|
|
# ── per-enemy / per-episode state reset ──────────────────────────────────────
|
|
|
|
proc testStateReset() =
|
|
block:
|
|
# A new target is a new SEQUENCE: its first activation must be computed
|
|
# from h(0) = 0, not from whatever the previous target left behind.
|
|
var g = initWaveElmGun(42, lagK = 4, relm = 0.6)
|
|
var x = 300.0
|
|
for t in 0..<8:
|
|
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 1)
|
|
discard g.predict(st, 17.0)
|
|
x += 5.0
|
|
check "reset: the RELM state is non-zero after a run of ticks",
|
|
(block:
|
|
var live = false
|
|
for h in g.net.hPrev:
|
|
if h != 0.0: live = true
|
|
live)
|
|
|
|
# Same scan stream, new enemy id -> the first activation must equal the one
|
|
# a FRESH net would produce (i.e. the state really was cleared).
|
|
var h = initWaveElmGun(42, lagK = 4, relm = 0.6)
|
|
x = 300.0
|
|
for t in 0..<8:
|
|
let st = mkState(t, x, 300.0, 0.0, 5.0, id = 2)
|
|
discard h.predict(st, 17.0)
|
|
x += 5.0
|
|
# The strongest form of the claim: after the id change, gun A (which has
|
|
# just been running another target) must produce BYTE-IDENTICAL aim points
|
|
# to a fresh gun B that has only ever seen the new target. Any residue of
|
|
# the old sequence — node state, learned beta, scan track — would break it.
|
|
let st4 = mkState(9, x, 300.0, 0.0, 5.0, id = 4)
|
|
var fresh = initWaveElmGun(42, lagK = 4, relm = 0.6)
|
|
var same = true
|
|
for p in WavePowers:
|
|
let a = h.predict(st4, bulletSpeed(p))
|
|
let b = fresh.predict(st4, bulletSpeed(p))
|
|
if a.x != b.x or a.y != b.y or a.confidence != b.confidence: same = false
|
|
check "reset: a new enemy id starts its sequence from h(0) = 0", same
|
|
check "reset: the target change was actually seen (tracks differ)",
|
|
h.tracks.hasKey(2) and h.tracks.hasKey(4)
|
|
|
|
block:
|
|
# Per-episode reset clears the state but KEEPS what was learned.
|
|
var g = initWaveElmGun(42, lagK = 2, relm = 0.5)
|
|
var x = 300.0
|
|
for t in 0..<30:
|
|
let st = mkState(t, x, 300.0, 0.0, 5.0)
|
|
let pr = g.predict(st, 17.0)
|
|
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 4.0,
|
|
actualY: pr.y, bulletPower: 1.0, fireTick: t, powerBin: 0,
|
|
hit: true, confidence: pr.confidence))
|
|
x += 5.0
|
|
let samples = g.net.samples
|
|
let learned = g.net.beta[0][0]
|
|
g.resetTemporalState()
|
|
var cleared = true
|
|
for v in g.net.hPrev:
|
|
if v != 0.0: cleared = false
|
|
check "reset: resetTemporalState zeroes h(t-1)", cleared
|
|
check "reset: it keeps the learned beta and the RLS state",
|
|
g.net.samples == samples and g.net.beta[0][0] == learned
|
|
check "reset: a RELM gun still trains on the stored activation",
|
|
samples == g.trainedShots
|
|
|
|
# ── end to end with everything on ────────────────────────────────────────────
|
|
|
|
proc testEndToEnd() =
|
|
var g = initWaveElmGun(42, lagK = 8, relm = 0.3)
|
|
var x = 200.0
|
|
var y = 300.0
|
|
var finite = true
|
|
for t in 0..<120:
|
|
let st = mkState(t, x, y, 30.0, 5.0)
|
|
for p in WavePowers:
|
|
let spd = bulletSpeed(p)
|
|
let pr = g.predict(st, spd)
|
|
if not (fin(pr.x) and fin(pr.y) and fin(pr.confidence)): finite = false
|
|
# resolve immediately, so every trace is trained on its own activation
|
|
g.onResult(FeedbackEvent(prediction: pr, actualX: pr.x + 3.0,
|
|
actualY: pr.y - 1.0, bulletPower: p, fireTick: t,
|
|
powerBin: waveBinForSpeed(spd), hit: true, confidence: pr.confidence))
|
|
x = (x + 5.0).clamp(BotRadius, 800.0 - BotRadius)
|
|
y = (y + 1.0).clamp(BotRadius, 600.0 - BotRadius)
|
|
check "e2e: lagK=8 + RELM 0.3 produces only finite aim points", finite
|
|
# A rung trains unless its trace lookup missed or the residual gate rejected it
|
|
# as implausible (this target accelerates across the arena, so the ring's
|
|
# constant-velocity base is not within 3*BotRadius of the truth every tick).
|
|
check &"e2e: every rung is accounted for (trained {g.trainedShots} + rejected " &
|
|
&"{g.rejectedShots} + misses {g.missShots} + traceMisses {g.traceMisses})",
|
|
g.trainedShots + g.rejectedShots + g.missShots + g.traceMisses == 120 * WaveRungs
|
|
check "e2e: the great majority of rungs train", g.trainedShots > (120 * WaveRungs) div 2
|
|
check "e2e: the net is still sane", g.net.isSane()
|
|
check "e2e: no soft reset was needed", g.net.resets == 0
|
|
|
|
# Degenerate state with every extension on must still not hang or leak NaN.
|
|
var h = initWaveElmGun(42, lagK = 8, relm = 0.9)
|
|
let nan = 0.0 / 0.0
|
|
var ok = true
|
|
for bad in [nan, 1.0 / 0.0, -1.0 / 0.0]:
|
|
let st = mkState(3, bad, bad, bad, bad, id = 7)
|
|
for p in WavePowers:
|
|
let pr = h.predict(st, bulletSpeed(p))
|
|
if not fin(pr.x): ok = false
|
|
let f = h.waveFeatures(st, bad, bad, bad)
|
|
for v in f:
|
|
if classify(v) in {fcNan, fcInf, fcNegInf}: ok = false
|
|
check "e2e: NaN/Inf state never escapes with lagK=8 + RELM 0.9", ok
|
|
check "e2e: the net survives it", h.net.isSane()
|
|
|
|
when isMainModule:
|
|
echo "── (A) lag window ──"; testLagWindow()
|
|
echo "── (B) RELM ──"; testRelm()
|
|
echo "── state reset ──"; testStateReset()
|
|
echo "── end to end ──"; testEndToEnd()
|
|
if failures > 0:
|
|
echo "\n", failures, " of ", checks, " check(s) FAILED"
|
|
quit(1)
|
|
echo &"\nAll {checks} WaveElm-temporal checks passed."
|