Files
SirRoboGarage/tools/elm_bench/audit_independent.py
SirStone 6d0dd987ca tools/elm_bench: aim-error ELM benchmark suite + findings
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.
2026-10-05 22:42:39 +02:00

106 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Independent audit reproduction. Written from scratch, does NOT import any
of the bench code. Uses only stdlib (pure-python ridge, closed form)."""
import json, math, glob, os, sys, collections
HERE = os.path.dirname(os.path.abspath(__file__))
def load(path):
rows = []
with open(path) as fh:
for line in fh:
if line.strip():
rows.append(json.loads(line))
return rows
def folds_by_group(rows, k=5):
"""round-robin over distinct groups, ordered."""
groups = sorted({r["group"] for r in rows})
gidx = {g: i % k for i, g in enumerate(groups)}
return [gidx[r["group"]] for r in rows]
def const_cv(rows, fa, ys):
out = []
for f in range(5):
tr = [ys[i] for i in range(len(ys)) if fa[i] != f]
te = [i for i in range(len(ys)) if fa[i] == f]
m = sum(tr) / len(tr)
out += [ys[i] - m for i in te]
return math.sqrt(sum(d*d for d in out) / len(out))
def ridge_cv(rows, fa, ys, xfn, lam=1e-6):
"""Standardise features on train folds, closed-form ridge."""
out = []
for f in range(5):
tr = [i for i in range(len(ys)) if fa[i] != f]
te = [i for i in range(len(ys)) if fa[i] == f]
X = [xfn(rows[i]) for i in tr]
p = len(X[0])
mu = [sum(x[j] for x in X)/len(X) for j in range(p)]
sd = [math.sqrt(sum((x[j]-mu[j])**2 for x in X)/len(X)) or 1.0 for j in range(p)]
Z = [[(x[j]-mu[j])/sd[j] for j in range(p)] + [1.0] for x in X]
yv = [ys[i] for i in tr]
my = sum(yv)/len(yv)
yc = [v-my for v in yv]
A = [[sum(Z[k][a]*Z[k][b] for k in range(len(Z))) + (lam*len(Z) if a == b else 0.0)
for b in range(p+1)] for a in range(p+1)]
for a in range(p+1): A[a][a] += 1e-8
b = [sum(Z[k][a]*yc[k] for k in range(len(Z))) for a in range(p+1)]
# gaussian elimination
for c in range(p+1):
piv = max(range(c, p+1), key=lambda r: abs(A[r][c]))
A[c], A[piv] = A[piv], A[c]; b[c], b[piv] = b[piv], b[c]
d = A[c][c]
for j in range(c, p+1): A[c][j] /= d
b[c] /= d
for r in range(p+1):
if r == c: continue
fct = A[r][c]
if fct:
for j in range(c, p+1): A[r][j] -= fct*A[c][j]
b[r] -= fct*b[c]
for i in te:
z = [(xfn(rows[i])[j]-mu[j])/sd[j] for j in range(p)] + [1.0]
out.append(ys[i] - (my + sum(z[a]*b[a] for a in range(p+1))))
return math.sqrt(sum(d*d for d in out)/len(out))
def in_sample_fit(rows, ys, key):
xs = [r[key] for r in rows]
mx = sum(xs)/len(xs); my = sum(ys)/len(ys)
cov = sum((xs[i]-mx)*(ys[i]-my) for i in range(len(ys)))
var = sum((x-mx)**2 for x in xs)
slope = cov/var; inter = my - slope*mx
mxr = sum((xs[i]-mx)*(ys[i]-my) for i in range(len(ys)))/math.sqrt(var*sum((y-my)**2 for y in ys))
return slope, inter, mxr
def main():
targets = sys.argv[1:] or [os.path.join(HERE, "gen", "DrussGT.ndjson")]
for path in targets:
rows = load(path)
ys = [r["label"] for r in rows]
fa = folds_by_group(rows)
print(f"\n== {os.path.basename(path)} n={len(rows)} groups={len(set(fa and [r['group'] for r in rows]))}")
c = const_cv(rows, fa, ys)
print(f" constant baseline (5-fold by round-group, pooled) = {c:.4f}")
slope, inter, corr = in_sample_fit(rows, ys, "beliefPredErr")
print(f" in-sample label ~ {slope:.4f} * beliefPredErr + {inter:.4f} corr={corr:.4f}")
single = ridge_cv(rows, fa, ys, lambda r: [r["beliefPredErr"]])
print(f" held-out RMSE, beliefPredErr ALONE (ridge) = {single:.4f} ({(single-c)/c*100:+.1f}%)")
prev = [ridge_cv(rows, fa, ys, lambda r: [r[k]])
for k in ("beliefScanAge", "beliefTgtLatVel", "beliefClosing", "beliefTof")]
for k, v in zip(("scanAge", "tgtLatVel", "closing", "tof"), prev):
print(f" held-out RMSE, {k:<26} = {v:.4f} ({(v-c)/c*100:+.1f}%)")
allf = ["beliefDist", "beliefSinRelBearing", "beliefCosRelBearing",
"beliefTgtSpeed", "bulletSpeed", "beliefScanAge", "beliefEverScanned",
"beliefScanGap", "beliefPredErr", "beliefLosRate", "beliefTof",
"beliefClosing", "gunHeat", "power", "ownSpeed", "beliefDisp"]
a = ridge_cv(rows, fa, ys, lambda r: [r[k] for k in allf])
print(f" held-out RMSE, 16 observable features (ridge) = {a:.4f} ({(a-c)/c*100:+.1f}%)")
# label reproducibility from ground truth?
print(f" label corr with oracleRelBearing (not a feature) = "
f"{in_sample_fit(rows, ys, 'oracleRelBearing')[2]:+.4f}")
print(f" label corr with beliefPredErr = {corr:+.4f}")
print(f" beliefPredErr == sin(beliefRelBearing)? dup-index check: "
f"sin/cosRel already present -> index 2 is sin(beliefRelBearing)")
main()