## The ELM GUN — a movement-prediction corrector on top of the geometric ## intercept. ## ## ## What it predicts ## ## The ELM predicts the ENEMY'S FUTURE POSITION, expressed as a correction to ## the plain geometric intercept: at fire time the classic intercept gives a ## base aim point, the ELM estimates `trueImpactBearing - baseBearing` from the ## enemy's recent motion window, and the gun adds the two. That is a movement ## predictor, NOT the old opponent-aim-bias model (which measured how far the ## OTHER bot's shots missed and is deleted). ## ## ## The baseline and the gate ## ## `heuristicAim` is the plain geometric intercept — dead-reckon the target from ## the last two scans, lead it by d/bulletSpeed. The learned correction is ## applied ONLY when `|correction| > gateTau`, the threshold calibrated on ## held-out folds (see `train_predict.nim`); below it the gun returns the exact ## geometric aim, so a small noisy nudge can never make the ELM worse than the ## baseline. ## ## ## Weights file ## ## `elm_gun_weights.txt` next to this file, written by ## `tools/elm_bench/train_predict.nim`. Plain text, one matrix per line, flat: ## ## # comment lines are ignored ## ## W hidden weights, ROW-major ## HS hidden-layer biases, b_j ## BETA <(hiddenDim+1)*outputs vals> output weights, ROW-major ## TRAIN_RMSE training RMSE at export time; diagnostic only, unused. ## GATE_TAU correction magnitude below which correction is 0. ## ## It is a data file, not code: deleting it costs the bot its learned correction, ## nothing else. ## ## ## In-game honesty ## ## Nothing here reads a ground truth. `GunBelief` is assembled by the caller ## from the bot's own state and its own scan history, and `buildFeatures` ## (elm_features.nim) is the same function the trainer fed the corpus through. import std/[math, os, sequtils, strutils] import ./elm import ./elm_features const DefaultWeightsFile* = "elm_gun_weights.txt" ## next to THIS source file FirePower* = 2.0'f64 ## The corpus is dominated by ## mid-power shots (1.95 is ## its mode, 2795 rows; power 3.0 ## has 61), and `power` / ## `bulletSpd` ARE model ## features, so firing at 2.0 ## keeps the in-game feature ## distribution inside the ## trained one. Damage per hit ## is 8 instead of 12. MaxAimShift* = 0.5 ## rad. The learned correction is clamped: the fit law is ## label ~= 0.87 * predErr + 0.04 rad, but a 0.5 rad ## correction is already a full miss at any range, and an ## 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 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 x*, y*: float ## the same point as absolute coordinates ## (GunPrediction's contract, see ## common_libs/gun_harness/gun_interface.nim) confidence*: float ## 0.0 = no signal: this is a deterministic ## geometric aim, it casts no composite vote correction*: float ## the learned part, 0 for the baseline proc defaultWeightsPath(): string = ## Resolved at compile time from this file's own location, so the current ## working directory at bot start does not matter. currentSourcePath().parentDir / DefaultWeightsFile proc readFloats(f: File, n: int, path: string): seq[float64] = ## `n` space-separated floats, spread over as many lines as needed. result = newSeq[float64](n) var got = 0 var line: string while got < n: if f.readLine(line) == false: echo "[elm_gun] ", path, ": truncated, wanted ", n, " floats, got ", got return @[] for t in line.strip().splitWhitespace(): if got >= n: break result[got] = t.parseFloat() inc got if got < n: return @[] proc loadWeightsFile(g: ElmGun, path: string): bool = ## Parse the format above into the live ELM. Returns false (and says why) ## instead of raising: a bot with no gun is still a working bot, and the ## harness must be able to report "ELM unavailable" rather than crash. if not fileExists(path): echo "[elm_gun] no weights at ", path, " — gun disabled" return false var cfg: ElmConfig var haveCfg = false var w, hs, beta: seq[float64] var f = open(path, fmRead) defer: f.close() var line: string while f.readLine(line): let t = line.strip() if t.len == 0 or t.startsWith("#"): continue let parts = t.splitWhitespace() case parts[0] of "W": w = readFloats(f, cfg.hiddenDim * cfg.inputDim, path) of "HS": hs = readFloats(f, cfg.hiddenDim, path) of "BETA": beta = readFloats(f, (cfg.hiddenDim + 1) * cfg.outputs, path) of "TRAIN_RMSE": discard of "GATE_TAU": g.gateTau = parts[1].parseFloat() else: # header row cfg = ElmConfig(inputDim: parts[0].parseInt(), hiddenDim: parts[1].parseInt(), outputs: parts[2].parseInt(), lambda: parts[3].parseFloat(), decay: parts[4].parseFloat(), seed: parseBiggestInt(parts[5]).int64, activation: parseActivation(parts[6]), refitEvery: 0) haveCfg = true continue # a matrix tag: an empty read means the file was truncated mid-matrix if (parts[0] == "W" and w.len == 0) or (parts[0] == "HS" and hs.len == 0) or (parts[0] == "BETA" and beta.len == 0): return false if not haveCfg or w.len == 0 or hs.len == 0 or beta.len == 0: echo "[elm_gun] ", path, ": incomplete weight file — gun disabled" return false if cfg.inputDim != FeatureDim: echo "[elm_gun] ", path, ": trained for ", cfg.inputDim, " features, this ", "build has ", FeatureDim, " — gun disabled" return false g.model = initElm(cfg) g.model.loadWeights(ElmWeights(W: w, hs: hs, beta: beta)) g.loaded = true true 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) 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 ## bearing to aim at, or NaN when there is no belief at all. if not b.everScanned: return NaN let v = 20.0 - 3.0 * power let d = hypot(b.ex - b.selfX, b.ey - b.selfY) let tof = d / v # one iteration, exact for a constant bullet speed arctan2(b.ey + b.vy * tof - b.selfY, b.ex + b.vx * tof - b.selfX) 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 let feat = buildFeatures(bb) let corr = g.model.infer(feat.toSeq())[0] g.lastCorrection = corr if abs(corr) <= g.gateTau: return 0.0 # gate closed: exact geometric aim clamp(corr, -MaxAimShift, MaxAimShift) proc predictAim*(g: ElmGun, b: GunBelief, power: float64 = FirePower, useElm: bool = true): GunAim = ## The gun's per-tick output, GunPrediction-shaped. `useElm = false` is the ## pure-heuristic baseline; it is the same call with the learned term switched ## off, so the two differ by exactly one thing. let base = heuristicAim(g, b, power) if base.isNaN: return GunAim(aim: NaN, confidence: 0.0) let d = hypot(b.ex - b.selfX, b.ey - b.selfY) result = GunAim(aim: base, x: b.selfX + d * cos(base), y: b.selfY + d * sin(base), confidence: 0.0) if not useElm or not g.loaded: return let corr = elmCorrection(g, b, power) if corr.isNaN: return result.aim = base + corr result.x = b.selfX + d * cos(result.aim) result.y = b.selfY + d * sin(result.aim) result.confidence = abs(corr) result.correction = corr