feat(affect): two-axis affect from the error stream (spec §5)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
This commit is contained in:
2 files changed
+121
No files matched your search
@@ -0,0 +1,56 @@
|
||||
"""Two-axis affect from the organism's own error stream. Spec §5.
|
||||
|
||||
Pure functions: state in, state out. No torch, no gradient by construction.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AffectConfig:
|
||||
rho_fast: float = 0.2 # fast error baseline rate
|
||||
rho_slow: float = 0.02 # slow error baseline rate, must be < rho_fast
|
||||
rho_a: float = 0.5 # arousal reactivity
|
||||
rho_v: float = 0.1 # valence reactivity
|
||||
reward_scale: float = 1.0 # s_r
|
||||
decay: float = 0.2 # between-episode decay toward neutral
|
||||
eps: float = 1e-6
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Affect:
|
||||
valence: float = 0.0 # v in [-1, 1]
|
||||
arousal: float = 0.0 # a in [0, 1]
|
||||
fast: float = 0.0 # L̄_fast
|
||||
slow: float = 0.0 # L̄_slow
|
||||
steps: int = 0
|
||||
|
||||
@property
|
||||
def axes(self) -> tuple[float, float]:
|
||||
"""(valence, arousal). Consumers read by name; this is the only positional export."""
|
||||
return (self.valence, self.arousal)
|
||||
|
||||
|
||||
def update(state: Affect, loss: float, cfg: AffectConfig, reward: float = 0.0) -> Affect:
|
||||
if state.steps == 0:
|
||||
fast = slow = loss # baselines initialise to the first loss: step one is not a surprise
|
||||
else:
|
||||
fast = state.fast + cfg.rho_fast * (loss - state.fast)
|
||||
slow = state.slow + cfg.rho_slow * (loss - state.slow)
|
||||
denom = slow + cfg.eps
|
||||
a_target = math.tanh(max(0.0, loss - slow) / denom)
|
||||
v_target = math.tanh((slow - fast) / denom + reward / cfg.reward_scale)
|
||||
return Affect(
|
||||
valence=state.valence + cfg.rho_v * (v_target - state.valence),
|
||||
arousal=state.arousal + cfg.rho_a * (a_target - state.arousal),
|
||||
fast=fast,
|
||||
slow=slow,
|
||||
steps=state.steps + 1,
|
||||
)
|
||||
|
||||
|
||||
def decay(state: Affect, cfg: AffectConfig) -> Affect:
|
||||
k = 1.0 - cfg.decay
|
||||
return replace(state, valence=state.valence * k, arousal=state.arousal * k)
|
||||
Reference in new issue
Block a user