ChimeraBot_garage: M6 — residual head, predictor fusion, fallback influence, G7 head-to-head

This commit is contained in:
2026-10-07 02:45:41 +02:00
parent 1b10603f28
commit 2d250487d4
15 changed files with 966 additions and 22 deletions
+33 -19
View File
@@ -94,21 +94,18 @@ proc guardSkip*() =
echo "Skipping bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing."
quit(0)
proc runBattleHard*(serverUrl: string, botDirs: seq[string], rounds: int,
timeoutMs = 90000, maxSpeed = true): bool =
## Hard-timeout battle: `test_framework.runBattleRunner` can block forever when
## the Java runner stops emitting output while still alive, so benches use this
## wrapper (shell redirect to a log, poll, then kill). Battles normally take
## 1-3 s, so 90 s is generous and bounds a hang.
proc runBattleHardLog*(serverUrl: string, botDirs: seq[string], rounds: int,
timeoutMs = 90000, maxSpeed = true,
logName = "chimera_runner"): tuple[ok: bool, logPath: string] =
## Hard-timeout battle that KEEPS the runner log, for benches that need the
## per-round results (G7). `battle_runner`'s TestBattleRunner emits JSON lines.
let jar = getEnv("TR_BATTLE_RUNNER", RunnerJar)
let classDir = getEnv("TR_BATTLE_RUNNER_DIR", RunnerDir)
let logf = getTempDir() / "chimera_runner.log"
let logf = getTempDir() / (logName & ".log")
var args = "--server-url " & quoteShell(serverUrl) &
" --rounds " & $rounds &
" --bot-dirs " & quoteShell(botDirs.join(","))
if maxSpeed: args.add " --max-speed"
# coreutils `timeout -s KILL` is the hard guarantee: if the Java runner blocks
# and ignores SIGTERM (shutdown hooks), the shell still kills it at the limit.
let hardSec = int(timeoutMs div 1000) + 5
let cmd = "timeout -s KILL " & $hardSec & " java -cp " &
quoteShell(classDir & ":" & jar) &
@@ -126,10 +123,18 @@ proc runBattleHard*(serverUrl: string, botDirs: seq[string], rounds: int,
sleep(200)
if p.peekExitCode() == -1: p.kill()
p.close()
return false
result = p.peekExitCode() == 0
return (false, logf)
result = (p.peekExitCode() == 0, logf)
p.close()
proc runBattleHard*(serverUrl: string, botDirs: seq[string], rounds: int,
timeoutMs = 90000, maxSpeed = true): bool =
## Hard-timeout battle: `test_framework.runBattleRunner` can block forever when
## the Java runner stops emitting output while still alive, so benches use this
## wrapper (shell redirect to a log, poll, then kill). Battles normally take
## 1-3 s, so 90 s is generous and bounds a hang.
runBattleHardLog(serverUrl, botDirs, rounds, timeoutMs, maxSpeed).ok
proc deps*(): seq[string] =
for p in ["robocode_tankroyale_botapi", "jsony"]:
let (outp, _) = execCmdEx("nimble path " & p)
@@ -139,10 +144,14 @@ proc deps*(): seq[string] =
if line.len == 0: quit("Cannot resolve dependency: " & p)
result.add "--path:" & line
proc stageBot*(tag: string, defines: seq[string] = @[]): string =
## Compile ChimeraBot into a throwaway /tmp dir with its json + boot script.
let botDir = getTempDir() / ("chimera_stage_" & tag) / "ChimeraBot"
removeDir(getTempDir() / ("chimera_stage_" & tag))
proc stageBot*(tag: string, defines: seq[string] = @[], name = "ChimeraBot"): string =
## Compile ChimeraBot into a throwaway /tmp dir with a json + boot script. The
## optional `name` gives a distinct identity so two staged arms can fight in
## one battle (G7 head-to-head); the default "ChimeraBot" keeps the older
## benches byte-identical.
let root = getTempDir() / ("chimera_stage_" & tag)
let botDir = root / name
removeDir(root)
createDir(botDir)
let bin = botDir / "ChimeraBot"
var cmd = "nim c -d:release --hints:off "
@@ -152,10 +161,15 @@ proc stageBot*(tag: string, defines: seq[string] = @[]): string =
let (outp, code) = execCmdEx(cmd, options = {poEvalCommand})
if code != 0 or not fileExists(bin):
quit("ChimeraBot (" & tag & ") compile failed:\n" & outp)
copyFile(GarageSrc / "ChimeraBot.json", botDir / "ChimeraBot.json")
writeFile(botDir / "ChimeraBot.sh",
"#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec \"./ChimeraBot\"\n")
let sh = botDir / "ChimeraBot.sh"
# Identity JSON: rename only the `name` field, then launch with it explicitly
# (the binary's compile-time default is the garage ChimeraBot.json).
var js = readFile(GarageSrc / "ChimeraBot.json")
js = js.replace("\"ChimeraBot\"", "\"" & name & "\"")
writeFile(botDir / (name & ".json"), js)
writeFile(botDir / (name & ".sh"),
"#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec \"./ChimeraBot\" \"" &
name & ".json\"\n")
let sh = botDir / (name & ".sh")
setFilePermissions(sh, getFilePermissions(sh) + {fpUserExec, fpGroupExec, fpOthersExec})
botDir
+203
View File
@@ -0,0 +1,203 @@
## G7 head-to-head + no-regression floor (CHIMERA M6). LIVE, Java required.
##
## Three binaries built from the SAME tree:
## * inert — `-d:chimeraInert` == the M1 exact copy (all CHIMERA off)
## * full — default (probes + fusion + influence)
## * noprobe — `-d:chimeraNoProbes` (fusion + influence, no probes)
##
## Head-to-head: full vs inert mirror 1v1, `H2HN` matches x `H2HRounds`.
## Bar: head-to-head win-rate >= 50% (exact, reported).
##
## Suite no-regression floor: each arm vs the 8 primary sample bots,
## `Rounds` rounds each. Bar: full >= inert on EVERY opponent (win rate), with
## survival and score margin reported; the full-minus-probes arm isolates the
## probe cost.
##
## A full < inert anywhere is reported plainly as a falsification, never hidden.
## Run: `nim c -r --hints:off -d:release tests/bench_g7.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times]
import bench_common
const
Rounds = 5
H2HN = 10 # head-to-head mirror matches
H2HRounds = 5 # rounds per head-to-head match
type
Outcome = object
rounds, wins: int
ourScore, oppScore: float64
ourSurv, oppSurv: int
Arm = object
tag, name: string
defines: seq[string]
const Arms = [
Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]),
Arm(tag: "full", name: "ChimeraFull", defines: @[]),
Arm(tag: "noprobe", name: "ChimeraNoProbe", defines: @["-d:chimeraNoProbes"]),
]
proc parseOutcome(log, ourName: string): Outcome =
## Aggregate a battle's JSONL runner output. A failed battle (no round_ended)
## yields rounds == 0.
for ln in log.splitLines():
if ln.len == 0 or ln.find("\"event\":\"round_ended\"") < 0: continue
inc result.rounds
let ri = ln.find("\"results\":[")
if ri < 0: continue
let oi = ln.find('[', ri)
let ci = ln.find(']', ri)
if oi < 0 or ci < 0 or ci <= oi: continue
let seg = ln[oi + 1 ..< ci]
var j = 0
var ourScoreV = -1.0
var theirScoreV = -1.0
var ourSurvF, theirSurvF = false
while j < seg.len:
let s = seg.find('{', j)
if s < 0: break
let e = seg.find('}', s)
if e < 0: break
let obj = seg[s + 1 ..< e]
let (found, name) = extract(obj, "name")
let (sf, score) = extract(obj, "score")
let (vf, surv) = extract(obj, "survived")
if found and sf and vf:
if name == ourName:
ourScoreV = score.parseFloat()
ourSurvF = surv == "true"
else:
theirScoreV = score.parseFloat()
theirSurvF = surv == "true"
j = e + 1
if ourScoreV >= 0.0 and theirScoreV >= 0.0:
result.ourScore += ourScoreV
result.oppScore += theirScoreV
if ourScoreV > theirScoreV: inc result.wins
if ourSurvF: inc result.ourSurv
if theirSurvF: inc result.oppSurv
proc runBattle(url: string, botDirs: seq[string], rounds: int,
ourName, tag: string): Outcome =
## Launch one battle, route telemetry to a throwaway dir, parse and return.
putEnv("CHIMERA_TELEMETRY_DIR", getTempDir() / ("chimera_g7_tel_" & tag))
let (ok, logPath) = runBattleHardLog(url, botDirs, rounds,
logName = "chimera_g7_" & tag)
if not ok: return Outcome()
parseOutcome(readFile(logPath), ourName)
proc winRate(o: Outcome): float64 =
if o.rounds == 0: 0.0 else: 100.0 * float(o.wins) / float(o.rounds)
proc margin(o: Outcome): float64 = o.ourScore - o.oppScore
proc main() =
guardSkip()
echo "[G7] staging 3 arms: " & Arms.mapIt(it.tag &
"=" & (if it.defines.len == 0: "(default)" else: it.defines.join(","))).join(" ")
var bots = initTable[string, string]()
for a in Arms:
bots[a.tag] = stageBot("g7_" & a.tag, a.defines, a.name)
var lines: seq[string]
lines.add("# G7 head-to-head + no-regression floor (M6)\n")
lines.add("Three arms from the SAME tree: **inert** (`-d:chimeraInert`, == M1 " &
"exact copy), **full** (default: probes + fusion + influence), " &
"**noprobe** (`-d:chimeraNoProbes`: fusion + influence). Head-to-head: " &
"full vs inert mirror 1v1, " & $H2HN & " matches x " & $H2HRounds &
" rounds. Suite: " & $Rounds & " rounds per arm per opponent vs the 8 " &
"primary sample bots. Generated by `tests/bench_g7.nim`.\n")
# ── head-to-head ──────────────────────────────────────────────────────────
restartServer()
var url = serverUrl()
var h2h: Outcome
echo "\n[G7] head-to-head full vs inert, ", H2HN, " matches x ", H2HRounds, " rounds"
for m in 1 .. H2HN:
var o: Outcome
for attempt in 1 .. MaxAttempts:
removeDir(getTempDir() / "chimera_g7_h2h_tel"); sleep(300)
o = runBattle(url, @[bots["full"], bots["inert"]], H2HRounds,
"ChimeraFull", "h2h")
if o.rounds > 0: break
echo " h2h match ", m, " attempt ", attempt, ": retry"
killStaleBots(); restartServer(); url = serverUrl()
h2h.wins += o.wins; h2h.rounds += o.rounds
h2h.ourScore += o.ourScore; h2h.oppScore += o.oppScore
h2h.ourSurv += o.ourSurv; h2h.oppSurv += o.oppSurv
echo " match ", m, " -> ", o.rounds, " rounds, full wins ", o.wins
let h2hWin = winRate(h2h)
echo "\n[G7] head-to-head: full win ", formatFloat(h2hWin, ffDecimal, 1),
"% over ", h2h.rounds, " rounds, margin ", formatFloat(margin(h2h), ffDecimal, 1),
", survival full ", h2h.ourSurv, " vs inert ", h2h.oppSurv
echo " G7 head-to-head bar (>=50%): ", (if h2hWin >= 50.0: "PASS" else: "FAIL")
lines.add "## Head-to-head: full vs inert\n"
lines.add "| metric | value |"
lines.add "|---|---:|"
lines.add "| matches | " & $H2HN & " x " & $H2HRounds & " rounds |"
lines.add "| full win-rate | " & formatFloat(h2hWin, ffDecimal, 1) & "% |"
lines.add "| full survival | " & $h2h.ourSurv & " / inert " & $h2h.oppSurv & " |"
lines.add "| score margin (full-inert) | " & formatFloat(margin(h2h), ffDecimal, 1) & " |"
lines.add "| **bar (>=50%)** | " & (if h2hWin >= 50.0: "**PASS**" else: "**FAIL**") & " |"
# ── suite no-regression ───────────────────────────────────────────────────
let opps = sorted(toSeq(Expected.keys))
var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out
for arm in Arms:
var t = initTable[string, Outcome]()
for opp in opps:
restartServer()
putEnv("CHIMERA_OPPONENT", opp)
let o = runBattle(serverUrl(), @[bots[arm.tag], SampleRoot / opp], Rounds,
arm.name, arm.tag & "_" & opp)
t[opp] = o
echo " [", arm.tag, "] vs ", alignLeft(opp, 10), " rounds=", o.rounds,
" winRate=", formatFloat(winRate(o), ffDecimal, 0), "%",
" margin=", formatFloat(margin(o), ffDecimal, 1)
suite[arm.tag] = t
echo "\n=== G7 suite no-regression (", Rounds, " rounds/arm/opponent) ==="
echo "Opponent fullW% fullM fullS inertW% inertM inertS noprW% noprM"
lines.add "\n## Suite no-regression floor (" & $Rounds & " rounds per arm)\n"
lines.add "| opponent | full W% | full margin | full surv | inert W% | inert margin | inert surv | noProbe W% | noProbe margin |"
lines.add "|---|---:|---:|---:|---:|---:|---:|---:|---:|"
var allOk = true
var failedOpps: seq[string]
for opp in opps:
let f = suite["full"].getOrDefault(opp)
let i = suite["inert"].getOrDefault(opp)
let n = suite["noprobe"].getOrDefault(opp)
let okRow = (f.rounds > 0 and i.rounds > 0) and (f.wins >= i.wins)
if not okRow: allOk = false; failedOpps.add opp
echo " ", alignLeft(opp, 10),
align(formatFloat(winRate(f), ffDecimal, 0), 7),
align(formatFloat(margin(f), ffDecimal, 1), 6),
align($f.ourSurv, 6),
align(formatFloat(winRate(i), ffDecimal, 0), 8),
align(formatFloat(margin(i), ffDecimal, 1), 6),
align($i.ourSurv, 6),
align(formatFloat(winRate(n), ffDecimal, 0), 7),
" ", formatFloat(margin(n), ffDecimal, 1)
lines.add "| " & opp & " | " & formatFloat(winRate(f), ffDecimal, 1) & " | " &
formatFloat(margin(f), ffDecimal, 1) & " | " & $f.ourSurv & " | " &
formatFloat(winRate(i), ffDecimal, 1) & " | " &
formatFloat(margin(i), ffDecimal, 1) & " | " & $i.ourSurv & " | " &
formatFloat(winRate(n), ffDecimal, 1) & " | " &
formatFloat(margin(n), ffDecimal, 1) & " |"
lines.add "\n**No-regression (full >= inert on every opponent): " &
(if allOk: "PASS" else: "**FAIL** on " & failedOpps.join(", ")) & "**. "
lines.add "Head-to-head win rate " & formatFloat(h2hWin, ffDecimal, 1) &
"% (bar >=50%: " & (if h2hWin >= 50.0: "PASS" else: "FAIL") & ")."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m6_g7.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
when isMainModule:
main()
+94
View File
@@ -0,0 +1,94 @@
## Tier A unit tests for CHIMERA predictor fusion (chimera/fusion.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/[math, sequtils]
import chimera/dsl
import chimera/hedge
import chimera/twinsim
import chimera/residual
import chimera/fusion
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc sum(f: Fusion): float64 =
for w in f.weights(): result += w
let kernels = allKernels()
proc demoOrigin(): ReplayTick =
let h = initHedge(kernelNames(kernels))
result = ReplayTick(tick: 10, ex: 200.0, ey: 300.0, edir: 0.0, espeed: 4.0,
eenergy: 100.0, ox: 600.0, oy: 300.0, odir: 180.0,
ospeed: 3.0, lastTurn: 0.0, lastSpeed: 4.0)
result.weights = h.weights
for k in kernels: result.mems.add defaultMemory(k.defaultParams)
block:
echo "test 1: weights normalize"
var f = initFusion()
check("uniform start sums to 1", abs(sum(f) - 1.0) < 1e-12)
for i in 0 ..< 20:
f.update(PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
[PredIntent(turn: 9.0, speed: -8.0, fire: 1.0),
PredIntent(turn: 5.0, speed: 0.0, fire: 0.5),
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0)])
check("stays normalized after updates", abs(sum(f) - 1.0) < 1e-12)
block:
echo "test 2: persistence sanity (the consistently-right predictor wins)"
var f = initFusion()
for i in 0 ..< 300:
f.update(PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
[PredIntent(turn: 9.0, speed: -8.0, fire: 1.0), # mixture: bad
PredIntent(turn: 5.0, speed: 0.0, fire: 0.5), # residual: bad
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0)]) # persistence: good
check("persistence weight dominates", f.weights()[PersistenceIdx] > 0.9,
$f.weights())
check("confidence is in range", f.confidence() >= 0.0 and f.confidence() <= 1.0,
$f.confidence())
block:
echo "test 3: fused rollout shape + fire/confidence smoke"
let origin = demoOrigin()
var f = initFusion()
for i in 0 ..< 50:
f.update(PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
[PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0),
PredIntent(turn: 0.0, speed: 4.0, fire: 0.0)])
var head = initResidualHead()
let rp = head.predict(features(ResidualInput(lastSpeed: 4.0, scanAge: 1.0,
dist: 400.0)))
let fp = f.fusedPrediction(kernels, origin, rp, 5)
check("horizon points = 5", fp.points.len == 5 and fp.pFire.len == 5,
$fp.points.len)
check("fireWithin in [0,1]", fp.fireWithin >= 0.0 and fp.fireWithin <= 1.0,
$fp.fireWithin)
check("confidence in [0,1]", fp.confidence >= 0.0 and fp.confidence <= 1.0)
check("all points finite",
fp.points.allIt(it.x == it.x and abs(it.x) < 1e9 and
it.y == it.y and abs(it.y) < 1e9))
block:
echo "test 4: determinism (same state => same fused prediction)"
let origin = demoOrigin()
var f1 = initFusion()
var f2 = initFusion()
for i in 0 ..< 30:
let r = PredIntent(turn: 1.0, speed: 2.0, fire: 0.0)
f1.update(r, [r, r, r])
f2.update(r, [r, r, r])
let a = f1.fusedPrediction(kernels, origin, ResidualPrediction(), 5)
let b = f2.fusedPrediction(kernels, origin, ResidualPrediction(), 5)
var same = a.points.len == b.points.len
for i in 0 ..< a.points.len:
if a.points[i].x != b.points[i].x or a.points[i].y != b.points[i].y:
same = false
check("bit-identical fused trajectories", same)
echo ""
if failed == 0: echo "all fusion tests passed"
else: echo failed, " fusion test(s) FAILED"; quit(1)
@@ -0,0 +1,79 @@
## Tier A unit tests for the CHIMERA influence / fallback layer
## (chimera/influence.nim). Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/fusion
import chimera/influence
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc fusedPath(points: seq[tuple[x, y: float64]], pFire = 0.4): FusedPrediction =
result.horizon = points.len
result.points = points
for _ in points: result.pFire.add pFire
result.fireWithin = 0.8
result.confidence = 0.7
block:
echo "test 1: influence ramp"
check("no samples => no influence", influenceScalar(0.0, 0) == 0.0)
check("low loss => full influence", influenceScalar(0.1, 5) == 1.0)
check("high loss => zero influence", influenceScalar(5.0, 5) == 0.0)
let mid = influenceScalar((GoodLoss + BadLoss) / 2.0, 5)
check("mid loss => mid influence", abs(mid - 0.5) < 1e-9, $mid)
check("monotone decreasing",
influenceScalar(0.6, 1) >= influenceScalar(0.7, 1) and
influenceScalar(0.7, 1) >= influenceScalar(0.8, 1))
block:
echo "test 2: reflex gate — never touch an active bullet dodge"
let fp = fusedPath(@[(60.0, 100.0), (60.0, 130.0), (60.0, 160.0)])
let adv = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, reflexBusy = true)
check("not applied while dodging", not adv.applied)
check("command untouched", adv.speed == 6.0 and adv.turnRate == 0.0)
block:
echo "test 3: zero influence => no steering"
let fp = fusedPath(@[(60.0, 100.0), (60.0, 130.0), (60.0, 160.0)])
let adv = overlay(0.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, reflexBusy = false)
check("not applied", not adv.applied)
check("command untouched", adv.speed == 6.0 and adv.turnRate == 0.0)
block:
echo "test 4: steering toward safety + safe margins"
# Collision course: our straight path (heading north through x=100) runs
# straight into the fused predicted enemy (a stationary point at y=130), so
# any turn buys clearance before we arrive.
let fp = fusedPath(@[(100.0, 130.0), (100.0, 130.0), (100.0, 130.0),
(100.0, 130.0), (100.0, 130.0)])
let adv = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, reflexBusy = false)
check("applied when it improves clearance", adv.applied, $adv.gain)
check("turns away from the predicted path", adv.turnRate < 0.0, $adv.turnRate)
check("turn within cap", abs(adv.turnRate - 0.0) <= MaxTurnBias + 1e-9,
$adv.turnRate)
check("speed within cap", abs(adv.speed - 6.0) <= MaxSpeedDelta + 1e-9,
$adv.speed)
block:
echo "test 5: no nudge when the baseline is already safe"
let far = fusedPath(@[(100.0, 10000.0), (100.0, 10030.0), (100.0, 10060.0)])
let adv = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, far,
reflexBusy = false)
check("not applied (gain below margin)", not adv.applied, $adv.gain)
block:
echo "test 6: determinism"
let fp = fusedPath(@[(100.0, 130.0), (100.0, 130.0), (100.0, 130.0),
(100.0, 130.0), (100.0, 130.0)])
let a = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, false)
let b = overlay(1.0, 6.0, 0.0, 100.0, 100.0, 90.0, 6.0, fp, false)
check("bit-identical advisory",
a.speed == b.speed and a.turnRate == b.turnRate and
a.applied == b.applied and a.gain == b.gain)
echo ""
if failed == 0: echo "all influence tests passed"
else: echo failed, " influence test(s) FAILED"; quit(1)
+76
View File
@@ -0,0 +1,76 @@
## Tier A unit tests for the CHIMERA residual head (chimera/residual.nim).
## Run: from ChimeraBot_garage/src, `nimble test`.
import std/math
import chimera/residual
var failed = 0
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
proc finite(x: float64): bool = x == x and abs(x) < 1e12
block:
echo "test 1: online determinism"
var a = initResidualHead()
var b = initResidualHead()
let f = features(ResidualInput(lastTurn: 3.0, lastSpeed: -2.0, scanAge: 1.0,
dist: 250.0, ownTurn: 4.0, ownSpeed: 5.0))
for i in 0 ..< 50:
let t = ResidualTarget(turn: 0.1 * float(i mod 5), speed: -0.05,
fire: 0.001 * float(i))
a.observe(f, t)
b.observe(f, t)
let pa = a.predict(f)
let pb = b.predict(f)
check("identical heads agree bit-for-bit",
pa.turn == pb.turn and pa.speed == pb.speed and pa.fire == pb.fire)
check("samples counted", a.samples == 50, $a.samples)
block:
echo "test 2: monotone improvement on a synthetic residual stream"
# Deterministic stream: target.turn = a linear function of the features.
var head = initResidualHead()
var state = 0x12345678'u64
proc u01(): float64 =
state = state * 6364136223846793005'u64 + 1442695040888963407'u64
float64(state shr 11) / 9007199254740992.0
var firstSum, lastSum = 0.0
for i in 0 ..< 2000:
let inp = ResidualInput(lastTurn: (u01() * 2.0 - 1.0) * 10.0,
lastSpeed: (u01() * 2.0 - 1.0) * 8.0,
scanAge: 1.0 + u01() * 3.0,
dist: u01() * 800.0,
ownTurn: (u01() * 2.0 - 1.0) * 10.0,
ownSpeed: (u01() * 2.0 - 1.0) * 8.0)
let ff = features(inp)
# true residual: 0.2*f0 + 0.1*f1 - 0.3*f4
let tgt = ResidualTarget(turn: 0.2 * ff[0] + 0.1 * ff[1] - 0.3 * ff[4],
speed: 0.0, fire: 0.0)
let l = head.meanSquaredLoss(ff, tgt)
if i < 100: firstSum += l
if i >= 1900: lastSum += l
head.observe(ff, tgt)
check("early loss > late loss (learns)", lastSum < firstSum,
$lastSum & " vs " & $firstSum)
block:
echo "test 3: no crash / finite on degenerate input"
var head = initResidualHead()
let zeros: array[NFeatures, float64] = default(array[NFeatures, float64])
head.observe(zeros, ResidualTarget())
let big = features(ResidualInput(dist: 1e9, lastTurn: 1e9, ownSpeed: -1e9))
head.observe(big, ResidualTarget(turn: 1e9, speed: -1e9, fire: 1.0))
let p = head.predict(big)
check("prediction is finite", finite(p.turn) and finite(p.speed) and finite(p.fire))
check("fire prediction clamped to [-1,1]", p.fire >= -1.0 and p.fire <= 1.0,
$p.fire)
var empty = initResidualHead()
empty.reset()
check("reset zeroes samples", empty.samples == 0 and
empty.predict(zeros).turn == 0.0)
echo ""
if failed == 0: echo "all residual tests passed"
else: echo failed, " residual test(s) FAILED"; quit(1)