File size: 13,150 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""Controlled-arm input/target planning and deterministic answer rewards."""

from __future__ import annotations

import math
from collections.abc import Mapping
from dataclasses import dataclass, replace
from typing import Any, Literal

from .answers import NormalizationError, answers_equal, normalize_answer, parse_answer
from .slots import ComparisonSlot
from .targets import (
    answerable_only_target,
    defacto_target,
    no_recompute_target,
    ours_target,
    target_text,
)

Arm = Literal[
    "answer_grpo",
    "papo_controlled",
    "defacto_controlled",
    "intervention_grpo",
    "evi_po",
    # Ablation arms (ingredient-isolation suite; not part of the five method
    # arms, so they are excluded from ALL_ARMS. GPU admission is separately
    # defined by GPU_SMOKE_ARMS below).
    "evi_po_no_direction",
    "evi_po_no_evidence",
    "evi_po_margin_wide",
    "intervention_answerable_only",
    "intervention_no_recompute",
    "papo_relaxed_guard",
    "papo_mask_low",
    "papo_mask_high",
]
ALL_ARMS: tuple[Arm, ...] = (
    "answer_grpo",
    "papo_controlled",
    "defacto_controlled",
    "intervention_grpo",
    "evi_po",
)
# One real GPU smoke per trainer implementation. Answer-GRPO and DeFacto use
# the exact same aligned GRPO trainer as Intervention-GRPO; their different
# target functions are covered by CPU contracts and do not justify duplicate
# GPU jobs.
GPU_SMOKE_ARMS: tuple[Arm, ...] = (
    "intervention_grpo",
    "papo_controlled",
    "evi_po",
)
# Supported opt-in ingredient-isolation arms. D and J collapse to one run
# (intervention_no_recompute): "intervention
# minus recompute" is identical to "DeFacto plus certificate-derived abstention,
# no recompute" given the same selected_view input and GRPO trainer; F is a
# two-point mask sweep (0.3 / 0.9), which supplies the eighth slot.
ABLATION_ARMS: tuple[Arm, ...] = (
    "evi_po_no_direction",        # A: leave direction loss out
    "evi_po_no_evidence",         # B: leave evidence loss out
    "intervention_answerable_only",  # C: drop abstention (U_* -> full)
    "intervention_no_recompute",  # D = J: drop recompute (A_CHANGED -> maintain)
    "papo_relaxed_guard",         # E: perception weight > collapse_guard
    "papo_mask_low",              # F: mask_ratio = 0.3
    "papo_mask_high",             # F: mask_ratio = 0.9
    "evi_po_margin_wide",         # K: direction margin = 1.0
)

# Only these two causal ingredient removals are part of the automatic core
# queue.  The remaining exploratory sweeps stay supported by the planner but
# are not allowed to consume eight full main-run budgets before the core result
# is known.
CORE_ABLATION_ARMS: tuple[Arm, ...] = (
    "evi_po_no_direction",
    "evi_po_no_evidence",
)

# Numeric knobs for the ablation arms, as a single code-defined source of truth
# (version-controlled via code_commit, not a free YAML parameter). plan_arm reads
# it for ArmPlan metadata; the CLI runtime builder reads it to override the
# frozen evi_po_config / papo_config so the trainer sees the same values.
# Arms absent here (C, D) are pure target-function variants with no numeric knob.
ABLATION_ARM_KNOBS: dict[Arm, dict[str, float]] = {
    "evi_po_no_direction": {"lambda_direction": 0.0, "lambda_evidence": 0.1, "margin": 0.5},
    "evi_po_no_evidence": {"lambda_direction": 0.1, "lambda_evidence": 0.0, "margin": 0.5},
    "evi_po_margin_wide": {"lambda_direction": 0.1, "lambda_evidence": 0.1, "margin": 1.0},
    "papo_relaxed_guard": {"mask_ratio": 0.6, "perception_loss_weight": 0.05},
    "papo_mask_low": {"mask_ratio": 0.3, "perception_loss_weight": 0.02},
    "papo_mask_high": {"mask_ratio": 0.9, "perception_loss_weight": 0.02},
}
LEGACY_ARM_ALIASES: dict[str, Arm] = {"ours": "intervention_grpo"}


def canonical_arm(arm: str) -> Arm:
    """Map the pre-EVI public name to its unambiguous canonical ablation name."""

    value = LEGACY_ARM_ALIASES.get(arm, arm)
    if value in ALL_ARMS or value in ABLATION_ARMS:
        return value
    raise ValueError(f"unknown arm: {arm!r}")


def arm_trainer_kind(arm: Arm | str) -> Literal["papo", "evi_po", "grpo"]:
    """Map an RL arm to its trainer kind: ``"papo"``, ``"evi_po"``, or ``"grpo"``.

    Single source of truth shared by the matrix planner (which selects the
    trainer) and the runtime-config guard (which checks the arm/trainer pair).
    """

    arm = canonical_arm(arm)
    if arm in {"papo_controlled", "papo_relaxed_guard", "papo_mask_low", "papo_mask_high"}:
        return "papo"
    if arm in {"evi_po", "evi_po_no_direction", "evi_po_no_evidence", "evi_po_margin_wide"}:
        return "evi_po"
    return "grpo"


def smoke_reference_arm(arm: Arm | str) -> Arm:
    """Return the tested parent implementation for a main or ablation arm."""

    canonical = canonical_arm(arm)
    if canonical in {"evi_po_no_direction", "evi_po_no_evidence", "evi_po_margin_wide"}:
        return "evi_po"
    if canonical in {"papo_relaxed_guard", "papo_mask_low", "papo_mask_high"}:
        return "papo_controlled"
    if canonical in {"intervention_answerable_only", "intervention_no_recompute"}:
        return "intervention_grpo"
    if canonical in {"answer_grpo", "defacto_controlled"}:
        return "intervention_grpo"
    return canonical


@dataclass(frozen=True)
class RewardWeights:
    answer: float = 1.0
    format: float = 0.0
    invalid_format_penalty: float = -1.0

    def __post_init__(self) -> None:
        if not all(math.isfinite(value) for value in (self.answer, self.format)):
            raise ValueError("reward weights must be finite")
        if not math.isfinite(self.invalid_format_penalty):
            raise ValueError("invalid-format penalty must be finite")
        if self.answer < 0 or self.format < 0:
            raise ValueError("answer and format weights must be non-negative")
        if self.invalid_format_penalty > 0:
            raise ValueError("invalid-format penalty must be non-positive")


@dataclass(frozen=True)
class ArmPlan:
    arm: Arm
    slot_id: str
    group_id: str
    base_id: str
    comparison_role: str
    input_view_id: str
    input_state: str
    gold_target: str
    answer_type: str
    choices: tuple[dict[str, Any], ...]
    visual_mask_ratio: float | None = None
    perception_coefficient: float | None = None
    reference_kl_coefficient: float | None = None
    use_aug_entropy_loss: bool = False
    use_ori_entropy_loss: bool = False


@dataclass(frozen=True)
class RewardTrace:
    arm: Arm
    slot_id: str
    parser_valid: bool
    parser_error: str | None
    parsed_answer: str | None
    normalized_prediction: str | None
    normalized_gold: str
    answer_component: float
    format_component: float
    total_reward: float
    normalizer_branch: str


def _full_plan(slot: ComparisonSlot, arm: Arm) -> ArmPlan:
    return ArmPlan(
        arm=arm,
        slot_id=slot.slot_id,
        group_id=slot.group_id,
        base_id=slot.base_id,
        comparison_role=slot.comparison_role,
        input_view_id=str(slot.full_view["view_id"]),
        input_state="FULL",
        gold_target=target_text(slot.full_answer),
        answer_type=slot.answer_type,
        choices=slot.choices,
    )


def plan_arm(slot: ComparisonSlot, arm: Arm | str) -> ArmPlan:
    """Plan the observed view and gold target for one controlled arm."""

    arm = canonical_arm(arm)
    if arm == "answer_grpo":
        return _full_plan(slot, arm)
    if arm == "papo_controlled":
        plan = _full_plan(slot, arm)
        return replace(
            plan,
            visual_mask_ratio=0.6,
            perception_coefficient=0.02,
            reference_kl_coefficient=0.01,
            use_aug_entropy_loss=False,
            use_ori_entropy_loss=False,
        )
    if arm in {"papo_relaxed_guard", "papo_mask_low", "papo_mask_high"}:
        knobs = ABLATION_ARM_KNOBS[arm]
        plan = _full_plan(slot, arm)
        return replace(
            plan,
            visual_mask_ratio=knobs["mask_ratio"],
            perception_coefficient=knobs["perception_loss_weight"],
            reference_kl_coefficient=0.01,
            use_aug_entropy_loss=False,
            use_ori_entropy_loss=False,
        )
    if arm == "defacto_controlled":
        target = defacto_target(slot.comparison_role, slot.full_answer)
    elif arm in {"intervention_grpo", "evi_po"} or arm in {
        "evi_po_no_direction",
        "evi_po_no_evidence",
        "evi_po_margin_wide",
    }:
        target = ours_target(slot.selected_view, slot.full_answer)
    elif arm == "intervention_answerable_only":
        target = answerable_only_target(slot.selected_view, slot.full_answer)
    elif arm == "intervention_no_recompute":
        target = no_recompute_target(slot.selected_view, slot.full_answer)
    return ArmPlan(
        arm=arm,
        slot_id=slot.slot_id,
        group_id=slot.group_id,
        base_id=slot.base_id,
        comparison_role=slot.comparison_role,
        input_view_id=str(slot.selected_view["view_id"]),
        input_state=str(slot.selected_view["state"]),
        gold_target=target,
        answer_type=slot.answer_type,
        choices=slot.choices,
    )


def plan_all_arms(slot: ComparisonSlot) -> tuple[ArmPlan, ...]:
    plans = tuple(plan_arm(slot, arm) for arm in ALL_ARMS)
    if {plan.slot_id for plan in plans} != {slot.slot_id}:
        raise AssertionError("controlled-arm planning drifted from the common slot")
    return plans


# Compatibility name for callers written before EVI-PO added a fifth arm.  It
# intentionally returns the current complete arm tuple.
plan_four_arms = plan_all_arms


def score_completion(
    plan: ArmPlan,
    completion: str,
    *,
    weights: RewardWeights | None = None,
) -> RewardTrace:
    """Score one completion; parser exceptions never become silent zeroes."""

    weights = weights or RewardWeights()
    parsed = parse_answer(completion)
    try:
        normalized_gold = normalize_answer(
            plan.gold_target,
            plan.answer_type,
            choices=plan.choices,
        )
    except NormalizationError as exc:
        raise ValueError(f"invalid gold target for slot {plan.slot_id}: {exc}") from exc

    if not parsed.valid:
        return RewardTrace(
            arm=plan.arm,
            slot_id=plan.slot_id,
            parser_valid=False,
            parser_error=parsed.error,
            parsed_answer=None,
            normalized_prediction=None,
            normalized_gold=normalized_gold,
            answer_component=0.0,
            format_component=0.0,
            total_reward=weights.invalid_format_penalty,
            normalizer_branch="parser_reject",
        )

    content = parsed.require_content()
    try:
        normalized_prediction = normalize_answer(
            content,
            plan.answer_type,
            choices=plan.choices,
        )
        normalizer_branch = plan.answer_type
    except NormalizationError:
        normalized_prediction = None
        normalizer_branch = f"{plan.answer_type}_invalid"
    correct = answers_equal(
        content,
        plan.gold_target,
        plan.answer_type,
        choices=plan.choices,
    )
    answer_component = 1.0 if correct else 0.0
    format_component = 1.0
    total = weights.answer * answer_component + weights.format * format_component
    if not math.isfinite(total):
        raise ValueError("non-finite reward")
    return RewardTrace(
        arm=plan.arm,
        slot_id=plan.slot_id,
        parser_valid=True,
        parser_error=None,
        parsed_answer=content,
        normalized_prediction=normalized_prediction,
        normalized_gold=normalized_gold,
        answer_component=answer_component,
        format_component=format_component,
        total_reward=total,
        normalizer_branch=normalizer_branch,
    )


def plans_share_fairness_key(plans: Mapping[Arm, ArmPlan]) -> bool:
    """Check the immutable schedule fields and method-specific input pairing."""

    if set(plans) != set(ALL_ARMS):
        return False
    if any(plan.arm != arm for arm, plan in plans.items()):
        return False
    values = tuple(plans.values())
    common_identities = {
        (
            plan.slot_id,
            plan.group_id,
            plan.base_id,
            plan.comparison_role,
            plan.answer_type,
        )
        for plan in values
    }
    if len(common_identities) != 1:
        return False
    if any(plan.choices != values[0].choices for plan in values[1:]):
        return False
    answer = plans["answer_grpo"]
    papo = plans["papo_controlled"]
    defacto = plans["defacto_controlled"]
    intervention = plans["intervention_grpo"]
    evi_po = plans["evi_po"]
    return (
        answer.input_view_id == papo.input_view_id
        and answer.input_state == papo.input_state == "FULL"
        and answer.gold_target == papo.gold_target
        and defacto.input_view_id == intervention.input_view_id == evi_po.input_view_id
        and defacto.input_state == intervention.input_state == evi_po.input_state
        and intervention.gold_target == evi_po.gold_target
    )