Files
SirStone 7505fbf089 common_libs/guns: WaveElm ring gun, GUNK knowledge gun, online ELM
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.
2026-10-05 22:43:22 +02:00

356 lines
18 KiB
Nim

## ELM — Extreme Learning Machine, ONLINE SEQUENTIAL variant (ridge / RLS).
##
## Fixed random hidden layer (weights + biases drawn ONCE from a seeded RNG,
## never trained) and output weights `beta` solved by recursive least squares as
## samples arrive. This is NOT gradient descent: no backprop, no epochs, one
## pass over the data.
##
## Per sample, with g = act(W x + b) the hidden activation:
## g = act(W x + b)
## P = rho P - rho^2 (P g)(g^T P) / (1 + rho g^T P g)
## beta = beta + (P_new g) (t - g^T beta)
## with P0 = I/lambda, so P is exactly (sum_i rho^{i-n} g_i g_i^T + lambda I)^-1
## and beta is the ridge solution beta = (H^T H + lambda I)^-1 H^T T solved in
## closed form at every step — no gradient descent, no epochs, one pass.
## rho = 1 is textbook ridge RLS (K = P g / (1 + g^T P g)); rho > 1 is the
## FORGETTING FACTOR of Zhao, Wang & Park, Neurocomputing 87:79-89 (2012) —
## it decays the accumulated information matrix (M <- M/rho) so the net tracks
## a non-stationary target instead of averaging over its whole history.
## Its effective memory is about 1/(rho - 1) samples.
##
## Two sign/placement traps this file got wrong first and now documents, because
## both fail silently (they train, they just never track a drift):
## * scale P UP by rho after the update, not down — scaling it down makes M
## grow with rho, i.e. rho > 1 AMPLIFIES the past and freezes the net;
## * the K gain must be P_new * g (post-update), not P_old * g: only the
## former preserves the invariant above once rho != 1.
##
## ── (OPTIONAL) RECURRENCE — the RELM hidden layer ───────────────────────────
## h_j(t) = act(sum_k W_jk x_k(t) + b_j + r_j * h_j(t-1))
## Park Jin-Man & Kim Jong-Hwan, "Online recurrent extreme learning machine for
## time-series prediction", IJCNN 2017 pp. 1983-1990, doi 10.1109/IJCNN.2017.7966094
## (citation verified in guns/docs/README.md; the PDF itself is NOT in
## guns/docs/, so the exact equation above is the STANDARD recurrent-ELM form
## taken on the citation's word, not a transcription — flagged as an assumption
## rather than passed off as verified).
##
## WHAT IT BUYS, MEASURED: nothing. The one caller that uses it,
## guns/waveelm.nim, sweeps it over synthetic target sequences
## (common_libs/tests/bench_waveelm_temporal.nim, 3 regimes x 2 motion styles x
## 3 seeds) and it lands between -1.4% and +4.7% on RMS error and between
## -4.6% and +9.7% on hit rate — noise around zero, both on its own and on top
## of the lag window, INCLUDING a case built specifically to favour it (a ground
## truth with a 12-tick memory, longer than any explicit window the feature map
## can carry, where only integrating over time can build the quantity: -0.2% to
## -1.4% RMS). It is therefore OFF by default (`recurrentGain = 0.0`), where it
## is not merely slow but BYTE-IDENTICAL to the feed-forward net: r_j = 0 makes
## the recurrent term vanish and `hidden` skips it entirely.
##
## WHY IT IS SAFE ANYWAY (the three things a recurrence can break):
## 1. DIVERGENCE. Every r_j is clamped to |r_j| <= ElmRMax = 0.9 < 1, and with
## act' <= 1 the map h -> act(a + r h) is a contraction, so h has a unique
## bounded fixed point for ANY input and cannot run away. `isSane` also
## checks |r_j| < 1 and every h_j for finiteness, so a poisoned recurrence
## is detected rather than propagated.
## 2. STATE LEAK. The node state is the state of a SEQUENCE, not of the net:
## `resetHidden` clears it and keeps beta/P (what was LEARNED survives, the
## sequence does not), and guns/waveelm.nim calls it when the resolved
## target id changes and exposes `resetTemporalState` for a new round.
## 3. MIS-ALIGNED LABELS. A gun's label arrives dozens of ticks after the
## shot, so re-running `hidden(x)` at training time would fit a DIFFERENT
## function (the node state has moved on). `trainHidden` therefore takes the
## activation the shot actually used, and the gun stores it in the probe
## trace. Also: the caller owns the clock — `hidden` and `predict` are
## read-only, only `predictStep` advances, so a gun probing four bullet
## speeds per tick steps the recurrence once per TICK, not once per probe.
##
## The tests for all of the above are common_libs/tests/test_waveelm_temporal.nim.
##
## Dependency-light on purpose: std/math + std/random only, so a gun plugin can
## import it without dragging in a network stack. Deliberately implements NO Gun
## interface — the caller feeds features in and reads predictions out.
##
## Coordinate/gun conventions of gun_harness/gun_interface.nim apply to callers,
## not here: nothing in this file knows about degrees or bullets.
import std/[math, random]
type
ElmActivation* = enum
## Hidden nonlinearity. tanh (default) is the usual ELM choice; sigmoid is
## offered because the original ELM paper used it and some targets are
## better served by a (0,1) squashing.
eaTanh
eaSigmoid
ElmNet* = object
inputDim*: int
hiddenDim*: int
outputDim*: int
act*: ElmActivation
lambda*: float ## ridge regularisation: beta = (H^T H + lambda I)^-1 H^T T
rho*: float ## forgetting factor, >= 1.0 (1.0 = no forgetting)
W*: seq[seq[float]] ## hiddenDim x inputDim, fixed after init
b*: seq[float] ## hiddenDim, fixed after init
r*: seq[float] ## hiddenDim, RELM recurrent gain per node; all-zero
## (the default) means NO recurrence at all
hPrev*: seq[float] ## hiddenDim, the hidden layer's own state h(t-1)
beta*: seq[seq[float]] ## hiddenDim x outputDim, learned
P*: seq[seq[float]] ## hiddenDim x hiddenDim inverse correlation, learned
samples*: int ## successful updates since init (or last reset)
resets*: int ## numerical blowups that forced a soft reset
const
ElmRMax* = 0.9
## HARD clamp on every recurrent gain r_j.
## WHY: with |r| < 1 the map h -> act(a + r*h) is a CONTRACTION whenever
## act' is bounded by 1 (max tanh' = 1, max sigmoid' = 1/4), so the recurrence
## has a unique BOUNDED fixed point for ANY input and provably cannot
## diverge. That clamp is what buys the guarantee, rather than hoping the
## seeded gains happen to be tame: a runaway hidden vector would feed NaN
## straight into the RLS and blow up P. 0.9 keeps a uniform margin below 1
## and still buys a ~10-sample memory (0.9^10 = 0.35).
# ── helpers ───────────────────────────────────────────────────────────────────
proc isFinite(x: float): bool {.inline.} =
classify(x) notin {fcNan, fcInf, fcNegInf}
proc allFinite(m: seq[seq[float]]): bool =
for row in m:
for v in row:
if not isFinite(v): return false
true
proc allFinite(v: seq[float]): bool =
for x in v:
if not isFinite(x): return false
true
proc zeroMat(rows, cols: int): seq[seq[float]] =
result = newSeq[seq[float]](rows)
for i in 0..<rows: result[i] = newSeq[float](cols)
proc matVec(m: seq[seq[float]], v: openArray[float]): seq[float] =
## m * v, rectangular m allowed (only P*g is used today; P is square).
result = newSeq[float](m.len)
for i in 0..<m.len:
var s = 0.0
for j in 0..<min(m[i].len, v.len): s += m[i][j] * v[j]
result[i] = s
proc dot(a, b: openArray[float]): float {.inline.} =
for i in 0..<a.len: result += a[i] * b[i]
proc applyAct(net: ElmNet, v: float): float {.inline.} =
case net.act
of eaTanh: tanh(v)
of eaSigmoid: 1.0 / (1.0 + exp(-v))
# ── construction ──────────────────────────────────────────────────────────────
proc init*(inputDim, hiddenDim: int, seed: int64 = 42, outputDim = 1,
act = eaTanh, lambda = 1e-3, rho = 1.0,
recurrentGain = 0.0): ElmNet =
## Fixed hidden layer drawn from a seeded RNG, so the whole net is
## reproducible: same seed => same predictions.
##
## `recurrentGain` > 0 turns on the RELM hidden layer (Park Jin-Man & Kim
## Jong-Hwan, "Online recurrent extreme learning machine for time-series
## prediction", IJCNN 2017 pp. 1983-1990, doi 10.1109/IJCNN.2017.7966094):
## h_j(t) = act(sum_k W_jk x_k(t) + b_j + r_j * h_j(t-1))
## each hidden node feeds its OWN previous activation back into itself, which
## is what turns the feature map into a function of the SEQUENCE rather than
## of the current sample alone. (ASSUMPTION, documented honestly: the exact
## paper formulation could not be read from here — the PDF is not in
## guns/docs/ — so this is the standard recurrent-ELM form; the citation is
## verified in guns/docs/README.md.)
## The r_j are drawn from the SAME seeded RNG as W and b, in the same call
## order, so one seed still reproduces the entire net. Signs are symmetric:
## half the nodes remember forwards and half backwards, which is what lets a
## signed oscillatory quantity (a rotating aim bias) be represented.
## 0.0 (the default) leaves every r_j at 0 and the net is byte-identical to
## the plain feed-forward ELM: h_j(t) = act(W_j x + b_j), no state at all.
doAssert inputDim > 0 and hiddenDim > 0 and outputDim > 0
doAssert lambda > 0.0
var rng = initRand(seed)
result.inputDim = inputDim
result.hiddenDim = hiddenDim
result.outputDim = outputDim
result.act = act
result.lambda = lambda
result.rho = max(1.0, rho) # < 1 would amplify old samples; clamp, don't fail
result.W = newSeq[seq[float]](hiddenDim)
for h in 0..<hiddenDim:
result.W[h] = newSeq[float](inputDim)
for i in 0..<inputDim:
# Uniform in [-1,1] scaled by 1/sqrt(inputDim) keeps W x in a range tanh
# does not saturate on. (No randn in std/random; uniform is fine here.)
result.W[h][i] = (rand(rng, 1.0) * 2.0 - 1.0) / sqrt(float(inputDim))
result.b.add(rand(rng, 1.0) * 2.0 - 1.0)
var rj = 0.0
if recurrentGain > 0.0:
rj = clamp(recurrentGain * (rand(rng, 1.0) * 2.0 - 1.0), -ElmRMax, ElmRMax)
result.r.add(rj)
result.hPrev = newSeq[float](hiddenDim)
result.beta = zeroMat(hiddenDim, outputDim)
result.P = zeroMat(hiddenDim, hiddenDim)
# P0 = I/lambda: with no data yet the information matrix is exactly the ridge
# lambda*I, and the update below maintains P = (S + lambda*I)^-1. Anything else
# here (I, or I/lambda with the other denominator) silently stops the
# recursion from being the ridge solution.
for i in 0..<hiddenDim: result.P[i][i] = 1.0 / result.lambda
# ── numerics guard ─────────────────────────────────────────────────────────────
proc isSane*(net: ElmNet): bool =
## False as soon as any weight, bias or inverse-correlation entry is
## NaN/Inf — i.e. the RLS recursion has blown up — and false for a net that
## was never `init`ed (zero dims: every allFinite check vacuously passes, and
## the first `hidden` call would trip `x.len == inputDim` inside the gun).
if net.inputDim <= 0 or net.hiddenDim <= 0 or net.outputDim <= 0: return false
if net.W.len != net.hiddenDim or net.beta.len != net.hiddenDim or
net.P.len != net.hiddenDim or net.b.len != net.hiddenDim or
net.r.len != net.hiddenDim or net.hPrev.len != net.hiddenDim:
return false
if not allFinite(net.b): return false
if not allFinite(net.r): return false
if not allFinite(net.hPrev): return false
for rj in net.r:
if abs(rj) >= 1.0: return false # outside the contraction range
if not allFinite(net.beta): return false
allFinite(net.P)
proc resetHidden*(net: var ElmNet) =
## Drop the hidden layer's own state (h(t-1) -> 0) WITHOUT touching anything
## the RLS has learned. The recurrence belongs to a SEQUENCE: a new target,
## a new round or a re-acquired scan track is a new sequence, and carrying
## the old node states into it makes the first few predictions of the new
## sequence wrong for reasons that have nothing to do with beta.
net.hPrev = newSeq[float](net.hiddenDim)
proc softReset*(net: var ElmNet) =
## Drop everything learned; keep the fixed hidden layer (it is a pure
## function of the seed, so re-deriving it would change the net's identity).
net.beta = zeroMat(net.hiddenDim, net.outputDim)
net.P = zeroMat(net.hiddenDim, net.hiddenDim)
for i in 0..<net.hiddenDim: net.P[i][i] = 1.0 / net.lambda
net.samples = 0
net.resetHidden() # h(t-1) is state too: a reset net starts at h(0)=0
inc net.resets
proc recurrent*(net: ElmNet): bool {.inline.} =
## Is any hidden node recurrent? (All-zero r is the plain feed-forward ELM,
## and this is the flag that skips the recurrent term in the inner loop.)
for rj in net.r:
if rj != 0.0: return true
false
# ── forward / update ──────────────────────────────────────────────────────────
proc hidden*(net: ElmNet, x: openArray[float]): seq[float] =
## g = act(W x + b + r . h_prev), length hiddenDim. READ-ONLY: it reads the
## current state and never advances it, so the CALLER owns the clock. With
## every r_j = 0 (the default) the recurrent term is skipped entirely and
## this is the textbook feed-forward g.
doAssert x.len == net.inputDim
let rec = net.recurrent()
result = newSeq[float](net.hiddenDim)
for h in 0..<net.hiddenDim:
var s = net.b[h]
for i in 0..<net.inputDim: s += net.W[h][i] * x[i]
if rec: s += net.r[h] * net.hPrev[h]
result[h] = net.applyAct(s)
proc readOut*(net: ElmNet, g: openArray[float]): seq[float] =
## y = g^T beta, length outputDim. Returns zeros if the net went non-finite,
## so a caller can never propagate NaN into the gun's aim.
result = newSeq[float](net.outputDim)
for o in 0..<net.outputDim:
var s = 0.0
for h in 0..<net.hiddenDim: s += g[h] * net.beta[h][o]
result[o] = s
if not isFinite(s): return newSeq[float](net.outputDim)
proc predict*(net: ElmNet, x: openArray[float]): seq[float] =
## y = g(t)^T beta at the CURRENT state, WITHOUT advancing it. Kept
## immutable so a read-only caller (an evaluation sweep, a test) can use it;
## the gun, which owns the clock, calls `predictStep`.
if not net.isSane(): return newSeq[float](net.outputDim)
net.readOut(net.hidden(x))
proc predictStep*(net: var ElmNet, x: openArray[float]): seq[float] =
## One step of the SEQUENCE: y = g(t)^T beta, then h(t-1) <- g(t).
## The caller MUST advance exactly once per time step: a gun that probes four
## bullet speeds per tick has to call this once per TICK, not once per probe,
## or the node state runs at the probe rate instead of the tick rate.
if not net.isSane(): return newSeq[float](net.outputDim)
let g = net.hidden(x)
result = net.readOut(g)
if not net.isSane():
net.resetHidden() # blew up mid-step: drop the state, keep beta
return newSeq[float](net.outputDim)
net.hPrev = g
proc trainHidden*(net: var ElmNet, g: openArray[float],
t: openArray[float]): bool =
## One RLS step on an ALREADY COMPUTED hidden vector. A caller that owns a
## sequence (the gun stores the g of the shot it fired) must use this: the
## label belongs to the activation that actually produced it, and by the time
## a hit resolves (dozens of ticks later) `hidden(x)` would now be computed
## from a DIFFERENT h(t-1), i.e. it would train a different function.
## Returns false (leaving the net sane but untouched) if the sample is
## rejected, and true after a successful update — including the case where the
## step blew up and `softReset` was forced; check `resets` for that.
doAssert g.len == net.hiddenDim
doAssert t.len == net.outputDim
if net.P.len != net.hiddenDim or net.beta.len != net.hiddenDim:
net.softReset()
if not net.isSane(): net.softReset()
for v in g:
if not isFinite(v): return false
for v in t:
if not isFinite(v): return false
let Pg = matVec(net.P, g)
# rho enters here too: M = P^-1 becomes M/rho + g g^T this step.
let denom = 1.0 + net.rho * dot(g, Pg)
if not isFinite(denom) or denom <= 0.0:
net.softReset()
return true # consumed, but as a reset
# P = rho P - rho^2 (P g)(g^T P) / (1 + rho g^T P g)
# = rho (I - K g^T) P with K = P_new g — the subtracted term is
# K_i * (g^T P)_j = Pg[i]*Pg[j], NOT g[j]*P[i][j] (a different, wrong recursion).
var k = newSeq[float](net.hiddenDim)
for i in 0..<net.hiddenDim:
for j in 0..<net.hiddenDim:
net.P[i][j] = (net.P[i][j] - net.rho * Pg[i] * Pg[j] / denom) * net.rho
var ki = 0.0
for j in 0..<net.hiddenDim: ki += net.P[i][j] * g[j]
k[i] = ki
# beta += K (t - g^T beta), K = P_new g
for o in 0..<net.outputDim:
var pred = 0.0
for h in 0..<net.hiddenDim: pred += g[h] * net.beta[h][o]
let e = t[o] - pred
for h in 0..<net.hiddenDim: net.beta[h][o] += k[h] * e
inc net.samples
if not net.isSane():
net.softReset()
return true
true
proc train*(net: var ElmNet, x: openArray[float], t: openArray[float]): bool =
## Convenience wrapper: g = hidden(x) at the CURRENT state, then one RLS step.
## Fine for a batch/streaming learner; a sequence learner that can go back in
## time (the gun, whose label arrives long after the shot) must use
## `predictStep` + `trainHidden` instead.
doAssert x.len == net.inputDim
for v in x:
if not isFinite(v): return false # reject at the trust boundary, not
# after tanh has saturated it to 1.0
let g = net.hidden(x)
net.trainHidden(g, t)