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
+119 -186
View File
@@ -1,220 +1,153 @@
## G6 ablation ladder — probes ON vs OFF (CHIMERA M5). LIVE, Java required.
## G6 ablation ladder — probes x carry-over (CHIMERA M5.5). LIVE, Java required.
##
## Runs the same 8×5 pinned-opponent protocol (bench_g4's set) for both builds:
## * ON — default build, probe scheduler wired (spec §9)
## * OFF — `-d:chimeraNoProbes`, probe advisory removed (command path == M1 copy)
## repeated `Repeat` (default 3) full runs each, and reports the MEDIAN
## identification tick per opponent (spec G4: median over >= 3 runs, to survive
## the sample-bot spawn variance) plus the G6 pass bar: probes cut the median
## identification ticks by >= 20%.
## Four arms over the same 8x5 pinned-opponent protocol, using the UNIFIED
## idTicks metric (round-relative, max posterior > 0.8; median/p90/id-fraction
## over all rounds):
## * on — probes ON, cross-round carry-over ON (default build)
## * off — probes OFF, carry-over ON (-d:chimeraNoProbes)
## * reset — probes ON, fresh-round reset ON (-d:chimeraFreshRound)
## * offreset — probes OFF, fresh-round reset ON (both defines)
##
## A round that never crosses the threshold is censored at its own tick count,
## so "never identified" cannot masquerade as a fast round; the identification
## rate is reported separately.
## Primary G6 read: probes must cut the MOVING-subset median identification
## ticks by >= 20% (`on` vs `off`), reported for the full suite too. The
## carry-over effect is `on` vs `reset`.
##
## ON telemetry is archived to /tmp/chimera_g6_on (input to bench_g5p.nim).
## Throwaway output only under /tmp. Run:
## `nim c -r --hints:off -d:release tests/bench_g6.nim`
## ON telemetry archived to /tmp/chimera_g6_on (input to bench_g5p.nim).
## Run: `nim c -r --hints:off -d:release tests/bench_g6.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm]
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times]
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_g6_stage"
Rounds = 5
Repeat = 3
Telemetry = getTempDir() / "chimera_twin"
OnDir = getTempDir() / "chimera_g6_on"
OffDir = getTempDir() / "chimera_g6_off"
Rounds = 5
Repeat = 3
Threshold = 0.8
TargetTicks = 300
MaxAttempts = 4
ArmTags = ["on", "off", "reset", "offreset"]
const Expected = {
"Crazy": "ZIGZAG",
"SpinBot": "ORBIT_BALLIST",
"RamFire": "STATIC",
"Corners": "STATIC",
"Walls": "WALLCRAWL",
"TrackFire": "STATIC",
"Fire": "STATIC",
"VelociBot": "STOP_AND_GO",
}.toTable
proc armDefines(tag: string): seq[string] =
case tag
of "on": @[]
of "off": @["-d:chimeraNoProbes"]
of "reset": @["-d:chimeraFreshRound"]
else: @["-d:chimeraNoProbes", "-d:chimeraFreshRound"]
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 G6 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(tag: string, off: bool): string =
let botDir = StageDir / tag / "ChimeraBot"
removeDir(StageDir / tag)
createDir(botDir)
let bin = botDir / "ChimeraBot"
var cmd = "nim c -d:release --hints:off "
if off: cmd.add "-d:chimeraNoProbes "
cmd.add deps().join(" ") & " --out:\"" & bin & "\" " &
quoteShell(GarageSrc / "ChimeraBot.nim")
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"
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])
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 weight(expected) >= Threshold, else -1
sumTicks: int
identified: bool
proc parseFile(path, expectedKernel: string): RoundStat =
result.idTick = -1
for ln in readFile(path).splitLines():
if ln.len == 0: continue
if ln.startsWith("{\"event\":\"round_summary\""):
result.sumTicks = extract(ln, "ticks").value.parseInt()
elif ln.startsWith("{\"tick\""):
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 j < top.len and (top[j] in Digits or top[j] == '.'): inc j
let w = top[wI ..< j].parseFloat()
let tick = extract(ln, "tick").value.parseInt()
if w >= Threshold and (result.idTick < 0 or tick < result.idTick):
result.idTick = tick
result.identified = result.idTick > 0
proc median(xs: seq[int]): int =
if xs.len == 0: return -1
var s = xs; s.sort()
s[s.len div 2]
proc runArm(tag: string, off: bool): Table[string, seq[int]] =
let botDir = stageBot(tag, off)
proc runArm(tag: string): Table[string, seq[int]] =
let botDir = stageBot("g6_" & tag, armDefines(tag))
removeDir(Telemetry)
let armDir = if off: OffDir else: OnDir
let armDir = getTempDir() / ("chimera_g6_" & tag)
removeDir(armDir)
createDir(armDir)
ensureServer()
let url = getServerUrl()
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 ids: seq[int]
for run in 1 .. Repeat:
var ok = false
let t0 = epochTime()
for attempt in 1 .. MaxAttempts:
removeDir(Telemetry)
sleep(1200)
try:
discard runBattleRunner(url, @[botDir, sampleBot], rounds = Rounds,
timeout = 300000)
sleep(500)
if runBattleHard(url, @[botDir, sampleBot], Rounds, 90000):
ok = true
break
except CatchableError:
if attempt >= MaxAttempts:
echo " ", tag, " ", opp, " run", run, ": battle failed"
echo " ", tag, " ", opp, " run", run, " attempt", attempt,
": battle failed/timeout"
killStaleBots()
restartServer()
url = serverUrl()
echo " [", tag, "] ", opp, " run", run, " ok=", ok, " in ",
formatFloat(epochTime() - t0, ffDecimal, 1), "s (attempts used)"
if not ok: continue
copyDir(Telemetry, armDir / (opp & "-run" & $run))
# parse everything for this opponent
var ids: seq[int]
for f in walkDirRec(armDir):
if not f.endsWith(".jsonl"): continue
if not f.extractFilename.startsWith(opp & "-"): continue
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
ids.add (if rs.identified: rs.idTick else: rs.sumTicks)
let runDir = armDir / (opp & "-run" & $run)
copyDir(Telemetry, runDir)
for f in toSeq(walkFiles(runDir / "*.jsonl")):
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
ids.add(if rs.identified: rs.idTick else: -1)
result[opp] = ids
proc stats(ids: seq[int]): tuple[med, rate: float64, n: int] =
if ids.len == 0: return (-1.0, 0.0, 0)
var identified = 0
for x in ids:
if x <= TargetTicks: inc identified
(float(median(ids)), 100.0 * float(identified) / float(ids.len), ids.len)
proc pooled(arm: Table[string, seq[int]], opps: seq[string]): seq[int] =
for opp in opps:
if opp in arm: result.add arm[opp]
proc cutPct(onMed, offMed: int): float64 =
if offMed <= 0: 0.0 else: 100.0 * float(offMed - onMed) / float(offMed)
proc main() =
guardSkip()
echo "[G6] staging ON/OFF builds and running ", Repeat, " full runs each"
let on = runArm("on", false)
let off = runArm("off", true)
echo "[G6] 4 arms x ", Repeat, " runs x ", Rounds, " rounds"
var tabs = initTable[string, Table[string, seq[int]]]()
for tag in ArmTags:
tabs[tag] = runArm(tag)
echo "\nG6 identification ticks, median over ", Repeat, " runs x ", Rounds,
" rounds (censored rounds scored at their tick count)"
echo "Opponent onMed onID% offMed offID% cut%"
var pooledOn, pooledOff: seq[int]
var onPass, offPass = 0
var comparable = 0
var cutSum = 0.0
var cutN = 0
echo "\n=== G6 arms: unified idTicks median / id-fraction% (", Repeat,
" runs x ", Rounds, " rounds) ==="
echo "Opponent on med id% off med id% reset med id% offreset med id%"
var lines: seq[string]
lines.add("# G6 ablation ladder (M5.5): probes x carry-over\n")
lines.add("Unified idTicks (round-relative, max posterior > 0.8), median over " &
$Repeat & " runs x " & $Rounds & " rounds; id% = fraction of rounds identified. " &
"Arms: on = probes+carry, off = -probes, reset = -carry, offreset = both. " &
"Generated by `tests/bench_g6.nim`.\n")
lines.add("| opponent | on med | on id% | off med | off id% | reset med | reset id% | offreset med | offreset id% |")
lines.add("|---|---:|---:|---:|---:|---:|---:|---:|---:|")
for opp in sorted(toSeq(Expected.keys)):
if not (opp in on and opp in off): continue
let so = stats(on[opp])
let sf = stats(off[opp])
if so.n == 0 or sf.n == 0: continue
pooledOn.add on[opp]
pooledOff.add off[opp]
inc comparable
if so.med <= TargetTicks: inc onPass
if sf.med <= TargetTicks: inc offPass
let cut = if sf.med > 0: 100.0 * (sf.med - so.med) / sf.med else: 0.0
cutSum += cut; inc cutN
echo " ", alignLeft(opp, 12),
align($int(so.med), 6), " ", align(formatFloat(so.rate, ffDecimal, 0), 5),
" ", align($int(sf.med), 7), " ", align(formatFloat(sf.rate, ffDecimal, 0), 5),
" ", align(formatFloat(cut, ffDecimal, 1), 6)
let onAll = median(pooledOn)
let offAll = median(pooledOff)
let overall = if offAll > 0: 100.0 * float(offAll - onAll) / float(offAll) else: 0.0
echo "\nPooled median ON = ", onAll, " ticks, OFF = ", offAll, " ticks"
echo "G6 probes cut median identification by ", formatFloat(overall, ffDecimal, 1),
"% (bar >= 20%): ", (if overall >= 20.0: "PASS" else: "FAIL")
echo "G4 median pass (ON, <= ", TargetTicks, "): ", onPass, "/", comparable,
" (OFF: ", offPass, "/", comparable, ")"
echo "Per-opponent cut mean = ",
formatFloat(if cutN > 0: cutSum / float(cutN) else: 0.0, ffDecimal, 1), "%"
echo "ON telemetry archived at ", OnDir, " (G5' input)"
var cells: seq[string]
var textLine = " " & alignLeft(opp, 12)
var row = "| " & opp & " |"
for tag in ArmTags:
if opp in tabs[tag]:
let s = idStats(tabs[tag][opp])
let m = if s.median < 0: "-" else: $s.median
textLine.add align(m, 8) & align(formatFloat(s.idFraction, ffDecimal, 0), 5)
row.add " " & m & " | " & formatFloat(s.idFraction, ffDecimal, 1) & " |"
else:
textLine.add align("-", 8) & align("-", 5)
row.add " - | - |"
echo textLine
lines.add row
let full = @["Crazy", "SpinBot", "RamFire", "Corners", "Walls",
"TrackFire", "Fire", "VelociBot"]
echo ""
echo "Metric on off reset offreset"
for (label, opps) in [("MOVING-subset", MovingOpponents), ("FULL-suite", full)]:
var st: Table[string, IdStats]
for tag in ArmTags:
st[tag] = idStats(pooled(tabs[tag], opps))
echo alignLeft(label, 18),
align($st["on"].median, 7), align($st["off"].median, 8),
align($st["reset"].median, 8), align($st["offreset"].median, 10),
" (id%: ", formatFloat(st["on"].idFraction, ffDecimal, 0), "/",
formatFloat(st["off"].idFraction, ffDecimal, 0), "/",
formatFloat(st["reset"].idFraction, ffDecimal, 0), "/",
formatFloat(st["offreset"].idFraction, ffDecimal, 0), ")"
let cut = cutPct(st["on"].median, st["off"].median)
let carryGain = if st["reset"].median > 0:
100.0 * float(st["reset"].median - st["on"].median) / float(st["reset"].median)
else: 0.0
echo " probes cut (off->on) = ", formatFloat(cut, ffDecimal, 1),
"% carry-over gain (reset->on) = ", formatFloat(carryGain, ffDecimal, 1), "%"
lines.add "\n**" & label & "** pooled: on " & $st["on"].median & " (id " &
formatFloat(st["on"].idFraction, ffDecimal, 1) & "%), off " &
$st["off"].median & " (id " & formatFloat(st["off"].idFraction, ffDecimal, 1) &
"%), reset " & $st["reset"].median & " (id " &
formatFloat(st["reset"].idFraction, ffDecimal, 1) & "%), offreset " &
$st["offreset"].median & " (id " &
formatFloat(st["offreset"].idFraction, ffDecimal, 1) & "%). Probes cut = " &
formatFloat(cut, ffDecimal, 1) & "%, carry-over gain = " &
formatFloat(carryGain, ffDecimal, 1) & "%. **G6 bar (>=20% cut, " & label & "): " &
(if cut >= 20.0: "PASS" else: "FAIL") & "**."
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m5_5_g6.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "Artifact: ", art
echo "ON telemetry archived at ", getTempDir() / "chimera_g6_on"
when isMainModule:
main()