ChimeraBot_garage: M5.5 — unified metrics, cross-round posterior carry, probe set v2, G5' v2

This commit is contained in:
2026-10-07 02:27:11 +02:00
parent f9f3cd7576
commit 6dd0b1c3cb
12 changed files with 815 additions and 452 deletions
+110 -205
View File
@@ -1,230 +1,135 @@
## G4 live-identification benchmark harness (CHIMERA M3).
## G4 live-identification benchmark — unified M5.5 metric.
##
## Runs headless 1v1 battles (server on a random port, tps=-1, `--enable-initial-
## position`) of the ChimeraBot observation sidecar against the 8 sample-bot
## ground-truth targets from `docs/chimera-spec.md` §12, parses the /tmp
## telemetry, and reports ticks-to-posterior>0.8 per expected kernel plus
## censoring rate and 5-tick ADE/FDE.
## Runs `Repeat` full `Rounds`-round battles per ground-truth opponent against
## the ChimeraBot observation sidecar (server on a random port, tps=-1), and
## reports the UNIFIED idTicks metric per opponent: median / p90 / id-fraction
## over ALL rounds in the protocol (every round of every run).
##
## Findings (per the DSL v0 defaults) are reported, not tuned away — a G4 miss is
## a design-level result to be analyzed, exactly as the milestone intends.
## Metric (spec §12, M5.5): per round, the round-relative tick at which
## `max_kernel posterior > 0.8`. argmax correctness is a diagnostic only.
## Pass condition: median <= 300 AND id-fraction >= 80% over >= 3 full 8x5 runs.
##
## Requires Java + the TR server/runner JARs + the unpacked Nim sample bots.
## Throwaway outputs (staged bot binary, telemetry) live only under /tmp.
## Run: `nim c -r --hints:off -d:release tests/bench_g4.nim` from ChimeraBot_garage.
## Findings are reported, never tuned away. Requires Java + JARs + sample bots.
## Run: `nim c -r --hints:off -d:release tests/bench_g4.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm]
import bench_common
import test_framework/server_manager
import test_framework/runner_process
const
SampleRoot = getEnv(
"TR_SAMPLE_BOTS",
"/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7")
GarageSrc = currentSourcePath().parentDir.parentDir / "src"
StageDir = getTempDir() / "chimera_g4_stage"
Repeat = 3
Rounds = 5
Telemetry = getTempDir() / "chimera_twin"
Archive = getTempDir() / "chimera_g4_run"
Rounds = 5 # enough ticks to observe 300 identification-capable ticks
Threshold = 0.8
TargetTicks = 300
MaxAttempts = 4
## expected kernel per ground-truth target (§12 verified mapping).
##
## v0.2 refinement from live measurement: Corners and RamFire are modelled by
## STATIC. The §12 source behaviour (Corners parks and sweeps; RamFire charges)
## exists, but in the observable body channels (turn / target-speed / heat-gated
## fire) the *realized* policy is stationary-posture dominated: Corners' approach
## run falls before the radar lock that starts the record, and RamFire spends
## 50-72% of observed ticks wall/collision-pinned spinning in place. The
## static-posture STATIC kernel reaches posterior >= 0.8 on both within 72 ticks
## (v0.2 STATIC_CORNER / RAMMER variants lose to it: see the M3.5 report). This
## is a G2-identifiability finding, not a source claim about those bots.
const Expected = {
"Crazy": "ZIGZAG",
"SpinBot": "ORBIT_BALLIST",
"RamFire": "STATIC",
"Corners": "STATIC",
"Walls": "WALLCRAWL",
"TrackFire": "STATIC",
"Fire": "STATIC",
"VelociBot": "STOP_AND_GO",
}.toTable
proc guardSkip() =
let serverOk = fileExists(getEnv("TR_SERVER_JAR",
"/home/davide/Downloads/robocode-tankroyale/robocode-tankroyale-server.jar"))
let runnerOk = fileExists(getEnv("TR_BATTLE_RUNNER",
"/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"))
if not serverOk or not runnerOk or not dirExists(SampleRoot):
echo "Skipping G4 bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing."
quit(0)
proc deps(): seq[string] =
for p in ["robocode_tankroyale_botapi", "jsony"]:
let (outp, _) = execCmdEx("nimble path " & p)
var line = ""
for l in outp.splitLines():
if l.len > 0: line = l; break
if line.len == 0:
quit("Cannot resolve dependency: " & p)
result.add "--path:" & line
proc stageBot(): string =
## Compile ChimeraBot into a throwaway /tmp dir with its json + boot script.
let botDir = StageDir / "ChimeraBot"
removeDir(StageDir)
createDir(botDir)
let bin = botDir / "ChimeraBot"
let deps = deps()
let (outp, code) = execCmdEx("nim c -d:release --hints:off " &
deps.join(" ") & " --out:\"" & bin & "\" " &
quoteShell(GarageSrc / "ChimeraBot.nim"), options = {poEvalCommand})
if code != 0 or not fileExists(bin):
quit("ChimeraBot 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"
setFilePermissions(sh, getFilePermissions(sh) + {fpUserExec, fpGroupExec, fpOthersExec})
botDir
proc extract(line: string, key: string): tuple[found: bool, value: string] =
let needle = "\"" & key & "\":"
let i = line.find(needle)
if i < 0: return (false, "")
let rest = line[i + needle.len .. ^1]
var j = 0
while j < rest.len and rest[j] in {' ', '\t'}: inc j
if j < rest.len and rest[j] == '"':
let start = j + 1
var k = start
while k < rest.len and rest[k] != '"': inc k
return (true, rest[start ..< k])
# number
var k = j
while k < rest.len and (rest[k].isAlphaNumeric or rest[k] in {'.', '-', 'e', 'E'}):
inc k
return (true, rest[j ..< k])
type RoundStat = object
idTick: int # first tick posterior(expected) >= Threshold, else -1
sumTicks: int
sumCensorRate: float64
finalPosterior: float64
finalKernel: string
ade: float64
fde: float64
gapMax: int
gapViolations: int
proc parseFile(path, expectedKernel: string): RoundStat =
result.idTick = -1
let lines = readFile(path).splitLines()
for ln in lines:
if ln.len == 0: continue
if ln.startsWith("{\"event\":\"round_summary\""):
let _ = extract(ln, "finalPosterior").found
let p = extract(ln, "finalPosterior").value.parseFloat()
result.finalPosterior = p
result.finalKernel = extract(ln, "finalKernel").value
let t = extract(ln, "ticks").value.parseInt()
result.sumTicks = t
result.sumCensorRate = extract(ln, "censorRate").value.parseFloat()
result.ade = extract(ln, "ade").value.parseFloat()
result.fde = extract(ln, "fde").value.parseFloat()
result.gapMax = extract(ln, "scanGapMax").value.parseInt()
result.gapViolations = extract(ln, "scanGapViolations").value.parseInt()
elif ln.startsWith("{\"tick\""):
let (tf, ts) = extract(ln, "tick")
if not tf: continue
let tick = ts.parseInt()
# posteriorTop5 payload: find expected kernel weight
let top = ln.substr(ln.find("posteriorTop5"))
let nameI = top.find("\"name\":\"" & expectedKernel & "\",\"w\":")
if nameI >= 0:
let wI = top.find("\"w\":", nameI) + len("\"w\":")
var j = wI
while top[j] in Digits or top[j] == '.': inc j
let w = top[wI ..< j].parseFloat()
if w >= Threshold and (result.idTick < 0 or tick < result.idTick):
result.idTick = tick
type
Acc = object
ids: seq[int] # per-round unified idTick (-1 = never)
expIds: seq[int]
correct: int # rounds where argmaxCorrect
finalPost, censor, ade, fde: float64
rounds: int
gapMax, gapViol: int
proc run() =
guardSkip()
echo "[G4] staging ChimeraBot -> ", StageDir
let botDir = stageBot()
let botDir = stageBot("g4")
removeDir(Telemetry)
removeDir(Archive)
createDir(Archive)
ensureServer()
let url = getServerUrl()
echo "\nOpponent Rounds idTicks(sum) idTick_best finalPost finalK censorRate ade5 fde5 gapMax/viol"
var allTicks = 0
var passCount = 0
var acc = initTable[string, Acc]()
for opp in sorted(toSeq(Expected.keys)):
restartServer()
var url = serverUrl()
putEnv("CHIMERA_OPPONENT", opp)
putEnv("CHIMERA_TELEMETRY_DIR", Telemetry)
let sampleBot = SampleRoot / opp
var ok = false
# Flaky boot: the persistent server can race a battle start; retry.
for attempt in 1 .. MaxAttempts:
removeDir(Telemetry)
sleep(1500)
try:
discard runBattleRunner(url, @[botDir, sampleBot], rounds = Rounds,
timeout = 300000)
ok = true
break
except CatchableError:
if attempt >= MaxAttempts:
echo " ", opp, ": battle failed after ", MaxAttempts, " attempts"
if not ok: continue
if not dirExists(Archive): createDir(Archive)
copyDir(Telemetry, Archive / opp) # keep per-opponent telemetry for analysis
# aggregate best round + total ticks
let files = toSeq(walkFiles(Telemetry / "*.jsonl"))
var best = RoundStat(idTick: high(int), finalPosterior: 0.0,
ade: 0.0, fde: 0.0)
var roundTicks = 0
var any = false
for f in files:
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
any = true
roundTicks += rs.sumTicks
if rs.idTick > 0 and rs.idTick < best.idTick:
best.idTick = rs.idTick
if rs.finalPosterior > best.finalPosterior:
best.finalPosterior = rs.finalPosterior
best.finalKernel = rs.finalKernel
best.sumCensorRate = rs.sumCensorRate
best.ade = rs.ade
best.fde = rs.fde
best.gapMax = rs.gapMax
best.gapViolations = rs.gapViolations
if not any:
echo " ", opp, ": no telemetry produced"
continue
allTicks += roundTicks
let idStr = if best.idTick < 0 or best.idTick >= high(int): "-"
else: $best.idTick & (if best.idTick <= TargetTicks: "*" else: "")
let passed = best.idTick > 0 and best.idTick <= TargetTicks
if passed: inc passCount
echo " ", alignLeft(opp, 12), " ", align($Rounds, 4), " ",
align($roundTicks, 8), " ", align(idStr, 10), " ",
align($best.finalPosterior, 9), " ",
alignLeft(best.finalKernel, 10), " ",
align($best.sumCensorRate, 7), " ",
align($best.ade, 6), " ", align($best.fde, 6), " ",
$best.gapMax & "/" & $best.gapViolations
var a: Acc
for run in 1 .. Repeat:
var ok = false
for attempt in 1 .. MaxAttempts:
removeDir(Telemetry)
sleep(500)
if runBattleHard(url, @[botDir, sampleBot], Rounds, 90000):
ok = true
break
echo " ", opp, " run", run, " attempt", attempt, ": battle failed/timeout"
killStaleBots()
restartServer()
url = serverUrl()
if not ok: continue
let runDir = Archive / (opp & "-run" & $run)
copyDir(Telemetry, runDir)
for f in toSeq(walkFiles(runDir / "*.jsonl")):
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
inc a.rounds
a.ids.add(if rs.identified: rs.idTick else: -1)
a.expIds.add(if rs.expIdTick > 0: rs.expIdTick else: -1)
if rs.argmaxCorrect: inc a.correct
a.finalPost += rs.finalPosterior
a.censor += rs.censorRate
a.ade += rs.ade
a.fde += rs.fde
a.gapMax = max(a.gapMax, rs.gapMax)
a.gapViol += rs.gapViolations
if a.rounds > 0: acc[opp] = a
echo "\nTotal identification-capable ticks observed: ", allTicks
echo "Passed (idTick<=300): ", passCount, "/", Expected.len
echo "Per-opponent telemetry archived at: ", Archive
echo "\n=== G4 unified idTicks (M5.5): ", Repeat, " runs x ", Rounds,
" rounds per opponent ==="
echo "Opponent med p90 id% expMed argmaxOk% finalPost% censor% ade5 gapMax/viol"
var lines: seq[string]
lines.add("# G4 unified idTicks (M5.5)\n")
lines.add("Metric: per round, round-relative tick at which `max_kernel posterior > 0.8`; " &
"median / p90 / id-fraction over all rounds. Pass = median <= 300 AND id% >= 80. " &
$Repeat & " runs x " & $Rounds & " rounds. Generated by `tests/bench_g4.nim`.\n")
lines.add("| opponent | median | p90 | id-fraction% | expMedian | argmaxOk% | finalPost% | censor% | ade5 | pass |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|---:|---|")
var passed = 0
var comparable = 0
var pooled: seq[int]
for opp in sorted(toSeq(Expected.keys)):
if opp notin acc: continue
let a = acc[opp]
let s = idStats(a.ids)
let se = idStats(a.expIds)
let n = float(a.rounds)
let correctPct = 100.0 * float(a.correct) / n
let pass = s.median > 0 and s.median <= TargetTicks and s.idFraction >= 80.0
inc comparable
if pass: inc passed
pooled.add a.ids
echo " ", alignLeft(opp, 12), s.fmt,
align($(if se.median < 0: "-" else: $se.median), 7),
align(formatFloat(correctPct, ffDecimal, 0), 10),
align(formatFloat(a.finalPost / n * 100.0, ffDecimal, 0), 11),
align(formatFloat(a.censor / n * 100.0, ffDecimal, 1), 8),
align(formatFloat(a.ade / n, ffDecimal, 2), 6), " ",
$a.gapMax & "/" & $a.gapViol
lines.add "| " & opp & " | " & $(if s.median < 0: -1 else: s.median) & " | " &
$(if s.p90 < 0: -1 else: s.p90) & " | " &
formatFloat(s.idFraction, ffDecimal, 1) & " | " &
$(if se.median < 0: -1 else: se.median) & " | " &
formatFloat(correctPct, ffDecimal, 1) & " | " &
formatFloat(a.finalPost / n * 100.0, ffDecimal, 1) & " | " &
formatFloat(a.censor / n * 100.0, ffDecimal, 2) & " | " &
formatFloat(a.ade / n, ffDecimal, 3) & " | " &
(if pass: "PASS" else: "FAIL") & " |"
let ps = idStats(pooled)
echo "\nPooled (all ", pooled.len, " rounds): median ", ps.median,
" p90 ", ps.p90, " id% ", formatFloat(ps.idFraction, ffDecimal, 1)
echo "G4 pass (median<=300 AND id%>=80): ", passed, "/", comparable,
" over ", Repeat, " full 8x5 runs"
lines.add "\nPooled over " & $pooled.len & " rounds: median " & $ps.median &
", p90 " & $ps.p90 & ", id-fraction " &
formatFloat(ps.idFraction, ffDecimal, 1) & "%. G4 pass: " & $passed & "/" &
$comparable & "."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g4.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "Artifact: ", art
echo "Telemetry archived at: ", Archive
when isMainModule:
run()
run()