## 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..