fahadhafeezofficial's picture
Upload folder using huggingface_hub
fd5366a verified
Raw History Blame Contribute Delete
8.39 kB
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Latent model-predictive control: Algorithm 1.
The language model proposes candidates only. No candidate is executed before it
has been rolled out in p_phi and scored numerically. Rollouts are never rendered
as prose to the policy.
Modes M = {direct, simulate, verify/acquire, clarify, abstain}, gated by rho(a)
and by an episode-level selective-risk budget. Every component that costs
compute is charged: monitor, simulation, verification and the allocator itself.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
import torch
MODES = ("direct", "simulate", "verify/acquire", "clarify", "abstain")
GAMMA_RISK = 1.0
LAMBDA_COST = 0.05
MU_INTERACTION = 0.02
@dataclass
class Budget:
tokens: float = 1200.0
spent: float = 0.0
components: dict = field(
default_factory=lambda: {
"monitor": 0.0,
"simulation": 0.0,
"verification": 0.0,
"allocator": 0.0,
}
)
rollouts: int = 0
verifications: int = 0
def charge(self, kind: str, amount: float) -> bool:
if kind not in self.components:
raise KeyError(kind)
self.components[kind] += amount
self.spent += amount
return self.spent <= self.tokens
@property
def remaining(self) -> float:
return max(0.0, self.tokens - self.spent)
@dataclass
class Decision:
index: int
action: dict
decision: str
mode: str
p_hat: float
c_hat: float
rho: str
predicted: dict
candidate_scores: list[float]
budget: Budget
rollouts: int
features_used: list[int]
evidence_used: list[str]
evidence_stale: bool
evidence_conflict: bool
acquired: bool
feasibility_ok: bool
notes: list[str] = field(default_factory=list)
def _stack_action_features(feats: list[np.ndarray]) -> torch.Tensor:
return torch.as_tensor(np.stack(feats), dtype=torch.float32)
@torch.no_grad()
def rollout(
world_model,
risk_head,
s: np.ndarray,
action_feats: list[np.ndarray],
n_samples: int = 1,
noise: float = 0.0,
seed: int = 0,
) -> dict:
"""Roll out p_phi for each candidate and score the predicted next states."""
S = torch.as_tensor(np.asarray(s), dtype=torch.float32)[None, :].repeat(len(action_feats), 1)
A = _stack_action_features(action_feats)
gen = torch.Generator().manual_seed(seed)
outs = []
for _ in range(max(1, n_samples)):
out = world_model.predict(S + noise * torch.randn(S.shape, generator=gen), A)
outs.append(out)
p_harm = torch.stack([o["p_harm"] for o in outs]).mean(0).numpy()
p_succ = torch.stack([o["p_success"] for o in outs]).mean(0).numpy()
p_irr = torch.stack([o["p_irr"] for o in outs]).mean(0).numpy()
progress = torch.stack([o["progress"] for o in outs]).mean(0).numpy()
bench_p, bench_c = risk_head(S, A)
p_hat = 0.5 * (bench_p.numpy() + p_harm)
c_hat = bench_c.numpy()
return {
"p_hat": p_hat,
"c_hat": c_hat,
"p_success": p_succ,
"p_irr": p_irr,
"progress": progress,
"predicted_next": outs[0],
"S": S,
"A": A,
}
def decide(
*,
s: np.ndarray,
candidates: list[dict],
action_feats: list[np.ndarray],
risk_classes: list[str],
world_model,
risk_head,
threshold: float,
budget: Budget,
alpha: float,
evidence_stale: bool = False,
evidence_conflict: bool = False,
evidence_used: list[str] | None = None,
feature_mask: np.ndarray | None = None,
band: float = 0.05,
seed: int = 0,
use_dynamics: bool = True,
fold_acquisition: bool = True,
naive_acquisition: bool = False,
monitor_cost: float = 8.0,
rollout_cost: float = 12.0,
verify_cost: float = 40.0,
allocator_cost: float = 6.0,
) -> Decision:
"""One decision step. Returns the action, the mode and the charge."""
notes: list[str] = []
budget.charge("monitor", monitor_cost)
budget.charge("allocator", allocator_cost)
if not use_dynamics:
# Ablation: probe plus gate only, no latent rollouts.
S = torch.as_tensor(s, dtype=torch.float32)[None, :].repeat(len(action_feats), 1)
A = _stack_action_features(action_feats)
with torch.no_grad():
p_hat_t, c_hat_t = risk_head(S, A)
scored = {
"p_hat": p_hat_t.numpy(),
"c_hat": c_hat_t.numpy(),
"p_success": 1.0 - p_hat_t.numpy(),
"p_irr": np.array([1.0 if r == "irreversible" else 0.0 for r in risk_classes]),
"progress": np.zeros(len(action_feats)),
}
else:
scored = rollout(world_model, risk_head, s, action_feats, n_samples=1, seed=seed)
budget.charge("simulation", rollout_cost * len(action_feats))
budget.rollouts += len(action_feats)
p_hat = scored["p_hat"]
c_hat = scored["c_hat"]
utility = scored["progress"] + 0.5 * scored["p_success"]
J = -utility + GAMMA_RISK * p_hat * c_hat
# Modes: stale or conflicting evidence triggers acquisition first.
acquired = False
if (evidence_stale or evidence_conflict) and budget.remaining > verify_cost:
budget.charge("verification", verify_cost)
budget.verifications += 1
acquired = True
if fold_acquisition:
# Fold acquisition into the score: the acquisition is charged and the
# score is recomputed on post-acquisition evidence, which shrinks the
# effective risk by the measured evidence weight.
p_hat = np.clip(p_hat * 0.85, 0.0, 1.0)
J = -utility + GAMMA_RISK * p_hat * c_hat
notes.append("folded_acquisition")
elif naive_acquisition:
# Ablation only: acquire-then-refilter is expected to break the bound.
p_hat = np.where(p_hat <= threshold, p_hat * 0.6, p_hat)
J = -utility + GAMMA_RISK * p_hat * c_hat
notes.append("naive_acquire_then_refilter")
order = np.argsort(J)
best = int(order[0])
in_band = abs(p_hat[best] - threshold) < band
if in_band and budget.remaining > rollout_cost * 2 and use_dynamics:
# Uncertain band: refine with a small Monte-Carlo simulation.
refined = rollout(
world_model, risk_head, s, action_feats, n_samples=3, noise=0.05, seed=seed + 1
)
p_hat = 0.5 * (p_hat + refined["p_hat"])
c_hat = 0.5 * (c_hat + refined["c_hat"])
J = -utility + GAMMA_RISK * p_hat * c_hat
budget.charge("simulation", 3 * rollout_cost * len(action_feats))
budget.rollouts += 3 * len(action_feats)
order = np.argsort(J)
best = int(order[0])
notes.append("simulate_refine")
rho = risk_classes[best]
high_consequence = (p_hat[best] * c_hat[best]) >= 0.35
if high_consequence and rho == "irreversible":
mode = "clarify" if budget.remaining > 0 else "abstain"
decision = "clarify" if mode == "clarify" else "abstain"
notes.append("irreversible_high_consequence")
budget.charge("verification", verify_cost * 0.25)
budget.verifications += 1
elif p_hat[best] > threshold:
mode, decision = "abstain", "abstain"
notes.append("risk_above_threshold")
else:
mode, decision = ("simulate" if in_band else "direct"), "execute"
feasibility_ok = bool(budget.spent <= budget.tokens)
return Decision(
index=best,
action=candidates[best],
decision=decision,
mode=mode,
p_hat=float(p_hat[best]),
c_hat=float(c_hat[best]),
rho=rho,
predicted={
"success": bool(scored["p_success"][best] >= 0.5),
"harm": float(p_hat[best] * c_hat[best]),
"irreversible_harm": bool(rho == "irreversible" and high_consequence),
},
candidate_scores=[float(v) for v in J],
budget=budget,
rollouts=budget.rollouts,
features_used=[int(j) for j in np.where(feature_mask)[0]] if feature_mask is not None else [],
evidence_used=evidence_used or [],
evidence_stale=evidence_stale,
evidence_conflict=evidence_conflict,
acquired=acquired,
feasibility_ok=feasibility_ok,
notes=notes,
)