diff --git a/DevControlBot_garage/DevControlBot/DevControlBot.nimble b/DevControlBot_garage/DevControlBot/DevControlBot.nimble index b76c6ce..ae9b06e 100644 --- a/DevControlBot_garage/DevControlBot/DevControlBot.nimble +++ b/DevControlBot_garage/DevControlBot/DevControlBot.nimble @@ -253,3 +253,4 @@ task runBot, "Compile, run and clean up the bot": task test, "Run unit tests": exec "nim c -r --hints:off ../tests/test_elm.nim" + exec "nim c -r --hints:off ../tests/test_online.nim" diff --git a/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim b/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim index 2d9203e..b5a4f7f 100644 --- a/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim +++ b/DevControlBot_garage/DevControlBot/modules/ELM/elm_gun.nim @@ -63,13 +63,41 @@ const ## unclamped outlier on a stale belief would point the ## gun into the wall. + ## ── ONLINE LEARNING knobs (see README "Online-learning gun") ──────────── + OnlineDecay* = 0.999 ## forgetting within the battle (reused tuning) + OnlineRefitEvery* = 25 ## shots between closed-form refits (reused tuning) + OnlineMinSamples* = 12 ## gate stays CLOSED below this many online samples + GateRatio* = 0.95 ## gate opens only when modelErr < ratio * zeroErr + OnlineEmaAlpha* = 0.08 ## EMA memory for the held-out gate error (~12 samples) + TraceCap* = 256 ## per-tick enemy position history for delayed labels + TraceTolTicks* = 3 ## label lookup tolerance: nearest scan within this + MaxPending* = 64 ## fired-but-unresolved shots kept at once + type ElmGun* = ref object - model*: Elm ## the loaded model (never refitted in-game) + model*: Elm ## the model, trained ONLINE during the battle loaded*: bool gateTau*: float ## |correction| below this -> geometric aim lastCorrection*: float ## last raw ELM output, rad — the calibration ## probe the battle harness reads + ## ── online state ────────────────────────────────────────────────────── + online*: bool ## true: feed delayed-label samples in-game + priorBeta*: seq[float64] ## the loaded output layer, BEFORE scaling + priorScale*: float64 ## 0.0 = neutral start; >0 = weak-prior start + pending*: seq[PendingShot] ## fired shots whose true impact is not due yet + traceTick*: seq[int] ## per-tick enemy positions (delayed labels) + traceX*, traceY*: seq[float64] + nOnline*: int ## samples resolved for THIS opponent + modelErr*: float64 ## EMA of (model pred - label)^2, held-out style + zeroErr*: float64 ## EMA of label^2 = zero-correction error + gateOpen*: bool ## novelty gate: correction applied only if true + + PendingShot* = object + ## One fired shot waiting for its label. Keyed by `dueTick`. + feat*: array[FeatureDim, float64] + base*: float64 ## geometric intercept bearing at fire time + selfX*, selfY*: float64 ## our position at fire time + dueTick*: int ## fire tick + time-of-flight in ticks GunAim* = object aim*: float ## ABSOLUTE bearing (rad) to point the gun at @@ -146,11 +174,112 @@ proc loadWeightsFile(g: ElmGun, path: string): bool = g.loaded = true true -proc initElmGun*(path: string = ""): ElmGun = - ## Build the gun and load its weights. `loaded` says whether the learned - ## correction is available; a caller may fall back to the heuristic. +proc initElmGun*(path: string = "", priorScale: float64 = 0.0): ElmGun = + ## Build the gun and load its hidden layer + output prior. `priorScale = 0` + ## starts NEUTRAL (zero output weights, learns purely online); `priorScale > 0` + ## starts from the pooled pretrained `beta` scaled down by that factor. The + ## hidden layer is always the pretrained one so the two arms share W/hs and + ## differ only in the output-layer starting point. new(result) - discard loadWeightsFile(result, if path.len > 0: path else: defaultWeightsPath()) + result.priorScale = priorScale + result.online = true + if not loadWeightsFile(result, if path.len > 0: path else: defaultWeightsPath()): + return + # Online mode: reuse the held-out-validated decay/refit tuning instead of the + # batch defaults the weights file was exported with (decay 1.0 / refit 0). + result.model.setOnlineParams(OnlineDecay, OnlineRefitEvery) + result.priorBeta = result.model.exportWeights().beta + if priorScale == 0.0: + result.model.reset() # neutral: zero beta, no samples + else: + var b = newSeq[float64](result.priorBeta.len) + for i in 0 ..< b.len: b[i] = result.priorBeta[i] * priorScale + let w = result.model.exportWeights() + result.model.loadWeights(ElmWeights(W: w.W, hs: w.hs, beta: b)) + +proc resetOnline*(g: ElmGun) = + ## New opponent => drop every online sample and restore the starting output + ## layer (neutral, or the scaled pooled prior). Hidden W/hs are never redrawn. + g.pending.setLen(0) + g.traceTick.setLen(0) + g.traceX.setLen(0) + g.traceY.setLen(0) + g.nOnline = 0 + g.modelErr = 0.0 + g.zeroErr = 0.0 + g.gateOpen = false + g.model.reset() + if g.priorScale > 0.0 and g.priorBeta.len > 0: + var b = newSeq[float64](g.priorBeta.len) + for i in 0 ..< b.len: b[i] = g.priorBeta[i] * g.priorScale + let w = g.model.exportWeights() + g.model.loadWeights(ElmWeights(W: w.W, hs: w.hs, beta: b)) + +proc noteEnemyAt*(g: ElmGun, tick: int, x, y: float64) = + ## Append one observed enemy position to the trace that delayed labels read. + g.traceTick.add tick + g.traceX.add x + g.traceY.add y + if g.traceTick.len > TraceCap: + g.traceTick.delete(0) + g.traceX.delete(0) + g.traceY.delete(0) + +proc tracePos(g: ElmGun, dueTick: int): tuple[ok: bool, x, y: float64] = + ## Nearest traced enemy position to `dueTick`, within TraceTolTicks. + var best = TraceTolTicks + 1 + for i in 0 ..< g.traceTick.len: + let dt = abs(g.traceTick[i] - dueTick) + if dt < best: + best = dt + result = (true, g.traceX[i], g.traceY[i]) + +proc updateGate(g: ElmGun) = + ## Novelty gate. Closed until enough ONLINE samples exist, then open only while + ## the model predicts the true correction better than assuming zero. Being + ## closed means the exact geometric intercept — never worse than baseline. + if g.nOnline < OnlineMinSamples: + g.gateOpen = false + else: + g.gateOpen = g.modelErr < GateRatio * g.zeroErr + +proc feedSample*(g: ElmGun, feat: openArray[float64], label: float64) = + ## One resolved delayed-label sample. The CURRENT model is scored against the + ## label BEFORE it trains on it, so `modelErr` is a genuine held-out error, and + ## `zeroErr` is what always aiming at the plain intercept would have cost. + if g.nOnline > 0: + let pred = g.model.infer(feat)[0] + let e = pred - label + let a = OnlineEmaAlpha + g.modelErr = (1.0 - a) * g.modelErr + a * e * e + g.zeroErr = (1.0 - a) * g.zeroErr + a * label * label + g.model.train(feat, @[label]) + inc g.nOnline + g.updateGate() + +proc recordShot*(g: ElmGun, feat: array[FeatureDim, float64], base, selfX, + selfY: float64, dueTick: int) = + ## Enqueue a fired shot; its label only exists `tof` ticks from now. + if g.pending.len >= MaxPending: + g.pending.delete(0) + g.pending.add PendingShot(feat: feat, base: base, selfX: selfX, selfY: selfY, + dueTick: dueTick) + +proc drainPending*(g: ElmGun, nowTick: int) = + ## Resolve (or drop) every shot whose flight time has elapsed. Reads the + ## enemy's actual position from the trace and trains on + ## wrap(trueImpactBearing - geometricInterceptBearing), the validated label. + var i = 0 + while i < g.pending.len: + let p = g.pending[i] + if nowTick < p.dueTick: + inc i + continue + let tp = g.tracePos(p.dueTick) + if tp.ok: + let trueBearing = arctan2(tp.y - p.selfY, tp.x - p.selfX) + g.feedSample(p.feat, wrapAngle(trueBearing - p.base)) + g.pending.delete(i) proc heuristicAim*(gun: ElmGun, b: GunBelief, power: float64 = FirePower): float = ## Baseline A: plain geometric intercept, no learning. Returns the ABSOLUTE @@ -165,6 +294,8 @@ proc elmCorrection*(g: ElmGun, b: GunBelief, power: float64 = FirePower): float ## The ELM's predicted aim error in radians, clamped to +-MaxAimShift. ## NaN when the model is unavailable or we have never scanned anything. if not g.loaded or not b.everScanned: return NaN + if g.online and not g.gateOpen: + return 0.0 # novelty gate closed: exact intercept var bb = b bb.power = power bb.bulletSpeed = 20.0 - 3.0 * power # physical speed, matches heuristicAim diff --git a/DevControlBot_garage/tests/test_online.nim b/DevControlBot_garage/tests/test_online.nim new file mode 100644 index 0000000..2682fb1 --- /dev/null +++ b/DevControlBot_garage/tests/test_online.nim @@ -0,0 +1,77 @@ +## Unit tests for the ONLINE-learning gun (elm_gun.nim): the delayed-label +## queue, the novelty gate, and the per-opponent reset. +## Run: nim c -r tests/test_online.nim (from DevControlBot_garage/) + +import std/math +import modules/ELM/elm_gun +import modules/ELM/elm_features +import modules/ELM/elm # for Elm.infer in the assertions + +var failed = 0 +proc check(name: string, cond: bool, detail: string = "") = + if cond: echo " ok ", name + else: echo " FAIL ", name, " [", detail, "]"; inc failed + +# ── 1. neutral start: no prior, gate closed ───────────────────────────────── +block: + echo "test 1: neutral start" + let g = initElmGun(priorScale = 0.0) + check("weights loaded", g.loaded) + check("prior stored", g.priorBeta.len > 0) + check("nOnline == 0", g.nOnline == 0) + check("gate closed at start", not g.gateOpen) + +# ── 2. online learning opens the gate once it beats zero ──────────────────── +block: + echo "test 2: online learning closes then opens the novelty gate" + let g = initElmGun(priorScale = 0.0) + let feat = newSeq[float64](FeatureDim) # constant feature vector + for i in 0 ..< 60: + g.feedSample(feat, 0.3) # constant true correction + check("accumulated samples", g.nOnline == 60) + check("model beats zero (modelErr < zeroErr)", g.modelErr < g.zeroErr, + $g.modelErr & " vs " & $g.zeroErr) + check("gate OPEN after learning", g.gateOpen) + let corr = g.model.infer(feat)[0] + check("correction near label", abs(corr - 0.3) < 0.1, $corr) + +# ── 3. a model that cannot beat zero keeps the gate shut ──────────────────── +block: + echo "test 3: no-signal data keeps the gate closed" + let g = initElmGun(priorScale = 0.0) + let feat = newSeq[float64](FeatureDim) + for i in 0 ..< 40: + g.feedSample(feat, 0.0) # label is exactly zero + check("gate stays closed on zero labels", not g.gateOpen) + +# ── 4. delayed-label queue: keyed by dueTick, needs the trace ─────────────── +block: + echo "test 4: pending queue resolves at dueTick" + let g = initElmGun(priorScale = 0.0) + let feat: array[FeatureDim, float64] = default(array[FeatureDim, float64]) + let due = 50 + g.noteEnemyAt(due, 100.0, 0.0) # target straight ahead of (0,0) + g.recordShot(feat, 0.0, 0.0, 0.0, due) # base bearing 0, due at tick 50 + g.drainPending(due - 1) + check("nothing resolved before dueTick", g.nOnline == 0 and g.pending.len == 1) + g.drainPending(due) + check("resolved at dueTick", g.nOnline == 1 and g.pending.len == 0) + +# ── 5. reset returns to the neutral start ─────────────────────────────────── +block: + echo "test 5: resetOnline clears per-opponent state" + let g = initElmGun(priorScale = 0.0) + let feat = newSeq[float64](FeatureDim) + for i in 0 ..< 60: g.feedSample(feat, 0.3) + g.noteEnemyAt(1, 1.0, 1.0) + g.recordShot(default(array[FeatureDim, float64]), 0.0, 0.0, 0.0, 5) + g.resetOnline() + check("nOnline cleared", g.nOnline == 0) + check("gate closed after reset", not g.gateOpen) + check("pending cleared", g.pending.len == 0) + check("trace cleared", g.traceTick.len == 0) + +if failed > 0: + echo "\n", failed, " check(s) FAILED" + quit(1) +echo "\nall online checks passed"