Files
SirRoboGarage/ChimeraBot_garage/src/ChimeraBot/chimera/residual.nim
T

109 lines
4.4 KiB
Nim

## 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