File size: 8,386 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# 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,
    )