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
+29
View File
@@ -0,0 +1,29 @@
# G7 head-to-head + no-regression floor (M6)
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, 10 matches x 5 rounds. Suite: 5 rounds per arm per opponent vs the 8 primary sample bots. Generated by `tests/bench_g7.nim`.
## Head-to-head: full vs inert
| metric | value |
|---|---:|
| matches | 10 x 5 rounds |
| full win-rate | 54.0% |
| full survival | 40 / inert 39 |
| score margin (full-inert) | 1621.0 |
| **bar (>=50%)** | **PASS** |
## Suite no-regression floor (5 rounds per arm)
| opponent | full W% | full margin | full surv | inert W% | inert margin | inert surv | noProbe W% | noProbe margin |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| Corners | 100.0 | 2466.0 | 5 | 100.0 | 2477.0 | 5 | 100.0 | 2486.0 |
| Crazy | 100.0 | 1669.0 | 5 | 100.0 | 1867.0 | 5 | 100.0 | 1311.0 |
| Fire | 100.0 | 2620.0 | 5 | 100.0 | 2607.0 | 5 | 100.0 | 2583.0 |
| RamFire | 100.0 | 2468.0 | 5 | 100.0 | 2574.0 | 5 | 100.0 | 2556.0 |
| SpinBot | 100.0 | 1798.0 | 5 | 100.0 | 1618.0 | 5 | 100.0 | 1842.0 |
| TrackFire | 100.0 | 2349.0 | 5 | 100.0 | 2406.0 | 5 | 100.0 | 2414.0 |
| VelociBot | 80.0 | 1132.0 | 4 | 80.0 | 927.0 | 4 | 100.0 | 2005.0 |
| Walls | 100.0 | 1808.0 | 5 | 100.0 | 1912.0 | 5 | 100.0 | 1693.0 |
**No-regression (full >= inert on every opponent): PASS**.
Head-to-head win rate 54.0% (bar >=50%: PASS).
+14
View File
@@ -36,6 +36,7 @@ import ChimeraBot/chimera/observer
import ChimeraBot/chimera/dsl
import ChimeraBot/chimera/probes
import ChimeraBot/chimera/physics
import ChimeraBot/chimera/influence
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
@@ -289,6 +290,19 @@ method run*(bot: ChimeraBot) =
# removes this block entirely (G6 ablation OFF arm).
var cmdSpeed = speed
var cmdTurn = turnRate
# CHIMERA influence overlay (spec §10, M6): a small tie-break on the TFIL
# command toward the fused-safest plan, never inside an active bullet dodge
# (reflexBusy). `-d:chimeraNoFusion` / `-d:chimeraInert` remove it entirely.
when FusionEnabled:
if bot.observer.hasCurrent:
let (sx, sy) = (getX(), getY())
let fused = bot.observer.fusedPrediction()
let adv = overlay(bot.observer.fusedInfluence(), speed, turnRate,
sx, sy, getDirection(), getSpeed(), fused,
bot.mover.dodgeActive(sx, sy))
if adv.applied:
cmdSpeed = adv.speed
cmdTurn = adv.turnRate
var probeFired = false
when ProbesEnabled:
if bot.observer.hasCurrent:
+3
View File
@@ -261,3 +261,6 @@ task test, "Run unit tests":
exec "nim c -r --hints:off ../tests/test_observer.nim"
exec "nim c -r --hints:off ../tests/test_twinsim.nim"
exec "nim c -r --hints:off ../tests/test_probes.nim"
exec "nim c -r --hints:off ../tests/test_residual.nim"
exec "nim c -r --hints:off ../tests/test_fusion.nim"
exec "nim c -r --hints:off ../tests/test_influence.nim"
@@ -0,0 +1,138 @@
## CHIMERA predictor fusion — hedge over PREDICTORS (spec §10).
##
## Three predictors compete for the counterfactual rollout:
## * `mixture` — the posterior-weighted kernel mixture (twinsim `rollout`),
## * `residual` — the mixture with the online linear residual correction
## applied to each tick's predicted intent (`residual.nim`),
## * `persistence` — constant-velocity carry (`twinsim.persistence`).
##
## Weights are updated by realized-vs-predicted loss per channel (turn, speed,
## fire) using the same Hedge/EWA machinery as the kernel posterior
## (`hedge.nim`), so the two layers share one update contract. The fused
## prediction is the weight-blended 5-tick trajectory plus a fused `P(fire
## within k)`; `confidence` is the fusion's own weight concentration damped by
## its recent realised loss (a monotone, deterministic reliability scalar).
##
## Pure and deterministic: no I/O, no clock, no RNG.
import std/math
import ./physics, ./dsl, ./twinsim, ./residual, ./hedge
const
NPredictors* = 3
MixtureIdx* = 0
ResidualIdx* = 1
PersistenceIdx* = 2
PredictorNames* = @["mixture", "residual", "persistence"]
LossScale* = 2.0 ## loss -> confidence falloff scale
BetaDefault* = 0.05
type
PredIntent* = object
## One predictor's next-tick intent prediction, or the realized intent.
turn*, speed*, fire*: float64
FusedPrediction* = object
horizon*: int
points*: seq[tuple[x, y: float64]]
pFire*: seq[float64]
fireWithin*: float64 ## fused P(fire at least once in 1..k)
confidence*: float64 ## 0..1, deterministic reliability scalar
lossEma*: float64
Fusion* = object
hedge*: Hedge
lossEma*: float64
lossN*: int
beta*: float64
# ── construction ────────────────────────────────────────────────────────────
proc initFusion*(cfg = HedgeConfig()): Fusion =
result.hedge = initHedge(PredictorNames, cfg)
result.beta = BetaDefault
proc weights*(f: Fusion): seq[float64] = f.hedge.weights
# ── per-channel loss (realized vs predicted) ────────────────────────────────
proc channelLoss*(realized, pred: PredIntent): float64 =
## Smooth per-tick loss: normalised squared turn + speed error, plus a
## Bernoulli log-loss on the fire channel. Scale-free enough that a single
## Hedge learning rate stays stable.
let dt = (realized.turn - pred.turn) / 10.0
let ds = (realized.speed - pred.speed) / 8.0
var l = dt * dt + ds * ds
let p = clamp(pred.fire, 1e-3, 1.0 - 1e-3)
let y = if realized.fire > 0.0: 1.0 else: 0.0
l += -(y * ln(p) + (1.0 - y) * ln(1.0 - p))
l
proc update*(f: var Fusion, realized: PredIntent, preds: openArray[PredIntent]) =
## One fusion step: score every predictor on this tick's realized intent, move
## the weights, update the fused-loss EMA.
doAssert preds.len == NPredictors, "need exactly NPredictors predictions"
var losses: array[NPredictors, float64]
for i in 0 ..< NPredictors:
losses[i] = channelLoss(realized, preds[i])
f.hedge.update(losses)
var fl = 0.0
for i in 0 ..< NPredictors:
fl += f.hedge.weights[i] * losses[i]
if f.lossN == 0: f.lossEma = fl
else: f.lossEma = (1.0 - f.beta) * f.lossEma + f.beta * fl
inc f.lossN
proc confidence*(f: Fusion): float64 =
## Weight concentration damped by recent realized loss. Deterministic.
var wmax = 0.0
for w in f.hedge.weights: wmax = max(wmax, w)
let ema = if f.lossN == 0: 0.0 else: f.lossEma
clamp(wmax * exp(-ema / LossScale), 0.0, 1.0)
# ── residual trajectory + fused rollout ─────────────────────────────────────
proc residualTrajectory*(origin: ReplayTick, mix: seq[RolloutPoint],
rp: ResidualPrediction, k: int): seq[tuple[x, y: float64]] =
## Integrate the mixture's per-tick intent PLUS the residual correction from
## the enemy origin through the physics mirror. A distinct, deterministic
## predictor: same base as the mixture, corrected by what it systematically
## got wrong.
var dir = origin.edir
var sp = origin.espeed
var x = origin.ex
var y = origin.ey
for h in 0 ..< k:
let baseTurn = (if h < mix.len: mix[h].turnRate else: origin.lastTurn)
let baseSpeed = (if h < mix.len: mix[h].targetSpeed else: origin.lastSpeed)
let ts = clamp(baseSpeed + rp.speed, MaxBackwardSpeed, MaxForwardSpeed)
sp = stepSpeed(sp, ts)
dir = wrap180(dir + limitTurnRate(baseTurn + rp.turn, sp))
x += sp * cos(degToRad(dir))
y += sp * sin(degToRad(dir))
result.add (x, y)
proc fusedPrediction*(f: Fusion, kernels: seq[Kernel], origin: ReplayTick,
rp: ResidualPrediction, k = 5): FusedPrediction =
## The fused 5-tick counterfactual prediction used by the influence layer.
let mix = rollout(kernels, origin, k)
let resPts = residualTrajectory(origin, mix.points, rp, k)
let persPts = persistence(origin, k)
let wm = f.hedge.weights[MixtureIdx]
let wr = f.hedge.weights[ResidualIdx]
let wp = f.hedge.weights[PersistenceIdx]
result.horizon = k
var pNoFire = 1.0
for h in 0 ..< k:
let mx = wm * mix.points[h].x + wr * resPts[h].x + wp * persPts[h].x
let my = wm * mix.points[h].y + wr * resPts[h].y + wp * persPts[h].y
result.points.add (mx, my)
var pf = wm * mix.points[h].pFire
pf += wr * clamp(mix.points[h].pFire + rp.fire, 0.0, 1.0)
# persistence carries no fire model: contributes 0
let pfC = clamp(pf, 0.0, 1.0)
result.pFire.add pfC
pNoFire *= (1.0 - pfC)
result.fireWithin = 1.0 - pNoFire
result.confidence = f.confidence()
result.lossEma = f.lossEma
@@ -0,0 +1,92 @@
## CHIMERA influence / fallback — how much the twin is allowed to steer us
## (spec §10 "Failure fallback" + §8 "predictive bullet avoidance").
##
## The twin's advice is a *tie-breaker*, never a reflex override. Two things
## happen here:
##
## 1. `influenceScalar` turns the fusion's realized-vs-predicted loss into a
## single 0..1 scalar: it ramps to 1 while the twin predicts well and to 0
## once the loss degrades past `BadLoss`. With no evidence it is 0 — the
## conservative choice, i.e. the bot degrades to DevControlBot behaviour.
## 2. `overlay` may nudge the EXISTING TFIL command (turn/speed) toward the
## candidate whose fused 5-tick rollout stays furthest from the predicted
## enemy path, weighting ticks by the fused fire probability. It only applies
## when the nudge clears a safety margin (`MinGain`), never touches a tick
## where TFIL's bullet-avoidance is active (`reflexBusy`), and can only
## change turn by <= `MaxTurnBias` deg and speed by <= `MaxSpeedDelta`.
##
## Pure and deterministic: no I/O, no clock, no RNG.
import std/math
import ./physics, ./fusion
const
GoodLoss* = 0.5 ## below this the twin is fully trusted
BadLoss* = 2.0 ## above this influence is 0 (degrade to baseline)
MinGain* = 3.0 ## units of extra clearance required to apply a nudge
MaxTurnBias* = 12.0 ## deg, hard cap on the overlay's turn adjustment
MaxSpeedDelta* = 2.0 ## units/tick, hard cap on the speed adjustment
type
InfluenceAdvisory* = object
influence*: float64 ## 0..1 twin steering authority
applied*: bool
speed*: float64 ## command after the overlay (== TFIL when not applied)
turnRate*: float64
gain*: float64 ## clearance improvement of the chosen nudge
proc influenceScalar*(lossEma: float64, samples: int): float64 =
## Loss-degradation ramp (spec §10). No samples => 0 (never steer blindly).
if samples <= 0: return 0.0
clamp((BadLoss - lossEma) / (BadLoss - GoodLoss), 0.0, 1.0)
proc overlay*(influence: float64,
tfilSpeed, tfilTurn: float64,
selfX, selfY, selfHeading, selfSpeed: float64,
fused: FusedPrediction,
reflexBusy: bool): InfluenceAdvisory =
## Overlay a small, safe correction on the TFIL command.
result.influence = influence
result.speed = tfilSpeed
result.turnRate = tfilTurn
if reflexBusy or influence <= 1e-6 or fused.points.len == 0:
return
let k = fused.points.len
# Safety score of a candidate (speed, turn): the fire-weighted minimum
# clearance from our own 5-tick rollout to the fused enemy path.
proc safety(speed, turn: float64): float64 =
var x = selfX
var y = selfY
var dir = selfHeading
var sp = selfSpeed
var best = Inf
for h in 0 ..< k:
sp = stepSpeed(sp, speed)
dir = wrap180(dir + limitTurnRate(turn, sp))
x += sp * cos(degToRad(dir))
y += sp * sin(degToRad(dir))
let d = hypot(x - fused.points[h].x, y - fused.points[h].y)
let w = 1.0 + (if h < fused.pFire.len: fused.pFire[h] else: 0.0)
best = min(best, d * w)
best
let base = safety(tfilSpeed, tfilTurn)
var bestGain = 0.0
var bestSpeed = tfilSpeed
var bestTurn = tfilTurn
for bias in [-MaxTurnBias, -MaxTurnBias * 0.5, MaxTurnBias * 0.5, MaxTurnBias]:
for dsp in [0.0, -MaxSpeedDelta, MaxSpeedDelta]:
let s = clamp(tfilSpeed + dsp, MaxBackwardSpeed, MaxForwardSpeed)
let t = tfilTurn + bias
let g = safety(s, t) - base
if g > bestGain + 1e-12:
bestGain = g
bestSpeed = s
bestTurn = t
if influence * bestGain >= MinGain:
result.speed = bestSpeed
result.turnRate = bestTurn
result.applied = true
result.gain = bestGain
@@ -19,11 +19,14 @@
## readiness check for the M4 twin rollout, not the twin itself.
import std/[math, os, strutils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence
const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
PredSlots* = 8 ## ring size; > MaxHorizon so an origin survives its queries
FusionEnabled* = not defined(chimeraNoFusion) and not defined(chimeraInert)
## M6 kill switches: `-d:chimeraNoFusion` drops the residual+fusion layer,
## `-d:chimeraInert` drops every CHIMERA command path (== M1 exact copy).
type
Observer* = ref object
@@ -62,6 +65,15 @@ type
# restores the per-round reset).
carryOver*: bool
# M6 residual + fusion (spec §10). Observation-only training lives here
# because the ledger fold is already computed here; the influence overlay
# itself runs in the bot's command path.
residual: ResidualHead
fusion: Fusion
prevOwnDir, prevOwnSpeed: float64
lastRealizedTurn, lastRealizedSpeed: float64
fireRateEma: float64
## predictions: `predPos[(origin mod PredSlots)][h]` is the enemy position
## predicted `h` ticks after `origin`; `predOrigin` guards a slot's owner.
predPos: array[PredSlots, array[MaxHorizon + 1, tuple[x, y: float64]]]
@@ -83,6 +95,8 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer =
result.telemetryDir = telemetryDir
result.scanTick = -1
result.enemyHeat = 3.0
result.residual = initResidualHead()
result.fusion = initFusion()
result.carryOver = not defined(chimeraFreshRound)
for i in 0 ..< PredSlots: result.predOrigin[i] = -1
@@ -100,6 +114,9 @@ proc resetRoundStats(o: Observer) =
o.adeSum = 0; o.adeN = 0
o.fdeSum = 0; o.fdeN = 0
o.enemyHeat = 3.0 ## round-start heat (spec §5)
o.prevOwnDir = 0.0; o.prevOwnSpeed = 0.0
o.lastRealizedTurn = 0.0; o.lastRealizedSpeed = 0.0
o.fireRateEma = 0.0
for i in 0 ..< PredSlots: o.predOrigin[i] = -1
proc resetRound(o: Observer) =
@@ -107,6 +124,8 @@ proc resetRound(o: Observer) =
o.hedge = initHedge(kernelNames(o.kernels), o.cfg)
for i in 0 ..< o.kernels.len:
o.mems[i] = defaultMemory(o.kernels[i].defaultParams)
o.residual.reset()
o.fusion = initFusion()
o.resetRoundStats()
proc sanitize*(s: string): string =
@@ -246,11 +265,47 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6
energy: o.prev.energy)
let my = MyState(x: o.prevOwnX, y: o.prevOwnY)
var losses = newSeq[float64](o.kernels.len)
var mixTurn, mixSpeed, mixFire = 0.0
for i in 0 ..< o.kernels.len:
let pred = o.kernels[i].step(e, my, o.kernels[i].defaultParams, o.mems[i])
losses[i] = intentLoss(pred, obs, s.speed)
let w = o.hedge.weights[i]
mixTurn += w * pred.turnRate
mixSpeed += w * pred.targetSpeed
mixFire += w * pred.fire
o.hedge.update(losses)
when FusionEnabled:
# Residual + fusion training (spec §10): learn the mixture's residual on
# THIS realized intent, then score the three predictors. Observation
# only — nothing here can change a command.
let realized = PredIntent(
turn: (if obs.turnKnown: (obs.turnRate.lo + obs.turnRate.hi) / 2.0 else: mixTurn),
speed: (if obs.targetKnown: (obs.targetSpeed.lo + obs.targetSpeed.hi) / 2.0 else: mixSpeed),
fire: (if obs.fireKnown: obs.fire else: mixFire))
let feat = features(ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: float64(s.tick - o.prev.tick),
dist: hypot(o.prev.x - o.prevOwnX, o.prev.y - o.prevOwnY),
ownTurn: wrap180(ownDir - o.prevOwnDir), ownSpeed: o.prevOwnSpeed))
let rpred = o.residual.predict(feat)
let persP = PredIntent(turn: o.lastRealizedTurn,
speed: o.lastRealizedSpeed, fire: o.fireRateEma)
o.fusion.update(realized, [
PredIntent(turn: mixTurn, speed: mixSpeed, fire: mixFire),
PredIntent(turn: mixTurn + rpred.turn, speed: mixSpeed + rpred.speed,
fire: clamp(mixFire + rpred.fire, 0.0, 1.0)),
persP])
o.residual.observe(feat, ResidualTarget(
turn: realized.turn - mixTurn, speed: realized.speed - mixSpeed,
fire: realized.fire - mixFire))
o.lastRealizedTurn = realized.turn
o.lastRealizedSpeed = realized.speed
if obs.fireKnown:
let y = (if obs.fire > 0.0: 1.0 else: 0.0)
o.fireRateEma = 0.95 * o.fireRateEma + 0.05 * y
o.prevOwnDir = o.curOwnDir
o.prevOwnSpeed = o.curOwnSpeed
o.prev = s; o.prevOwnX = ownX; o.prevOwnY = ownY; o.havePrev = true
o.cur = s; o.curOwnX = ownX; o.curOwnY = ownY; o.haveCur = true
o.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed
@@ -282,6 +337,31 @@ proc probeOrigin*(o: Observer): ReplayTick =
result.weights = o.hedge.weights
result.mems = o.mems
proc currentResidualInput(o: Observer): ResidualInput =
## Feature inputs at the current origin (dense stream => scanAge 1).
ResidualInput(
lastTurn: o.lastRealizedTurn, lastSpeed: o.lastRealizedSpeed,
scanAge: 1.0,
dist: (if o.haveCur: hypot(o.cur.x - o.curOwnX, o.cur.y - o.curOwnY) else: 0.0),
ownTurn: 0.0,
ownSpeed: (if o.haveCur: o.curOwnSpeed else: 0.0))
proc fusedPrediction*(o: Observer, k = MaxHorizon): FusedPrediction =
## The fused 5-tick counterfactual prediction at the current origin (M6).
## Computed on demand; O(k * kernels) and allocation-light.
if not o.haveCur: return
let origin = o.probeOrigin()
let rp = o.residual.predict(features(o.currentResidualInput()))
o.fusion.fusedPrediction(o.kernels, origin, rp, k)
proc fusedInfluence*(o: Observer): float64 =
## Twin steering authority (0..1), ramped down by realized prediction loss.
influenceScalar(o.fusion.lossEma, o.fusion.lossN)
proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights()
proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma
proc fusionSamples*(o: Observer): int = o.fusion.lossN
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
entropyBefore, entropyAfter, turnRate,
targetSpeed: float64) =
@@ -24,9 +24,10 @@ import std/[math, algorithm]
import ./physics, ./dsl, ./twinsim
const
ProbesEnabled* = not defined(chimeraNoProbes)
ProbesEnabled* = not defined(chimeraNoProbes) and not defined(chimeraInert)
## Compile-time kill switch. `-d:chimeraNoProbes` removes the probe advisory
## from the bot entirely (G6 ablation OFF arm; command path == M1 baseline).
## `-d:chimeraInert` (M6) forces it off too: inert == the M1 exact copy.
DefaultInterval* = 25 ## nominal probe cadence, ticks (spec: 20–30)
MinInterval* = 20
@@ -0,0 +1,108 @@
## CHIMERA residual head — online linear correction for the posterior mixture.
##
## Source of truth: `docs/chimera-spec.md` §10. The DSL mixture is a compact
## approximation, so a small head absorbs its *systematic* mispredictions: it
## predicts the residual `realized - mixture_predicted` per channel (turn,
## targetSpeed, fire) from a fixed feature vector (last intents, scan age,
## distance, our last plan).
##
## Default: per-channel ridge-regularised online SGD, zero-initialised so runs
## are byte-identical (deterministic; no RNG). The 32-unit GRU upgrade path is
## reserved behind `-d:chimeraGRU` and is deliberately NOT implemented here — the
## flag currently selects the same linear head (see `UseGRU`), because the linear
## head is the M6 default and the GRU is an unproven cost we did not need.
##
## No I/O, no clock, no allocation: `observe` is O(NFeatures) and safe to call
## every scanned tick (well below µs at NFeatures = 6).
import std/math
const
NFeatures* = 6
## last enemy turn, last enemy targetSpeed, scan gap, distance,
## our last turn, our last speed.
UseGRU* = defined(chimeraGRU)
## Reserved upgrade path. The GRU is not implemented; when the flag is set
## the linear head is still what runs (documented deviation, M6).
type
ResidualInput* = object
## Everything the feature vector needs, all observable.
lastTurn*: float64 ## last realized enemy turn rate (deg/tick)
lastSpeed*: float64 ## last realized enemy target speed (units/tick)
scanAge*: float64 ## ticks since the previous scan (gap)
dist*: float64 ## our distance to the enemy (units)
ownTurn*: float64 ## our last commanded/observed body turn (deg/tick)
ownSpeed*: float64 ## our last realized speed (units/tick)
ResidualTarget* = object
## `realized - mixture_predicted`, per channel.
turn*, speed*, fire*: float64
ResidualPrediction* = object
turn*, speed*, fire*: float64
ResidualHead* = object
wTurn*, wSpeed*, wFire*: array[NFeatures, float64]
bTurn*, bSpeed*, bFire*: float64
lr*: float64
l2*: float64
samples*: int
# ── construction ────────────────────────────────────────────────────────────
proc initResidualHead*(lr = 0.05, l2 = 1e-4): ResidualHead =
## Zero weights, so two heads fed the same stream stay identical.
result.lr = lr
result.l2 = l2
proc reset*(h: var ResidualHead) =
## Back to the freshly-constructed state (keeps the configured lr/l2).
h = initResidualHead(h.lr, h.l2)
# ── features / prediction / update ──────────────────────────────────────────
proc features*(x: ResidualInput): array[NFeatures, float64] =
## Fixed, normalised feature vector, clamped to a sane band so an outlier
## observation can never blow the linear head up. Deterministic /
## allocation-free.
[clamp(x.lastTurn / 10.0, -4.0, 4.0),
clamp(x.lastSpeed / 8.0, -4.0, 4.0),
clamp(x.scanAge / 5.0, -4.0, 4.0),
clamp(x.dist / 800.0, 0.0, 4.0),
clamp(x.ownTurn / 10.0, -4.0, 4.0),
clamp(x.ownSpeed / 8.0, -4.0, 4.0)]
proc predict*(h: ResidualHead, f: array[NFeatures, float64]): ResidualPrediction =
var t = h.bTurn
var s = h.bSpeed
var fi = h.bFire
for i in 0 ..< NFeatures:
t += h.wTurn[i] * f[i]
s += h.wSpeed[i] * f[i]
fi += h.wFire[i] * f[i]
ResidualPrediction(turn: t, speed: s, fire: clamp(fi, -1.0, 1.0))
proc observe*(h: var ResidualHead, f: array[NFeatures, float64],
target: ResidualTarget) =
## One ridge-SGD step per channel. `target` is the residual the mixture missed.
template sgd(w: untyped, b: untyped, tgt: float64) =
var p = b
for i in 0 ..< NFeatures: p += w[i] * f[i]
let err = tgt - p
for i in 0 ..< NFeatures:
w[i] += h.lr * (err * f[i] - h.l2 * w[i])
b += h.lr * err
sgd(h.wTurn, h.bTurn, target.turn)
sgd(h.wSpeed, h.bSpeed, target.speed)
sgd(h.wFire, h.bFire, target.fire)
inc h.samples
proc meanSquaredLoss*(h: ResidualHead, f: array[NFeatures, float64],
target: ResidualTarget): float64 =
## Squared residual error of the current head on one sample (diagnostics/tests).
let p = h.predict(f)
let dt = target.turn - p.turn
let ds = target.speed - p.speed
let df = target.fire - p.fire
(dt * dt + ds * ds + df * df) / 3.0
@@ -40,6 +40,8 @@ type
tick*: int
x*, y*: float64 ## mixture-predicted enemy position
pFire*: float64 ## mixture P(enemy fires this tick)
turnRate*: float64 ## mixture-predicted enemy turn rate (deg/tick)
targetSpeed*: float64 ## mixture-predicted enemy target speed (units/tick)
Rollout* = object
horizon*: int
@@ -202,6 +204,8 @@ proc rollout*(kernels: seq[Kernel], origin: ReplayTick, k: int,
var mx = 0.0
var myY2 = 0.0
var pf = 0.0
var mixTurn = 0.0
var mixSpeed = 0.0
for i in 0 ..< n:
let it = kernels[i].step(est[i], my, kernels[i].defaultParams, mems[i])
let ns = stepSpeed(est[i].speed, it.targetSpeed)
@@ -216,8 +220,11 @@ proc rollout*(kernels: seq[Kernel], origin: ReplayTick, k: int,
let w = if i < origin.weights.len: origin.weights[i] else: 0.0
mx += w * est[i].x
myY2 += w * est[i].y
mixTurn += w * it.turnRate
mixSpeed += w * it.targetSpeed
if it.fire > eps: pf += w
result.points.add RolloutPoint(tick: origin.tick + h, x: mx, y: myY2, pFire: pf)
result.points.add RolloutPoint(tick: origin.tick + h, x: mx, y: myY2, pFire: pf,
turnRate: mixTurn, targetSpeed: mixSpeed)
pNoFire *= (1.0 - min(1.0, pf))
for i in 0 ..< n: result.samples.add (est[i].x, est[i].y)
result.fireWithin = 1.0 - pNoFire
@@ -310,6 +310,12 @@ proc bulletLock(m: TfilModule, selfX, selfY: float): bool =
let dy = selfY - b.y
if dx * dx + dy * dy <= r2: return true
proc dodgeActive*(m: TfilModule, selfX, selfY: float): bool =
## Public read-only view of the bullet-avoidance reflex, for the CHIMERA
## influence overlay: while a tracked bullet is locked, TFIL is mid-dodge and
## the overlay must not touch the command (M6 spec §10).
m.bulletLock(selfX, selfY)
proc advanceBullets(m: var TfilModule, selfX, selfY: float) =
## Advance positions and reap bullets that passed us, left the arena, or are
## too old.
+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)