ChimeraBot_garage: M6 — residual head, predictor fusion, fallback influence, G7 head-to-head
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user