diff --git a/common_libs/guns/docs/README.md b/common_libs/guns/docs/README.md new file mode 100644 index 0000000..346415a --- /dev/null +++ b/common_libs/guns/docs/README.md @@ -0,0 +1,199 @@ +# OS-ELM reference papers — audit, downloads, and update-rule notes + +Audit date: 2026-08-22, extended 2026-10-02 (all identifiers re-fetched from arxiv.org, +api.crossref.org, api.openalex.org and doi.org — nothing here is trusted from a previous pass). + +Re-download everything open access with: + +```bash +./fetch_papers.sh # idempotent; exits non-zero and deletes any non-PDF +``` + +## CITATION NOTES — read this first + +Three of the fourteen claimed citations were wrong, and one does not exist at all. + +| Claim | Reality | +|---|---| +| `10.1109/TSMCS.2011.616645` — "Huang/Zhu/Zhou 2011–2012 ELM survey" | **DOES NOT EXIST.** `doi.org` returns **404**; absent from Crossref *and* OpenAlex. No paper carries this DOI. Do not cite it. | +| "Extreme Learning Machine: A Review and New Trends", Huang, IEEE T-SMC-B **42(2):513–529, 2012** | **WRONG TITLE + WRONG AUTHORS.** Those exact pages belong to `10.1109/TSMCB.2011.2168604` = *"Extreme Learning Machine for Regression and Multiclass Classification"*, **Huang, Zhou, Ding & Zhang** (4 authors, not 1). A Crossref title search for "…A Review and New Trends" returns **no such article**. Treat the title as fabricated. The likely intended real review is *"Trends in extreme learning machines: A review"*, `10.1016/j.neunet.2014.10.001` (Neural Networks 61:32–48, 2015). | +| `10.1007/s10922-025-09976-3` — "Shwaysh et al., Ensemble RELM, **J Real-Time Image Proc 2025**" | **WRONG VENUE.** It is *Journal of Network and Systems Management* **34(1), 2025** — an intrusion-detection paper. First author Shwaysh is correct. | +| `10.1007/s11042-021-11008-7` — "A review on extreme learning machine" | **TYPO, DOES NOT RESOLVE (404).** The correct DOI is **`10.1007/s11042-021-11007-7`** (11007, not 11008). | + +Two more were near-misses rather than errors: + +* **`arXiv:2512.21777` is REAL**, despite the "implausible number" flag. Submitted 2025-12-25, and the title matches almost verbatim (it spells out "Extreme Learning Machine"). Confirmed twice: `arxiv.org/abs/2512.21777` and the arXiv API. Not hallucinated. +* **`arXiv:2504.09028`** has a different title than claimed. It is *"Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing"*; the OSOS-ELM / one-sided-Jacobi content is real (it's in the abstract), only the title was misremembered. + +One more non-existent citation, found on a later pass (audit date 2026-10-02): + +* **"Extreme Learning Machines: A Survey", Huang / Zhu / Zhou, IEEE T-SMC-B 42(3):486–497 (2012)" — NOT DISCOVERABLE.** There is no such article. Crossref's full, *gap-free* inventory of T-SMC-B vol. 42 shows issue 2 runs 294–580 and issue 3 starts at 581, so pages 486–497 cannot be in either. The range 486–497 sits **inside** a different article, 42(2):482–500 = *"An Adaptive Differential Evolution Algorithm With Novel Mutation and Crossover Strategies for Global Numerical Optimization"* (`10.1109/TSMCB.2011.2167966`, Islam, Das, Ghosh, Roy, Suganthan), verified independently in OpenAlex. The genuine ELM article in issue 2 is 513–529 (`10.1109/TSMCB.2011.2168604`), the one already audited above. No DOI was found for a Huang/Zhu/Zhou survey; a `prefix:10.1109` Crossref title sweep and an OpenAlex title sweep both return nothing. **Do not cite 42(3):486–497.** Use `10.1007/s13042-011-0019-y` instead — it is the real, verifiable 2011 ELM survey, and it is now in this directory. + +One open-access status correction: + +* **`10.1007/s11042-021-11007-7` is listed as hybrid OA by OpenAlex, but its PDF cannot be fetched from here** — `link.springer.com/.../11007-7.pdf` answers `200 text/html` (a ~3 KB bot-challenge page), not a PDF. The green-OA copy at `ntu.edu.sg/.../ELM-Unified-Learning.pdf` now 404s. So it is listed as **not downloaded** below. MDPI likewise 403s on `www.mdpi.com/.../pdf`; `mdpi-res.com` works, which is what `fetch_papers.sh` uses. + +## Audit table + +| Claimed citation | Verdict | Correct identifier / real paper | +|---|---|---| +| arXiv:2512.21777 — "Online Learning ELM with Low-Complexity Predictive Plasticity Rule and FPGA Implementation" | **VERIFIED** (title differs only by spelling out "Extreme Learning Machine") | Zang, Li, Li — arXiv:2512.21777, 2025-12-25 | +| arXiv:2504.09028 — "…One-Sided Jacobi Rotation OSOS-ELM" | **VERIFIED (content)** / title wrong | Real title "Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing", Zang, Li, Li, 2025-04-12 | +| arXiv:2505.08129 — Liu & Cao, "High-order Regularization…" | **VERIFIED** | "High-order Regularization for Machine Learning and Learning-based Control", arXiv:2505.08129, 2025-05-13 | +| 10.1109/IJCNN.2017.7966094 — Park & Kim, "Online recurrent ELM … time-series prediction" | **VERIFIED** | Park Jin-Man & Kim Jong-Hwan, IJCNN 2017, **pp. 1983–1990** | +| 10.1002/er.8514 — Gu & Wang, BASO-optimized RELM | **VERIFIED** (full title longer) | "A beetle antennae search optimized recurrent extreme learning machine for battery state of charge estimation", *Int J Energy Res* **46(13):19190–19205, 2022** — BASO = Beetle Antennae Search Optimization | +| 10.1007/s10922-025-09976-3 — Shwaysh et al., J Real-Time Image Proc 2025 | **WRONG (venue)** | Shwaysh et al., *Journal of Network and Systems Management* **34(1), 2025**, "…Ensemble Recurrent Extreme Learning Machine for Enhanced Network Intrusion Detection Systems" | +| 10.3390/app7030217 — Lu, Huang, Lu, "Adaptive-Weight OS-ELM for time series", Appl Sci 7:217, 2017 | **VERIFIED** | "Time Series Prediction Based on Adaptive Weight Online Sequential Extreme Learning Machine", Lu Junjie, Huang Jinquan, Lu Feng, *Appl Sci* **7(3):217, 2017** — gold OA | +| 10.1016/j.neucom.2012.02.003 — Zhao, Wang, Park, forgetting mechanism | **VERIFIED** | *Neurocomputing* **87:79–89, 2012** | +| 10.1016/j.neucom.2009.02.013 — Lan, Soh, Huang, Ensemble of OSELM | **VERIFIED** | *Neurocomputing* **72(13–15):3391–3395, 2009** | +| 10.1109/TSMCS.2011.616645 — ELM survey DOI | **NOT FOUND** | 404 at doi.org, absent from Crossref and OpenAlex. No such DOI | +| 10.1109/tsmcb.2011.2168604 — Huang, "ELM: A Review and New Trends", 42(2):513–529 | **WRONG** | Same DOI = "Extreme Learning Machine for Regression and Multiclass Classification", Huang, **Zhou, Ding, Zhang**, T-SMC-B 42(2):513–529, 2012 | +| 10.1007/s13042-011-0019-y — Huang, Lan, Wang, "ELM: A Review", IJMLC 2(2):107–122 | **VERIFIED, author order wrong** | Crossref: **Huang, Wang, Lan** — "Extreme learning machines: a survey", *Int J Mach Learn Cybern* **2(2):107–122, 2011** | +| 10.1016/j.neunet.2017.04.001 — Yang et al., RL mean-p-power ELM | **VERIFIED, year off by one** | Yang, Ye, Rong, Chen, "Recursive least mean p-power Extreme Learning Machine", *Neural Networks* **91:22–33, 2017** (not 2018 — 2018 is the issue-print year) | +| 10.1109/codit.2018.8394791 — "A Survey of Online Sequential ELM", CoDIT 2018 | **VERIFIED, authors missing** | **Zhang Senyue, Tan Wenan, Li Yibo**, CoDIT 2018, **pp. 45–50** | +| `…/s11042-021-11008-7.pdf` | **NOT FOUND (typo)** | Correct: `…/s11042-021-11007-7.pdf` — Wang, Lu, Wang, Zhang, "A review on extreme learning machine", *Multimed Tools Appl* **81(29):41611–41660, 2021** | + +## Downloaded (open access) + +Files in this directory, all verified with `file` as real PDFs. + +### zang_2025_predictive_plasticity_elm_fpga.pdf +*Online Learning Extreme Learning Machine with Low-Complexity Predictive Plasticity Rule and FPGA Implementation* — Zhenya Zang, Xingda Li, David Day Uei Li. arXiv:2512.21777, submitted 2025-12-25. + · PDF: + +Replaces the ELM's one-shot matrix inverse with a local, biologically inspired +predictive-plasticity rule: weights change only on prediction error, and each +update is a sparse vector addition gated by a binary firing mask. Training cost +drops from O(M³) to O(M) in hidden nodes M, at a reported accuracy cost of 3.6 % +train / 2.0 % test, and is demonstrated on an FPGA. **Update rule: predictive +plasticity (spike/error-gated local delta) — not RLS.** The most interesting +paper here for a real-time aiming loop: it is the only one whose whole point is +O(M) per-sample cost with no inverse. + +### zang_2025_osos_elm_single_photon.pdf +*Towards On-Device Learning and Reconfigurable Hardware Implementation for Encoded Single-Photon Signal Processing* — Zhenya Zang, Xingda Li, David Day Uei Li. arXiv:2504.09028, submitted 2025-04-12. + · PDF: + +The hardware sibling of the above: an **OSOS-ELM** whose per-sample +inverse-covariance update is restructured as a **one-sided Jacobi rotation**, so +the RLS algebra becomes a sequence of rank-1 updates with no square matrix to +factor or invert. Evaluated against plain OS-ELM across hidden/input/output sizes +(comparable accuracy, better hardware efficiency) and implemented on a Xilinx +ZCU104 (multi-task ARM cores + pipelined logic fabric) and on a Jetson Xavier NX +GPU, with three single-photon case studies. **Update rule: one-sided Jacobi +rotation RLS (OSOS-ELM).** Same authors and line of work as the entry above. + +### liu_2025_high_order_regularization.pdf +*High-order Regularization for Machine Learning and Learning-based Control* — Xinghua Liu, Ming Cao. arXiv:2505.08129, submitted 2025-05-13. + · PDF: + +Generalises L2 ridge regularisation to a **high-order (matrix) regulariser**, +framing regularisation as an inverse-map approximation with an explicitly +computable error bound; L2 appears as the special first-order case. The authors +prove convergence, give lower/upper error bounds, and show the solution is a +contraction whose generalisation is maximised by a suitable regulariser matrix. +Includes an **incremental** HR solution for regularised ELM, plus an RL +value-approximation case study. **Update rule: none per se — it is the +regularisation term itself; supplies the incremental-solution framing that makes +the ridge `lambda` in an online ELM meaningful.** Relevant to `common_libs/guns/elm.nim`, +which currently uses a scalar `lambda`. + +### lu_2017_adaptive_weight_oselm.pdf +*Time Series Prediction Based on Adaptive Weight Online Sequential Extreme Learning Machine* — Junjie Lu, Jinquan Huang, Feng Lu. *Applied Sciences* 7(3):217, 2017. + · PDF: + +Plain OS-ELM on a fixed random hidden layer, but each hidden node's contribution +is re-weighted per sample so that nodes which keep losing prediction error are +down-weighted, which stabilises long non-stationary time-series runs. Reports +improved forecasting accuracy over vanilla OS-ELM on public time-series +benchmarks. **Update rule: recursive least squares (OS-ELM RLS) + per-node adaptive +sample weighting.** This is the closest published match to what +`common_libs/guns/elm.nim` already implements. + +## Manually supplied (paywalled — user-provided) + +One paper here was **not** fetched by `fetch_papers.sh`: it is closed-access +(`oa_status: closed`, no legal OA copy anywhere) and was supplied by hand. + +### huang_wang_lan_2011_elm_survey.pdf + +*Extreme learning machines: a survey* — **Guang-Bin Huang, Dian Hui Wang, Yuan Lan**, +*International Journal of Machine Learning and Cybernetics* **2(2):107–122, 2011**. +DOI **`10.1007/s13042-011-0019-y`** — + +Verified against both Crossref and OpenAlex (they agree on title, author order, +volume, issue and page range). The file is the **complete version of record**, +602314 bytes, md5 `547b4311cdb610fdf348d08107205907`, 16 pages = exactly the +printed range 107–122; the Springer DOI is printed on the title page and every +page footer reads `Int. J. Mach. Learn. & Cyber. (2011) 2:107–122`. Author order +is **Huang, Wang, Lan** (some citations wrongly give Huang, Lan, Wang). + +Note the bibliographic trap this paper sits in: it is frequently mis-attributed +to *Neurocomputing* 75 (2011) 3051–3060. No such Neurocomputing article exists — +a Crossref sweep of every 2011 Neurocomputing paper by this trio returns only +the ELM2010 editorial (`10.1016/j.neucom.2011.03.030`, 74(16):2411–2412). It is +also unrelated to the phantom "IEEE T-SMC-B 42(3):486–497" survey above. + +Content: the canonical ELM survey — the batch closed-form solution +`β = (HᵀH + λI)⁻¹HᵀT`, the universal-approximation theorem for SLFNs with +randomly generated hidden nodes, kernel ELM, and the full taxonomy of variants +including the OS-ELM/online-sequential family. **No single update rule** — it is +the map of the rules cited throughout this file. + +## Paywalled (not downloaded, cited for reference) + +OpenAlex reports `oa_status: closed` for all of these; no legal PDF exists to fetch. + +* **Park Jin-Man, Kim Jong-Hwan**, "Online recurrent extreme learning machine and its application to time-series prediction", *IJCNN 2017*, pp. 1983–1990. — **update rule: recurrent ELM** (ELM hidden layer fed back over time). +* **Gu Tianyu, Wang Dongqing**, "A beetle antennae search optimized recurrent extreme learning machine for battery state of charge estimation", *Int J Energy Res* 46(13):19190–19205, 2022. — **update rule: recurrent ELM, hyper-parameters tuned by BASO** (beetle antennae search metaheuristic). BASO tunes the network, it is not a per-sample online rule. +* **Shwaysh Mustafa Muslih** et al., "…Ensemble Recurrent Extreme Learning Machine for Enhanced Network Intrusion Detection Systems", *J Network Syst Manage* 34(1), 2025. — **update rule: ensemble** of RELM members (combined with autoencoder feature selection). +* **Zhao Jianwei, Wang Zhihui, Park Dong Sun**, "Online sequential extreme learning machine with forgetting mechanism", *Neurocomputing* 87:79–89, 2012. — **update rule: RLS + forgetting factor.** The canonical source for the `rho` knob; `elm.nim` already cites it. +* **Lan Yuan, Soh Yeng Chai, Huang Guang-Bin**, "Ensemble of online sequential extreme learning machine", *Neurocomputing* 72(13–15):3391–3395, 2009. — **update rule: ensemble** of independently trained OS-ELMs. +* **Huang Guang-Bin, Zhou Hongming, Ding Xiaojian, Zhang Rui**, "Extreme Learning Machine for Regression and Multiclass Classification", *IEEE T-SMC-B* 42(2):513–529, 2012. — **update rule: none** (batch ELM; the closed-form ridge solution β = (HᵀH + λI)⁻¹HᵀT). + +* **Yang Jing, Ye Feng, Rong Hai-Jun, Chen Badong**, "Recursive least mean p-power Extreme Learning Machine", *Neural Networks* 91:22–33, 2017. — **update rule: recursive least mean p-power (RLMP).** Like RLS but the gain is powered to *p* and normalised by the power of the activation, trading exactness for robustness — the right shape for noisy, drift-prone inputs. +* **Zhang Senyue, Tan Wenan, Li Yibo**, "A Survey of Online Sequential Extreme Learning Machine", *CoDIT 2018*, pp. 45–50. — **survey** of the OS-ELM family; the map of the rules above. +* **Wang Jian, Lu Siyuan, Wang Shui-Hua, Zhang Yu-Dong**, "A review on extreme learning machine", *Multimed Tools Appl* 81(29):41611–41660, 2021. — open access in principle, but **bot-blocked from this machine** (see CITATION NOTES). **survey**, no single rule. + +## Core OS-ELM RLS equations (plain text) + +Hidden layer is drawn once and frozen: `H = [g₁ … g_M]` with `g_j = act(W_j x + b_j)`. +Output weights `β` (M×C) start at zero; `P` starts at `P₀ = (1/η) I`. No epochs, one pass. + +Per sample `(x_t, y_t)`, with `g_t = act(W x_t + b_t)`: + +``` +g_t = act(W x_t + b_t) # frozen random hidden map + +# optional forgetting factor (Zhao, Wang & Park 2012) — do this FIRST: +# P <- P / rho rho = 1 → plain RLS, rho > 1 → old data decays +# NOTE: divide rho**2 into lambda below to keep the steady-state noise floor sane. + +K_t = P g_t / (lambda + g_t^T P g_t) # gain vector, no matrix inverse +beta_t = beta_{t-1} + K_t (y_t - g_t^T beta_{t-1}) # rank-1 weight correction +P_t = (I - K_t g_t^T) P_{t-1} # downdate the inverse correlation +``` + +Read `K_t` as: "how much of the current inverse correlation points along this +sample's hidden activation". `beta_t` only ever moves by a rank-1 step, so the +per-sample cost is O(M·C) plus one O(M²) downdate — versus the batch ELM's +O(M³) inverse. `P` is the inverse of `Σ_i g_i g_iᵀ + λI`, so the fixed point of +the recursion is exactly the ridge solution `β = (HᵀH + λI)⁻¹HᵀT`; RLS is that +solution, computed incrementally. + +Variants referenced above: + +* **Forgetting factor** (Zhao 2012) — insert `P ← P/ρ` before the update so the + fixed point becomes a exponentially-weighted least squares fit. `ρ = 1` is + exactly the equations above. +* **Ensemble** (Lan 2009, Shwaysh 2025) — run `N` independent copies (different + random hidden draws, different seeds) and average their outputs. Cost `N×`, + variance down. +* **Mean-p-power** (Yang 2017) — replace the gain with a powered, normalised + form: `K_t = P g_t / (lambda + ‖g_t‖_p^p)` style denominators, which caps the + influence of outlier activations instead of trusting them exactly. +* **One-sided Jacobi** (Zang 2025) — restructure `P`'s update as an explicit + sweep of one-sided Jacobi rotations so each step is a rank-1 rotation rather + than a matrix product; same fixed point, better pipelining on FPGA. +* **Predictive plasticity** (Zang 2025) — drop RLS entirely; `Δw ∝ (err) ⊙ mask` + on error only, O(M). \ No newline at end of file diff --git a/common_libs/guns/docs/fetch_papers.sh b/common_libs/guns/docs/fetch_papers.sh new file mode 100755 index 0000000..cb3fff1 --- /dev/null +++ b/common_libs/guns/docs/fetch_papers.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Re-download the open-access OS-ELM / ELM reference PDFs. +# Idempotent: skips files that already exist and are genuine PDFs. +# Fails loudly (exit 1) if a download does not yield a real PDF. +# +# Only papers verified open access in CITATION NOTES (see README.md) are listed. +# Paywalled items are deliberately absent - there is nothing to fetch. +# +# huang_wang_lan_2011_elm_survey.pdf (10.1007/s13042-011-0019-y, IJMLC 2(2):107-122) +# is paywalled with no OA copy and is deliberately NOT in this list: adding a +# publisher URL here would just curl a bot-challenge page. It was supplied by +# hand - see README.md "Manually supplied". This script only ever writes or +# removes the filenames listed below, so that file is never touched. +set -uo pipefail + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +UA='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36' +mkdir -p "$DIR" + +# name|url +PAPERS=( + "zang_2025_predictive_plasticity_elm_fpga.pdf|https://arxiv.org/pdf/2512.21777" + "zang_2025_osos_elm_single_photon.pdf|https://arxiv.org/pdf/2504.09028" + "liu_2025_high_order_regularization.pdf|https://arxiv.org/pdf/2505.08129" + "lu_2017_adaptive_weight_oselm.pdf|https://mdpi-res.com/d_attachment/applsci/applsci-07-00217/article_deploy/applsci-07-00217.pdf" +) + +fail=0 +for entry in "${PAPERS[@]}"; do + name="${entry%%|*}"; url="${entry#*|}"; out="$DIR/$name" + + if [ -s "$out" ] && file -b "$out" | grep -q '^PDF'; then + echo "SKIP $name (already present, $(stat -c%s "$out") bytes)" + continue + fi + + # MDPI blocks plain /pdf with a Referer-less request; arXiv does not care. + echo "GET $name <- $url" + if ! curl -fL -A "$UA" -H 'Referer: https://www.mdpi.com/' -H 'Accept: application/pdf,*/*' \ + --retry 3 --retry-delay 2 -o "$out" "$url"; then + echo "FAIL $name (curl error)" >&2; rm -f "$out"; fail=1; continue + fi + + if ! file -b "$out" | grep -q '^PDF'; then + echo "FAIL $name: not a PDF ($(file -b "$out"))" >&2 + rm -f "$out"; fail=1; continue + fi + echo "OK $name ($(stat -c%s "$out") bytes)" +done + +[ "$fail" -eq 0 ] || { echo "one or more downloads failed" >&2; exit 1; } +echo "all open-access papers present in $DIR" \ No newline at end of file diff --git a/common_libs/guns/elm.nim b/common_libs/guns/elm.nim new file mode 100644 index 0000000..6ea906e --- /dev/null +++ b/common_libs/guns/elm.nim @@ -0,0 +1,356 @@ +## 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..