"""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 )