Extractors, benchmarks and analysis for "can we predict an opponent's aim error from our own belief state?". All labels come from BulletFiredEvents; all features come only from the shooter's own state and its ScannedBotEvent history (the target's true state is used for the label and never for a feature, verified by a ground-truth-poisoning re-extraction). extract.py / extract_realistic.py label + oracle features / realistic ones gen_analysis.py, analyse_realistic.py, audit_independent.py bench.nim, bench_realistic.nim, cross_opponent.nim, online.nim gen/*.ndjson the per-opponent sample tables README.md the write-up, ~1200 lines Headline: DrussGT applies about 13% of the correct lead, and that 13% is computable from one feature (beliefPredErr) as label ~ 0.8663*predErr + 0.0418. ELM ALL-21 pools to RMSE 0.4220 against a constant 1.1463 (-63%). The network is not the finding; the single linear term is. Cross-opponent, --prev leakage audit and an independent re-derivation are in the README. The top-level samples_realistic*.ndjson are byte-identical to gen/DrussGT* and are gitignored; gen/ is the authoritative copy.
310 lines
12 KiB
Nim
310 lines
12 KiB
Nim
#!/usr/bin/env nim c -r
|
|
# ONLINE / ADAPTIVE LEARNING experiments A, B, C for the ELM gun.
|
|
#
|
|
# nim c -r --path:../../DevControlBot_garage/DevControlBot online.nim
|
|
#
|
|
# Everything is temporal: samples are fed in capture order, never shuffled.
|
|
# Uses the real ELM module (DevControlBot_garage/DevControlBot/modules/ELM).
|
|
import std/[math, os, strutils, strformat, json, times]
|
|
import ../../DevControlBot_garage/DevControlBot/modules/ELM/elm
|
|
|
|
const
|
|
FD = 22 # feature count
|
|
H = 128
|
|
LAM = 1e-2
|
|
SEED = 42
|
|
GEN = "gen"
|
|
DECAYS: seq[float64] = @[1.0, 0.999, 0.99, 0.95, 0.9]
|
|
REFIT_EVERY = 25 # shots between refits (see EXPERIMENT C timing)
|
|
WIN = 100 # window for the per-shot error curve
|
|
POOLCAP = 600 # max samples per corpus in the pooled priors (timing cap)
|
|
ONLINE_A = 700 # shots streamed per held-out opponent in Experiment A
|
|
|
|
type
|
|
Samp = object
|
|
x: array[64, float64]
|
|
y: float64
|
|
Corp = object
|
|
name: string
|
|
d: seq[Samp]
|
|
|
|
proc vecOf(j: JsonNode): array[64, float64] =
|
|
var s: seq[float64] = @[
|
|
j["beliefDist"].getFloat / 1000.0,
|
|
1.0 / (1.0 + j["beliefDist"].getFloat / 100.0),
|
|
j["beliefSinRelBearing"].getFloat,
|
|
j["beliefCosRelBearing"].getFloat,
|
|
j["beliefTgtSpeed"].getFloat / 10.0,
|
|
j["bulletSpeed"].getFloat / 20.0,
|
|
min(max(j["beliefScanAge"].getFloat, 0.0), 30.0) / 30.0,
|
|
math.ln(1.0 + min(max(j["beliefScanAge"].getFloat, 0.0), 60.0)) / 4.0,
|
|
j["beliefEverScanned"].getFloat,
|
|
min(j["beliefScanGap"].getFloat, 30.0) / 30.0,
|
|
math.sin(j["beliefPredRelBearing"].getFloat),
|
|
math.cos(j["beliefPredRelBearing"].getFloat),
|
|
j["beliefPredErr"].getFloat / PI,
|
|
j["beliefLosRate"].getFloat,
|
|
j["beliefTof"].getFloat / 30.0,
|
|
j["beliefClosing"].getFloat / 10.0,
|
|
j["gunHeat"].getFloat / 3.0,
|
|
j["power"].getFloat / 3.0,
|
|
j["ownSpeed"].getFloat / 10.0,
|
|
j["beliefDisp"].getFloat / 100.0,
|
|
j["round"].getFloat / 10.0,
|
|
j["tick"].getFloat / 1000.0,
|
|
math.sin(j["beliefRelBearing"].getFloat)]
|
|
for p in 0 ..< s.len: result[p] = s[p]
|
|
|
|
proc load(name: string): Corp =
|
|
result.name = name
|
|
for line in lines(GEN / name & ".ndjson"):
|
|
if line.len == 0: continue
|
|
let j = parseJson(line)
|
|
result.d.add Samp(x: vecOf(j), y: j["label"].getFloat)
|
|
|
|
proc newElm(decay: float64): Elm =
|
|
initElm(ElmConfig(inputDim: FD, hiddenDim: H, outputs: 1, seed: SEED,
|
|
lambda: LAM, decay: decay, refitEvery: REFIT_EVERY))
|
|
|
|
proc rmseOf(pred, ys: seq[float64], lo, hi: int): float64 =
|
|
if hi <= lo: return 0.0
|
|
var s2 = 0.0
|
|
for i in lo ..< hi: s2 += (pred[i] - ys[i]) * (pred[i] - ys[i])
|
|
sqrt(s2 / float64(hi - lo))
|
|
|
|
proc maeOf(pred, ys: seq[float64], lo, hi: int): float64 =
|
|
if hi <= lo: return 0.0
|
|
var s = 0.0
|
|
for i in lo ..< hi: s += abs(pred[i] - ys[i])
|
|
s / float64(hi - lo)
|
|
|
|
proc predictAll(e: Elm, d: seq[Samp]): seq[float64] =
|
|
result = newSeq[float64](d.len)
|
|
for i, s in d: result[i] = infer(e, s.x.toOpenArray(0, FD - 1))[0]
|
|
|
|
proc curve(pred, ys: seq[float64], w: int): seq[float64] =
|
|
result = newSeq[float64](pred.len)
|
|
var s2 = 0.0; var sa = 0.0; var n = 0
|
|
for i in 0 ..< pred.len:
|
|
let d = pred[i] - ys[i]
|
|
s2 += d * d; sa += abs(d); inc n
|
|
if i >= w: # sliding window
|
|
let od = pred[i - w] - ys[i - w]
|
|
s2 -= od * od; sa -= abs(od); dec n
|
|
result[i] = sqrt(s2 / float64(max(n, 1)))
|
|
# mae curve stored in a side channel is overkill; callers recompute
|
|
|
|
# first index where cur stays below target for the rest of the curve
|
|
proc crossover(cur, target: seq[float64]): int =
|
|
## first shot from which the adaptive model stays below the reference for good
|
|
var lastAbove = -1
|
|
for i in 0 ..< cur.len:
|
|
if cur[i] >= target[i]: lastAbove = i
|
|
result = lastAbove + 1
|
|
|
|
proc firstBelow(cur: seq[float64], target: float64, lo: int): int =
|
|
result = -1
|
|
for i in lo ..< cur.len:
|
|
if cur[i] < target: result = i; break
|
|
|
|
var corps: seq[Corp]
|
|
for f in walkFiles(GEN / "*.ndjson"):
|
|
if f.endsWith("_prev.ndjson"): continue
|
|
corps.add load(f.splitFile().name.replace(".ndjson", ""))
|
|
|
|
echo fmt"corpora: {corps.len} features={FD} H={H} lambda={LAM} refitEvery={REFIT_EVERY}"
|
|
echo fmt"POOLCAP={POOLCAP}/corpus, ONLINE_A={ONLINE_A} shots/corpora, window={WIN}"
|
|
for c in corps:
|
|
var m = 0.0
|
|
for s in c.d: m += s.y
|
|
echo fmt" {c.name:<14} n={c.d.len:<6} mean={m/float64(c.d.len):+.4f}"
|
|
|
|
proc idxOf(nm: string): int =
|
|
for i, c in corps:
|
|
if c.name == nm: return i
|
|
return -1
|
|
|
|
proc pooled(corps: seq[Corp], skip: int, decay: float64): Elm =
|
|
## Shipped priors: every corpus except the held-out one, same cfg.
|
|
result = newElm(decay)
|
|
for i, c in corps:
|
|
if i == skip: continue
|
|
var m = POOLCAP
|
|
for s in c.d:
|
|
if m <= 0: break
|
|
train(result, s.x.toOpenArray(0, FD - 1), [s.y]); dec m
|
|
|
|
proc constantPred(d: seq[Samp]): seq[float64] =
|
|
## Live-legal constant baseline: running mean of labels seen SO FAR
|
|
## (a bot can only predict its opponent's mean from observed shots).
|
|
result = newSeq[float64](d.len)
|
|
var m = 0.0; var n = 0
|
|
for i, s in d:
|
|
result[i] = m
|
|
m += s.y; inc n
|
|
m /= float64(n)
|
|
|
|
# ─────────────────────────────────────────────────────── EXPERIMENT A ──────
|
|
echo "\n================ EXPERIMENT A: within-enemy adaptation speed ================"
|
|
echo "pooled priors trained on 8 corpora, held-out corpus streamed one shot at a time"
|
|
echo "crossover = first shot from which the windowed RMSE stays below the reference\n"
|
|
|
|
echo " held-out decay poolOnly crossovershot finalRMSE(win) vs const%"
|
|
let only = commandLineParams()
|
|
proc want(x: string): bool = only.len == 0 or x in only
|
|
let heldOut = ["Phoenix", "CassiusClay", "Dookious"]
|
|
if want("a"):
|
|
for skip in 0 ..< corps.len:
|
|
if corps[skip].name notin heldOut: continue
|
|
let test = corps[skip]
|
|
let n = min(test.d.len, ONLINE_A)
|
|
var ys = newSeq[float64](n)
|
|
for i in 0 ..< n:
|
|
ys[i] = test.d[i].y
|
|
let cp = constantPred(test.d[0 ..< n])
|
|
var ccurve = newSeq[float64](n)
|
|
var s2 = 0.0; var sa = 0.0; var cnt = 0
|
|
for i in 0 ..< n:
|
|
let d = cp[i] - ys[i]
|
|
s2 += d * d; sa += abs(d); inc cnt
|
|
if i >= WIN:
|
|
let od = cp[i - WIN] - ys[i - WIN]
|
|
s2 -= od * od; sa -= abs(od); dec cnt
|
|
ccurve[i] = sqrt(s2 / float64(max(cnt, 1)))
|
|
for decay in DECAYS:
|
|
let e = pooled(corps, skip, decay)
|
|
refit(e)
|
|
let ppred = predictAll(e, test.d[0 ..< n]) # static pooled, no adaptation
|
|
var pcurve = newSeq[float64](n)
|
|
var q2 = 0.0; var qn = 0
|
|
for i in 0 ..< n:
|
|
q2 += (ppred[i] - ys[i]) * (ppred[i] - ys[i]); inc qn
|
|
if i >= WIN: q2 -= (ppred[i - WIN] - ys[i - WIN]) * (ppred[i - WIN] - ys[i - WIN]); dec qn
|
|
pcurve[i] = sqrt(q2 / float64(max(qn, 1)))
|
|
# online: score shot i BEFORE training on it, then train, refit every k
|
|
var pred = newSeq[float64](n)
|
|
for i in 0 ..< n:
|
|
pred[i] = infer(e, test.d[i].x.toOpenArray(0, FD - 1))[0]
|
|
train(e, test.d[i].x.toOpenArray(0, FD - 1), [ys[i]])
|
|
let acurve = curve(pred, ys, WIN)
|
|
let xc = crossover(acurve, pcurve)
|
|
let xk = crossover(acurve, ccurve)
|
|
let fin = rmseOf(pred, ys, max(0, n - WIN), n)
|
|
let finC = rmseOf(cp, ys, max(0, n - WIN), n)
|
|
let tag = if xc < n: $xc else: "never"
|
|
let tagC = if xk < n: $xk else: "never"
|
|
echo fmt" {test.name:<14} {decay:<7.3f} {pcurve[n-1]:.4f} const@{tagC:<6} {fin:.4f} {100*(fin-finC)/finC:+.1f}% (vs pool crosses@{tag})"
|
|
|
|
# ─────────────────────────────────────────────────────── EXPERIMENT B ──────
|
|
echo "\n================ EXPERIMENT B: opponent switch / forgetting ================"
|
|
echo "sequence pooled-prior -> A(M shots) -> B(M shots) -> C(M shots)"
|
|
echo "reconvergence = shots into the new opponent until windowed RMSE <= the B-only reference\n"
|
|
|
|
let M = 400
|
|
echo " sequence decay segRMSE(win) refRMSE delta%"
|
|
let allSeqs: seq[seq[string]] = @[@["Phoenix", "CassiusClay"], @["CassiusClay", "Phoenix"],
|
|
@["Phoenix", "CassiusClay", "Dookious"]]
|
|
for names in (if want("b"): allSeqs else: @[]):
|
|
for decay in DECAYS:
|
|
# reference: model trained ONLY on the second opponent's data (its own ceiling)
|
|
let lastName = names[^1]
|
|
let ci = idxOf(lastName)
|
|
let solo = newElm(1.0)
|
|
for s in corps[ci].d:
|
|
train(solo, s.x.toOpenArray(0, FD - 1), [s.y])
|
|
refit(solo)
|
|
let soloPred = predictAll(solo, corps[ci].d)
|
|
var ys = newSeq[float64](corps[ci].d.len)
|
|
for i, s in corps[ci].d:
|
|
ys[i] = s.y
|
|
let refRmse = rmseOf(soloPred, ys, 0, min(M, corps[ci].d.len))
|
|
|
|
let e = pooled(corps, idxOf(names[0]), decay)
|
|
var segs: seq[float64]
|
|
for nm in names:
|
|
let k = idxOf(nm)
|
|
let d = corps[k].d
|
|
let m = min(M, d.len)
|
|
var pred = newSeq[float64](m)
|
|
var yy = newSeq[float64](m)
|
|
for i in 0 ..< m:
|
|
pred[i] = infer(e, d[i].x.toOpenArray(0, FD - 1))[0]
|
|
yy[i] = d[i].y
|
|
train(e, d[i].x.toOpenArray(0, FD - 1), [d[i].y])
|
|
segs.add rmseOf(pred, yy, max(0, m - WIN), m)
|
|
var line = " " & names.join("->").align(24) & " " & $decay & " "
|
|
for v in segs: line &= fmt"{v:.4f} "
|
|
line &= fmt" {refRmse:.4f} {100.0*(segs[^1]-refRmse)/refRmse:+.1f}%"
|
|
echo line
|
|
|
|
# reconvergence + dip, detailed for A->B
|
|
echo "\n== reconvergence / dip detail (Phoenix -> CassiusClay, M={M} each) =="
|
|
echo " decay dipMax% dipAtShot reconvShots finalSegRMSE BonlyRMSE"
|
|
for decay in (if want("b"): DECAYS else: @[]):
|
|
let k = idxOf("Phoenix")
|
|
let ci = idxOf("CassiusClay")
|
|
let bd = corps[ci].d
|
|
let m2 = min(M, bd.len)
|
|
# online model: pooled priors (all but Phoenix) + M shots of Phoenix
|
|
let e = newElm(decay)
|
|
for i2, c in corps:
|
|
if i2 == k: continue
|
|
var m = POOLCAP
|
|
for s in c.d:
|
|
if m <= 0: break
|
|
train(e, s.x.toOpenArray(0, FD - 1), [s.y]); dec m
|
|
let pd = corps[k].d
|
|
let m1 = min(M, pd.len)
|
|
for i in 0 ..< m1:
|
|
train(e, pd[i].x.toOpenArray(0, FD - 1), [pd[i].y])
|
|
# static pooled reference on B's first M shots = what the shipped gun does
|
|
let stat = pooled(corps, k, decay)
|
|
let ppred = predictAll(stat, bd[0 ..< m2])
|
|
var pcurve = newSeq[float64](m2)
|
|
var q2 = 0.0; var qn = 0
|
|
var pred = newSeq[float64](m2); var yy = newSeq[float64](m2)
|
|
for i in 0 ..< m2:
|
|
pred[i] = infer(e, bd[i].x.toOpenArray(0, FD - 1))[0]
|
|
yy[i] = bd[i].y
|
|
train(e, bd[i].x.toOpenArray(0, FD - 1), [bd[i].y])
|
|
q2 += (ppred[i] - yy[i]) * (ppred[i] - yy[i]); inc qn
|
|
if i >= WIN:
|
|
q2 -= (ppred[i - WIN] - yy[i - WIN]) * (ppred[i - WIN] - yy[i - WIN]); dec qn
|
|
pcurve[i] = sqrt(q2 / float64(max(qn, 1)))
|
|
let cur = curve(pred, yy, WIN)
|
|
# B-only ceiling, scored on the SAME M shots the online model saw
|
|
let solo = newElm(1.0)
|
|
for s in bd:
|
|
train(solo, s.x.toOpenArray(0, FD - 1), [s.y])
|
|
refit(solo)
|
|
let sp = predictAll(solo, bd)
|
|
var sy = newSeq[float64](bd.len)
|
|
for i, s in bd: sy[i] = s.y
|
|
let refRmse = rmseOf(sp, sy, 0, m2)
|
|
var dipMax = 0.0; var dipAt = 0
|
|
for i in WIN ..< m2:
|
|
if cur[i] - pcurve[i] > dipMax: dipMax = cur[i] - pcurve[i]; dipAt = i
|
|
let rec = firstBelow(cur, refRmse, 0)
|
|
let recS = if rec < 0: "never" else: $rec
|
|
echo fmt" {decay:<6.3f} {100*dipMax/pcurve[0]:+6.1f}% {dipAt:<9} {recS:<12} {rmseOf(pred,yy,max(0,m2-WIN),m2):.4f} {refRmse:.4f} pooled {pcurve[m2-1]:.4f}"
|
|
|
|
# ─────────────────────────────────────────────────────── EXPERIMENT C ──────
|
|
echo "\n================ EXPERIMENT C: refit cost / memory ================"
|
|
let e2 = newElm(0.99)
|
|
var big = corps[0]
|
|
for c in corps:
|
|
if c.d.len > big.d.len: big = c
|
|
echo " corpus=" & big.name & " n=" & $big.d.len
|
|
for target in [100, 500, 1000, 2000, 5000, big.d.len]:
|
|
let tgt = min(target, big.d.len)
|
|
while diagnostics(e2).nSamples < tgt:
|
|
let i = diagnostics(e2).nSamples
|
|
train(e2, big.d[i].x.toOpenArray(0, FD - 1), [big.d[i].y])
|
|
let t0 = cpuTime()
|
|
refit(e2)
|
|
let dt = (cpuTime() - t0) * 1000
|
|
let n = diagnostics(e2).nSamples
|
|
echo " " & align($n, 10) & " " & align(formatFloat(dt, ffDecimal, 1), 6) & " " &
|
|
formatFloat(float64(n)*24*8/1e6, ffDecimal, 2) & " MB"
|
|
echo fmt" final n={diagnostics(e2).nSamples} samples, sampleMem={(float64(diagnostics(e2).nSamples)*24*8)/1e6:.2f} MB (growth: UNBOUNDED, one sample per shot)"
|