From b49647999d083a4597ecfe2cd211c7759f583d8e Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:04:42 -0700 Subject: [PATCH 01/26] add subrx --- CHANGELOG.md | 32 ++ docs/agentic_benchmark.md | 14 + evalrx/analyzers/_internals/attn_tap.py | 19 +- evalrx/analyzers/_internals/edits.py | 13 +- .../perturbation/modality_ablation.py | 96 ++++- evalrx/benchmark/run.py | 18 + evalrx/benchmark/runner.py | 55 ++- evalrx/eval_agent/probing/__init__.py | 40 ++ evalrx/eval_agent/probing/actions.py | 133 +++++++ evalrx/eval_agent/probing/controller.py | 284 ++++++++++++++ evalrx/eval_agent/probing/executor.py | 118 ++++++ evalrx/eval_agent/probing/ledger.py | 89 +++++ evalrx/eval_agent/probing/metering.py | 73 ++++ evalrx/eval_agent/probing/partition.py | 28 ++ evalrx/eval_agent/probing/sampler.py | 110 ++++++ evalrx/eval_agent/probing/triage.py | 275 ++++++++++++++ .../test_modality_ablation_swap.py | 112 ++++++ tests/test_eval_agent/test_probing_mvp0.py | 348 ++++++++++++++++++ 18 files changed, 1837 insertions(+), 20 deletions(-) create mode 100644 evalrx/eval_agent/probing/__init__.py create mode 100644 evalrx/eval_agent/probing/actions.py create mode 100644 evalrx/eval_agent/probing/controller.py create mode 100644 evalrx/eval_agent/probing/executor.py create mode 100644 evalrx/eval_agent/probing/ledger.py create mode 100644 evalrx/eval_agent/probing/metering.py create mode 100644 evalrx/eval_agent/probing/partition.py create mode 100644 evalrx/eval_agent/probing/sampler.py create mode 100644 evalrx/eval_agent/probing/triage.py create mode 100644 tests/test_analyzers/test_modality_ablation_swap.py create mode 100644 tests/test_eval_agent/test_probing_mvp0.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e2ce567b..d961b887 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,38 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — triage probing controller, MVP-0 (`--m1-policy triage_active`) + +An opt-in alternative to the judge-selected M1 (`evalrx/eval_agent/probing/`). +After Stage 0 and the usual EXPLORE/CONFIRM split, a host-side controller runs +a fixed plan — `answer_extraction_audit`, `termination_audit` (no +continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")` +— on a matched, nested FAIL/PASS sample of EXPLORE, exactly as planned (no +backfill, cap or generated probes), and writes `selection_trace.jsonl`, +`cost_ledger.jsonl`, per-action observations and a triage report (H/N/X route +labels traced to case, field, action and fidelity verdict) under +`/probing/`. Outcomes are typed (`ok` / `unsupported` / `failed` / +`unfaithful`) and never written as zeros; a rerun reads finished actions back +instead of re-running them. No judge is called and M2–M5 do not run. The +default `--m1-policy judge` path is unchanged. + +### Fixed — `modality_ablation(mode="swap")` could swap in the same media + +The donor was the first other case filling the slot, compared by case id only: +on POPE (two questions per image, adjacent rows) the first pair swapped the +same image back in, and every other case shared one donor. Donors are now the +next case in batch order whose media differs in content (file bytes or +pixels), each row records `ablation__donor` and the compared answers, and +`n_drop_fallback_` counts cases that had to fall back to drop. `drop` +mode output is unchanged. + +### Changed — fidelity refusals raise `FidelityError` + +`require_fidelity` and `require_edit_fidelity` raise +`evalrx.analyzers._internals.attn_tap.FidelityError` (a `RuntimeError` +subclass carrying the check's `verdict`), so callers can tell an untrustworthy +edit from an ordinary failure without parsing the message. + ### Fixed — hybrid analyzer compatibility with Transformers 5 Recognize Qwen3.5 / Qwen3-Next linear-attention mixers when Transformers calls diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 6e9d040a..a4b785f0 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -19,6 +19,20 @@ Repair and surgery are excluded from the benchmark controller's tool registry. A Agentic repair does not inject built-in floor candidates. The agent can still propose known repair methods. The existing repair tier/capability constraints and maximum repair rounds remain enforced. This mode is bounded adaptive diagnosis, not an unlimited autonomous training loop. +## Triage policy (opt-in, MVP-0) + +`--m1-policy triage_active` replaces the diagnosis with a host-side triage controller (`evalrx/eval_agent/probing/`, design in `evalsmith/probing/probing_design_mix.md`). The default `--m1-policy judge` is unchanged. + +```bash +python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend hf_local \ + --dataset pope_adversarial --limit 200 --attn-impl eager \ + --m1-policy triage_active --run-tag triage0 +``` + +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed plan exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")` — with no backfill, case cap or generated probes. No judge is called, M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl`, `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json`, `split_manifest.json`, and `triage_report.{json,md}` with H/N/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips later actions once the wall-clock budget is spent. + +White-box edits refuse when their edit-free self-check fails. On Qwen3.5-0.8B in bf16, the attention tap reproduces `--attn-impl eager` exactly but differs from `sdpa` by about 1–2% of the largest logit, above the 1% tolerance, so `attention_knockout` reports `unfaithful` under `sdpa`; use `--attn-impl eager` for edit-based analyzers. + ## Failure and progress semantics M3 exceptions are recorded as structured error exchanges with exception type, message, attempt, and retry status. The runtime automatically permits one additional attempt; valid empty diagnoses are not retried as transport failures. Exhaustion produces `diagnosis_error`, an error diagnosis status, and benchmark exit code 2 rather than a successful `no_hypotheses` result. diff --git a/evalrx/analyzers/_internals/attn_tap.py b/evalrx/analyzers/_internals/attn_tap.py index 1320fdc7..183cd020 100644 --- a/evalrx/analyzers/_internals/attn_tap.py +++ b/evalrx/analyzers/_internals/attn_tap.py @@ -353,16 +353,31 @@ def check_fidelity(model: "Model", inputs: Any, *, rtol: float = 1e-2, return dict(verdict) +class FidelityError(RuntimeError): + """An edit mechanism failed its edit-free self-check on this model. + + A ``RuntimeError`` so every existing ``except RuntimeError`` still catches + it; the subclass lets a caller tell "the measurement cannot be trusted" + apart from an ordinary crash without parsing the message. ``verdict`` is + the check's own record (engaged layers, logit diff, tolerance). + """ + + def __init__(self, message: str, verdict: "dict[str, Any]") -> None: + super().__init__(message) + self.verdict = dict(verdict) + + def require_fidelity(model: "Model", inputs: Any, *, rtol: float = 1e-2, analyzer: str = "attention tap") -> "dict[str, Any]": """:func:`check_fidelity`, raising when the tap cannot be trusted on *model*.""" verdict = check_fidelity(model, inputs, rtol=rtol, analyzer=analyzer) if not verdict["tap_faithful"]: - raise RuntimeError( + raise FidelityError( f"{analyzer}: the evalrx attention tap does not faithfully reproduce this " f"model's attention ({verdict}); refusing to report edited-attention effects. " "Engaged < expected layers means the architecture bypasses the transformers " - "attention interface; a large logit diff means its attention is not eager-equivalent." + "attention interface; a large logit diff means its attention is not eager-equivalent.", + verdict, ) return verdict diff --git a/evalrx/analyzers/_internals/edits.py b/evalrx/analyzers/_internals/edits.py index 9bfab094..9dd46102 100644 --- a/evalrx/analyzers/_internals/edits.py +++ b/evalrx/analyzers/_internals/edits.py @@ -19,7 +19,13 @@ from typing import TYPE_CHECKING, Any, Iterable, Iterator from evalrx.analyzers._internals.access import decoder_stack, torch_module -from evalrx.analyzers._internals.attn_tap import attention_tap, check_fidelity, knockout, reweight +from evalrx.analyzers._internals.attn_tap import ( + FidelityError, + attention_tap, + check_fidelity, + knockout, + reweight, +) from evalrx.analyzers._internals.linear_mix import check_linear_fidelity, linear_media_edit if TYPE_CHECKING: @@ -69,11 +75,12 @@ def require_edit_fidelity(model: "Model", inputs: Any, media: Iterable[int], *, verdict.update(check_linear_fidelity(model, inputs, media, rtol=rtol, analyzer=analyzer)) verdict["faithful"] = bool(verdict.get("tap_faithful", True) and verdict.get("linear_faithful", True)) if not verdict["faithful"]: - raise RuntimeError( + raise FidelityError( f"{analyzer}: the attention edits cannot be trusted on this model ({verdict}). " "tap: engaged < expected layers means the architecture bypasses the transformers " "attention interface, a logit diff means its attention is not eager-equivalent; " "linear: the media-absent re-run must engage every linear layer and reproduce " - "the outputs before the first media token." + "the outputs before the first media token.", + verdict, ) return verdict diff --git a/evalrx/analyzers/perturbation/modality_ablation.py b/evalrx/analyzers/perturbation/modality_ablation.py index 508680fd..f7d37f7c 100644 --- a/evalrx/analyzers/perturbation/modality_ablation.py +++ b/evalrx/analyzers/perturbation/modality_ablation.py @@ -20,7 +20,9 @@ not correct use: the input shape changed too. * ``swap`` — substitute another case's media, keeping the input shape intact and breaking only the grounding. Cleaner evidence, and it needs no extra model - capability, but it requires at least two cases filling the same slot. + capability, but it requires at least two cases filling the same slot with + DIFFERENT media: the donor is matched on content, not on case id, and every + row records which case it came from. Reported as reliance, never as correctness. ``ungrounded_rate_`` is the share of probed cases whose answer survived the ablation; ``by_strategy`` carries @@ -31,6 +33,8 @@ from __future__ import annotations import dataclasses +import hashlib +import os from typing import TYPE_CHECKING, Any, Callable, Optional from evalrx.analyzers.perturbation.prompt_contrast import _default_score, _norm_answer @@ -47,6 +51,33 @@ BASELINE = "baseline" +def _media_key(media: Any) -> Any: + """Content identity of one media value, so a swap never substitutes the same media. + + Files hash their bytes (two rows may name the same file, or copies of it), + in-memory images/arrays hash their pixels; a URL or unreadable path is its + own reference; anything else falls back to its repr. + """ + if isinstance(media, (str, os.PathLike)): + path = os.fspath(media) + try: + with open(path, "rb") as fh: + return ("file", hashlib.sha1(fh.read()).hexdigest()) + except OSError: + return ("ref", path) + if isinstance(media, (bytes, bytearray)): + return ("bytes", hashlib.sha1(bytes(media)).hexdigest()) + tobytes = getattr(media, "tobytes", None) + if callable(tobytes): + try: + shape = getattr(media, "shape", None) or getattr(media, "size", None) + return ("pixels", type(media).__name__, getattr(media, "mode", None), str(shape), + hashlib.sha1(tobytes()).hexdigest()) + except Exception: # noqa: BLE001 - an unhashable buffer falls through to repr + pass + return ("repr", repr(media)) + + @register_analyzer("modality_ablation") class ModalityAblationAnalyzer(Analyzer): """Per-slot grounding probe: does ablating a modality move the answer?""" @@ -59,11 +90,18 @@ class ModalityAblationAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image", "audio", "video"}) signal_docs = { + 'ablation_base_answer': 'Swap mode: the unablated answer the ablated ones are compared against.', + 'ablation_audio_answer': 'Swap mode: the answer with the audio swapped (or dropped).', + 'ablation_image_answer': 'Swap mode: the answer with the image swapped (or dropped).', + 'ablation_video_answer': 'Swap mode: the answer with the video swapped (or dropped).', + 'ablation_audio_donor': "Swap mode: the case whose audio was put in (None = no different audio, so it was dropped).", 'ablation_audio_is_swap': "The audio was replaced with another case's rather than removed.", + 'ablation_image_donor': "Swap mode: the case whose image was put in (None = no different image, so it was dropped).", 'ablation_image_is_swap': "The image was replaced with another case's rather than removed.", 'ablation_mode_audio': 'How the audio was removed for these cases.', 'ablation_mode_image': 'How the image was removed for these cases.', 'ablation_mode_video': 'How the video was removed for these cases.', + 'ablation_video_donor': "Swap mode: the case whose video was put in (None = no different video, so it was dropped).", 'ablation_video_is_swap': "The video was replaced with another case's rather than removed.", 'grounded_in_audio': ('Actually listened', 'The answer changed when the audio was taken away — the model was listening.'), 'grounded_in_image': ('Actually looked', 'The answer changed when the image was taken away — the model was using it.'), @@ -73,6 +111,9 @@ class ModalityAblationAnalyzer(Analyzer): 'n_probed_audio': 'How many cases had audio to test.', 'n_probed_image': 'How many cases had an image to test.', 'n_probed_video': 'How many cases had video to test.', + 'n_drop_fallback_audio': 'Swap mode: cases whose audio was dropped because no case held different audio.', + 'n_drop_fallback_image': 'Swap mode: cases whose image was dropped because no case held a different image.', + 'n_drop_fallback_video': 'Swap mode: cases whose video was dropped because no case held different video.', 'probed_slots': 'Which modalities were tested this way.', 'ungrounded_rate_audio': ('Ignored the audio', 'Share of cases whose answer did NOT change when the audio was removed — the model was not listening.'), 'ungrounded_rate_image': ('Ignored the image', 'Share of cases whose answer did NOT change when the image was removed — the model was not looking.'), @@ -114,16 +155,25 @@ def _slots_of(self, case: "FailureCase") -> "list[str]": ] @staticmethod - def _donor(cases: "list[FailureCase]", slot: str, case: "FailureCase") -> Any: - """Another case's media for *slot*, or ``None`` when there is no donor. + def _donor(cases: "list[FailureCase]", slot: str, case: "FailureCase", + key_of: "Callable[[Any], Any]") -> "tuple[str, Any] | None": + """``(donor id, media)`` for *slot*, or ``None`` when no case holds different media. - Deterministic (first non-self filler in batch order) so a rerun of the - same batch ablates with the same substitute — a random donor would make - the paired comparison irreproducible. + The next case in batch order (wrapping) whose media differs in CONTENT + from this case's own. Deterministic, so a rerun of the same batch swaps + with the same donors — a random donor would make the paired comparison + irreproducible — and spread over the batch instead of one shared donor. + Comparing case ids is not enough: two rows can carry the same file + (POPE asks two questions per COCO image, adjacent in the manifest), and + "swapping" the same image back in reads as a model that ignores it. """ - for other in cases: - if other.id != case.id and getattr(other.inputs, slot, None) is not None: - return getattr(other.inputs, slot) + own = key_of(getattr(case.inputs, slot)) + start = next(i for i, c in enumerate(cases) if c is case) + for step in range(1, len(cases)): + other = cases[(start + step) % len(cases)] + media = getattr(other.inputs, slot, None) + if media is not None and other.id != case.id and key_of(media) != own: + return str(other.id), media return None def _run(self, model: "Model", cases: "CaseBatch") -> Result: @@ -136,7 +186,14 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: # per-slot tallies: probed cases, and those whose answer never moved probed = {s: 0 for s in MEDIA_SLOTS} ungrounded = {s: 0 for s in MEDIA_SLOTS} - modes_used: dict[str, str] = {} + modes_used: dict[str, set[str]] = {} + swap = self.mode == "swap" + media_keys: dict[int, Any] = {} + + def key_of(media: Any) -> Any: # hash each media value once per run + if id(media) not in media_keys: + media_keys[id(media)] = _media_key(media) + return media_keys[id(media)] for case in selected: base_answer = str(model.generate(case.inputs)) @@ -146,13 +203,16 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: by_strategy[BASELINE][case.id] = float(bool(base_verdict)) row: dict[str, Any] = {"sample_id": case.id} + if swap: + row["ablation_base_answer"] = base_answer[:120] for slot in self._slots_of(case): - donor = self._donor(selected, slot, case) if self.mode == "swap" else None + found = self._donor(selected, slot, case, key_of) if swap else None + donor = found[1] if found else None # swap with no donor degrades to drop rather than skipping: the # weaker evidence is still evidence, and silently probing nothing # would look identical to a fully-grounded model. effective = "swap" if donor is not None else "drop" - modes_used[slot] = effective + modes_used.setdefault(slot, set()).add(effective) ablated = dataclasses.replace(case.inputs, **{slot: donor}) answer = str(model.generate(ablated)) @@ -165,6 +225,9 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: # nested {slot: {...}} here would reach no statistic at all. row[f"grounded_in_{slot}"] = bool(changed) row[f"ablation_{slot}_is_swap"] = effective == "swap" + if swap: + row[f"ablation_{slot}_donor"] = found[0] if found else None + row[f"ablation_{slot}_answer"] = answer[:120] strategy = f"without_{slot}" verdict = score(case, answer) @@ -188,7 +251,14 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: # cannot separate them will report the wrong one. findings[f"n_probed_{slot}"] = n findings[f"ungrounded_rate_{slot}"] = round(ungrounded[slot] / n, 4) if n else None - findings[f"ablation_mode_{slot}"] = modes_used.get(slot) + used = modes_used.get(slot, set()) + findings[f"ablation_mode_{slot}"] = ( + None if not used else next(iter(used)) if len(used) == 1 else "mixed" + ) + if swap: + findings[f"n_drop_fallback_{slot}"] = sum( + 1 for r in per_case if r.get(f"ablation_{slot}_is_swap") is False + ) return Result( analyzer=self.name, model=repr(model), cases=cases, findings=findings, diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 8051e0fc..222af536 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -144,6 +144,19 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP p.add_argument("--m1-selection", choices=["pinned", "judge"], default="pinned", help="pinned = the task's static analyzer set; judge = catalog selection " "(modality-gated on the MODEL, so avoid on multimodal specs for text tasks)") + p.add_argument("--m1-policy", choices=["judge", "triage_active"], default="judge", + help="judge = the current diagnosis (decision judge over M1-M4, then M5/fix); " + "triage_active = MVP-0 triage controller: after Stage 0, run the fixed " + "triage plan strictly on a matched EXPLORE sample, write the trace, cost " + "ledger and triage report under /probing/, and stop (no judge, no " + "M2-M5, CONFIRM untouched)") + p.add_argument("--triage-n-fail", type=int, default=8, + help="triage_active: FAIL cases in the sample (PASS controls are matched per gold answer)") + p.add_argument("--triage-seed", type=int, default=0, + help="triage_active: rank seed of the nested sampler") + p.add_argument("--triage-budget-sec", type=float, default=0.0, + help="triage_active: wall-clock cap on executed actions (0 = none); a running " + "action is not interrupted, later ones are skipped") p.add_argument("--analyzer-max-cases", type=int, default=0, help="cap per analyzer (0 = every case)") p.add_argument("--m2-codegen", action=argparse.BooleanOptionalAction, default=None, help="coder-written M2 statistics tools (default: on)") @@ -211,6 +224,11 @@ def run_args(args) -> int: raise ValueError("max-actions must be positive") if args.diagnosis_mode == "agentic" and args.held_out: raise ValueError("agentic diagnosis uses EXPLORE; --held-out is supported only in fixed mode") + triage = getattr(args, "m1_policy", "judge") == "triage_active" + if triage and args.held_out: + raise ValueError("--m1-policy triage_active works on EXPLORE only; it has no --held-out role yet") + if triage and args.triage_n_fail < 1: + raise ValueError("--triage-n-fail must be positive") dataset = args.dataset or T.DEFAULT_TASK[args.modality] task = T.get(dataset) if task.modality != args.modality: diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 0daff89f..a69773be 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -22,6 +22,10 @@ from . import tasks as T from .models import Resolved +#: Seed of the label-stratified EXPLORE/CONFIRM split, shared by the diagnosis +#: loop and the triage controller so both see the same EXPLORE cases. +CONFIRM_SPLIT_SEED = 20260818 + def model_label(resolved: Resolved) -> str: from evalrx.specs import get_spec @@ -342,6 +346,50 @@ def run_fix_isolated(loop, run_dir: Path, ctx, report, cases, **fix_kwargs): return loop.run_fix(report, cases, **fix_kwargs) +def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, + cases, ctx, run_dir: Path, baseline: dict) -> int: + """``--m1-policy triage_active`` (MVP-0): the fixed triage plan on EXPLORE, then stop. + + Same Stage 0 and the same EXPLORE/CONFIRM split as the diagnosis loop; the + controller sees EXPLORE only, calls no judge, and runs no M2-M5. Outputs + go to ``/probing/``. + """ + from evalrx.eval_agent.probing import explore_confirm_split, run_triage_mvp0 + + explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED) + runtime = getattr(model, "runtime", None) + identity = { + "spec": spec.key, "weights": spec.hf_repo, "backend": resolved.backend, + "dtype": getattr(runtime, "dtype", args.dtype), "attn_impl": getattr(runtime, "attn_impl", None), + "generation": gen_kwargs, "enable_thinking": bool(args.enable_thinking), + } + ctx.config.update(m1_policy="triage_active", judge_provider=None, judge_model=None) # none was built + report = run_triage_mvp0( + model, explore, out_dir=run_dir / "probing", model_identity=identity, + n_fail=args.triage_n_fail, seed=args.triage_seed, + stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", + host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), + analyzer_kwargs={"modality_ablation": {"score_fn": T.score_case}}, + budget_sec=float(args.triage_budget_sec), + stage0_cost={"wall_sec": baseline["seconds"], "calls": {"generate": baseline["n"]}, + "n_cases": baseline["n"]}, + partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, + "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, + "confirm_visible_to_controller": False}, + run_logger=ctx.logger, + ) + ctx.finalize() + summary = { + "model": args.model, "spec": spec.key, "dataset": task.name, "modality": task.modality, + "backend": resolved.backend, "n_cases": len(cases), "baseline_accuracy": baseline["accuracy"], + "m1_policy": "triage_active", "triage": report["summary"], + "triage_steps": [{k: s.get(k) for k in ("analyzer", "status", "reused")} for s in report["steps"]], + } + (run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n", encoding="utf-8") + print(f"Done (triage). {run_dir / 'probing' / 'triage_report.md'}") + return 0 + + def run(args, task: T.Task, resolved: Resolved) -> int: manifest = ensure_manifest(task, args) # Fail fast: the held-out validation manifest must exist before any model @@ -356,8 +404,9 @@ def run(args, task: T.Task, resolved: Resolved) -> int: label = model_label(resolved) print(f"[model] {label}; backend={resolved.backend}; benchmark={task.title}; n={len(candidates)}") + triage = getattr(args, "m1_policy", "judge") == "triage_active" judge = coder_provider = coder_model = coder_extra = None - if not args.baseline_only: + if not args.baseline_only and not triage: # MVP-0 triage calls no judge judge, coder_provider, coder_model, coder_extra = build_judge(args) model, gen_kwargs, spec = load_model(resolved, args, task) @@ -485,6 +534,8 @@ def run(args, task: T.Task, resolved: Resolved) -> int: return 0 if not discovery.has_m4_groups: raise SystemExit("M4 needs both PASS and FAIL cases; adjust --limit / --seed") + if triage: + return _run_triage(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline) # Held-out validation set (--held-out): a SEPARATE frozen sample, labeled # by its own Stage-0 pass. It takes the M4-holdout + fix-development roles; @@ -646,7 +697,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: diagnosis_agent=DiagnosisAgent(judge=judge), hypothesis_tester=HypothesisTester(judge=judge, min_effect=0.05), fix_agent=fix_agent, max_cycles=args.max_cycles, run_logger=ctx.logger, - confirm_split=float(args.confirm_split), confirm_split_seed=20260818, + confirm_split=float(args.confirm_split), confirm_split_seed=CONFIRM_SPLIT_SEED, # Default: the 50/50 explore/confirm design — M1-M4 work on EXPLORE # (M4 in-cycle), the fix ladder searches on EXPLORE, and CONFIRM is # reserved for the single frozen-winner validation. diff --git a/evalrx/eval_agent/probing/__init__.py b/evalrx/eval_agent/probing/__init__.py new file mode 100644 index 00000000..4a285b98 --- /dev/null +++ b/evalrx/eval_agent/probing/__init__.py @@ -0,0 +1,40 @@ +"""Triage-first probing controller (``--m1-policy triage_active``). + +The default M1 lets the decision judge pick a batch of analyzers, which +``ProbeAgent`` may then backfill, cap, or extend with generated probes. This +package is the opt-in alternative from ``evalsmith/probing/probing_design_mix.md``: +a host-side controller that runs one explicit action at a time, on exactly the +cases and configuration it planned, and records why each action ran, what it +cost, and whether its measurement can be trusted. + +MVP-0 is a fixed plan with no judge and no M2-M5: + + partition.py the same EXPLORE/CONFIRM split the diagnosis loop uses + sampler.py matched, nested FAIL/PASS sample (S8 ⊆ S16 ⊆ S32 ...) + actions.py ProbeAction / Observation and their content identities + metering.py per-action call counts, model seconds, GPU peak memory + executor.py strict execution: capability gate, typed outcome, no backfill + ledger.py append-only selection_trace.jsonl / cost_ledger.jsonl + resume + triage.py H/N/X route labels traced back to case, field and action + controller.py the MVP-0 plan and run_triage_mvp0() + +Nothing here is imported by the default ``judge`` path. +""" + +from __future__ import annotations + +from evalrx.eval_agent.probing.actions import Observation, ProbeAction +from evalrx.eval_agent.probing.controller import MVP0_PLAN, POLICY_VERSION, run_triage_mvp0 +from evalrx.eval_agent.probing.partition import explore_confirm_split +from evalrx.eval_agent.probing.sampler import SampleDraw, matched_sample + +__all__ = [ + "MVP0_PLAN", + "POLICY_VERSION", + "Observation", + "ProbeAction", + "SampleDraw", + "explore_confirm_split", + "matched_sample", + "run_triage_mvp0", +] diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/probing/actions.py new file mode 100644 index 00000000..dbdd522e --- /dev/null +++ b/evalrx/eval_agent/probing/actions.py @@ -0,0 +1,133 @@ +"""What one probing action is, what came back, and the identity tying them together. + +An action is ``(analyzer, configuration, cases, purpose)``. Its identity is a +content hash over the analyzer, its full configuration, the ordered case ids +and the execution context (model, policy version), so a resumed run recognises +a finished action and a changed configuration never reuses an old result. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import asdict, dataclass, field +from typing import Any + +#: Terminal outcomes of an executed action. ``skipped`` (budget) is never +#: persisted as an observation, so a resumed run with more budget runs it. +OK = "ok" +UNSUPPORTED = "unsupported" # capability / data precondition not met; nothing ran +FAILED = "failed" # raised during execution; no measurement +UNFAITHFUL = "unfaithful" # the edit's own self-check failed; no measurement +SKIPPED = "skipped" +TERMINAL = frozenset({OK, UNSUPPORTED, FAILED, UNFAITHFUL}) + + +def canonical(value: Any) -> Any: + """A JSON-stable rendering of *value* for hashing and logging. + + Callables become their import path (a function's repr carries a memory + address, which would give every run a new identity); sets are sorted; + anything else unknown falls back to its type name and repr. + """ + if value is None or isinstance(value, (bool, int, float, str)): + return value + if isinstance(value, dict): + return {str(k): canonical(v) for k, v in sorted(value.items(), key=lambda kv: str(kv[0]))} + if isinstance(value, (list, tuple)): + return [canonical(v) for v in value] + if isinstance(value, (set, frozenset)): + return sorted(canonical(v) for v in value) + if callable(value): + module = getattr(value, "__module__", None) or "?" + name = getattr(value, "__qualname__", None) or type(value).__qualname__ + return f"callable:{module}.{name}" + if hasattr(value, "item") and callable(value.item): # numpy / torch scalars + try: + return canonical(value.item()) + except Exception: # noqa: BLE001 - not a scalar after all + pass + return f"{type(value).__name__}:{value!r}" + + +def digest(payload: Any) -> str: + """16-hex content hash of :func:`canonical` ``(payload)``.""" + text = json.dumps(canonical(payload), sort_keys=True, ensure_ascii=False) + return hashlib.sha1(text.encode("utf-8")).hexdigest()[:16] + + +@dataclass(frozen=True) +class ProbeAction: + """One planned experiment, executed exactly as written. + + Attributes: + analyzer: registered analyzer name. + config: constructor keyword arguments (only the ones the plan sets; + the executed analyzer's full ``get_params()`` is recorded on + the observation). + case_ids: the cases it runs on, in batch order. The analyzer receives + exactly these — no cap, no backfill. + route: the triage route or method layer it serves (``H``, ``N``, ``N1``). + purpose: why the plan contains it, in one line. + source: which policy proposed it. + reserve: estimated model calls by method, reserved before execution. + """ + + analyzer: str + config: dict[str, Any] + case_ids: tuple[str, ...] + route: str + purpose: str + source: str = "mvp0_fixed_order" + reserve: dict[str, int] = field(default_factory=dict) + + def identity(self, context: dict[str, Any]) -> str: + return digest({ + "analyzer": self.analyzer, "config": self.config, + "case_ids": list(self.case_ids), "context": context, + }) + + def to_dict(self) -> dict[str, Any]: + out = canonical(asdict(self)) + out["n_cases"] = len(self.case_ids) + return out + + +@dataclass +class Observation: + """What one execution attempt of an action produced. + + ``findings`` is ``None`` unless ``status == "ok"``: a failed, unsupported + or unfaithful action has no measurement, and no zero is written in its place. + + ``fidelity["status"]`` is one of ``passed`` / ``failed`` / ``unchecked`` + (the tool has an implementation check that did not run) / + ``not_applicable`` (no implementation edit to check). + """ + + action_id: str + analyzer: str + attempt: int + status: str + params: dict[str, Any] + planned_ids: list[str] + measured_ids: list[str] = field(default_factory=list) + missing: dict[str, str] = field(default_factory=dict) + findings: "dict[str, Any] | None" = None + error_type: "str | None" = None + error: "str | None" = None + fidelity: dict[str, Any] = field(default_factory=lambda: {"status": "not_applicable"}) + cost: dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> dict[str, Any]: + return canonical(asdict(self)) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "Observation": + names = cls.__dataclass_fields__.keys() + return cls(**{k: v for k, v in data.items() if k in names}) + + def per_case(self) -> dict[str, dict[str, Any]]: + """``{case_id: per_case row}`` for an ``ok`` observation, else empty.""" + rows = (self.findings or {}).get("per_case") or [] + return {str(r.get("sample_id")): r for r in rows if isinstance(r, dict) and r.get("sample_id") is not None} diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py new file mode 100644 index 00000000..a6116bd6 --- /dev/null +++ b/evalrx/eval_agent/probing/controller.py @@ -0,0 +1,284 @@ +"""MVP-0: the fixed triage plan, executed strictly, with its trace and costs. + +The plan is four actions on one matched sample, in this order: + +1. ``answer_extraction_audit`` (re-reads the Stage-0 outputs; no model call) +2. ``termination_audit`` without continuation (re-reads the outputs too) +3. ``modality_ablation(mode="swap")`` — the N triage check +4. ``attention_knockout(target="gold")`` — the first N-layer measurement, on + white-box backends; elsewhere it is gated off as ``unsupported`` + +No judge is called and nothing is selected adaptively: MVP-0 establishes the +execution, metering, fidelity and trace contracts the adaptive controller +(MVP-3) will be built on. Outputs land in ``out_dir``:: + + split_manifest.json triage_report.json triage_report.md + selection_trace.jsonl cost_ledger.jsonl observations/.json +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable + +from evalrx.eval_agent.probing.actions import OK, SKIPPED, ProbeAction, canonical +from evalrx.eval_agent.probing.executor import execute +from evalrx.eval_agent.probing.ledger import Ledger +from evalrx.eval_agent.probing.sampler import matched_sample +from evalrx.eval_agent.probing.triage import summarize, triage_cases + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + +POLICY_VERSION = "mvp0-1" + + +@dataclass(frozen=True) +class PlanStep: + """One row of the fixed plan: what to build, why, and what it may cost.""" + + analyzer: str + config: dict[str, Any] + route: str + purpose: str + fidelity_check: "str | None" = None # "edit" = tap/linear self-check applies + calls_per_case: dict[str, int] = field(default_factory=dict) + + +MVP0_PLAN: tuple[PlanStep, ...] = ( + PlanStep("answer_extraction_audit", {"reask": False}, "H", + "re-read Stage-0 outputs for grading and extraction problems"), + PlanStep("termination_audit", {"continue_non_clean": False}, "H", + "classify how each Stage-0 output ended, without continuing it"), + PlanStep("modality_ablation", {"mode": "swap"}, "N", + "re-ask with a different case's media; an unchanged answer is the N signal", + calls_per_case={"generate": 2}), + PlanStep("attention_knockout", {"target": "gold"}, "N1", + "cut text-to-media attention per layer band; margin change of the gold first token", + fidelity_check="edit", calls_per_case={"forward": 5}), +) + + +def _write_json(path: Path, payload: Any) -> None: + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(canonical(payload), ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, path) + + +def _build(step: PlanStep, extra: dict[str, Any]) -> Any: + from evalrx.core.registry import registry + + return registry.analyzers.get(step.analyzer)(**{**step.config, **extra}) + + +def run_triage_mvp0( + model: Any, + explore: "CaseBatch", + *, + out_dir: "str | Path", + model_identity: dict[str, Any], + n_fail: int = 8, + seed: int = 0, + stratum: str = "gold", + host_assumed_finish: bool = False, + answer_contract: bool = False, + analyzer_kwargs: "dict[str, dict[str, Any]] | None" = None, + plan: "tuple[PlanStep, ...]" = MVP0_PLAN, + budget_sec: float = 0.0, + stage0_cost: "dict[str, Any] | None" = None, + partition: "dict[str, Any] | None" = None, + run_logger: Any = None, + progress: "Callable[[str], None] | None" = print, +) -> dict[str, Any]: + """Run the fixed triage plan on a matched sample of *explore*; return the report. + + Args: + model: the model under test. + explore: Stage-0-labelled EXPLORE cases (CONFIRM never enters here). + out_dir: where the trace, ledger, observations and report go. + model_identity: spec / weights / backend / dtype / generation settings; + part of every action identity, so a different model + never reuses an observation. + n_fail: FAIL cases to draw (PASS controls are matched to them). + seed: rank seed of the nested sampler. + stratum: ``"gold"`` (match PASS on the gold answer) or ``"none"``. + host_assumed_finish: the host, not the backend, set ``finish_reason``. + answer_contract: the task declares an answer tag or output contract. + analyzer_kwargs: per-analyzer constructor extras the host supplies + (e.g. the task's ``score_fn``); recorded in the config. + budget_sec: wall-clock cap on executed actions (0 = none). An action + already running is not interrupted; later ones are skipped. + stage0_cost: the shared baseline cost, logged once and kept separate. + partition: how EXPLORE/CONFIRM were split (recorded, not used). + run_logger: optional RunLoggerV2 for per-call model logs. + """ + say = progress or (lambda _msg: None) + out = Path(out_dir) + ledger = Ledger(out) + extras = analyzer_kwargs or {} + sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) + _write_json(out / "split_manifest.json", { + "policy": POLICY_VERSION, "partition": partition or {}, "n_explore": len(explore), + "sample": draw.to_dict(), + }) + if stage0_cost: + # Every invocation's Stage 0 is spent compute (the runner does not cache + # it), even when every action is then read back from an earlier run. + n_prior = sum(1 for e in ledger.cost_events() if e.get("kind") == "stage0") + ledger.cost({"kind": "stage0", "shared": True, "invocation": n_prior + 1, **stage0_cost}) + say(f"[triage] sample: {len(draw.fail_ids)} FAIL + {len(draw.pass_ids)} PASS " + f"(stratum={stratum}, shortfall={draw.shortfall or 'none'})") + + context = {"policy": POLICY_VERSION, "model": model_identity} + observations: dict[str, Any] = {} + steps: list[dict[str, Any]] = [] + for step_no, step in enumerate(plan): + extra = extras.get(step.analyzer, {}) + action = ProbeAction( + analyzer=step.analyzer, config={**step.config, **extra}, case_ids=draw.case_ids, + route=step.route, purpose=step.purpose, + reserve={k: v * len(draw.case_ids) for k, v in step.calls_per_case.items()}, + ) + action_id = action.identity(context) + base = {"step": step_no, "action_id": action_id, "analyzer": step.analyzer} + + done = ledger.settled(action_id) + if done is not None: + ledger.trace({**base, "event": "reused", "status": done.status, "attempt": done.attempt, + "note": "terminal observation with the same identity; read back, not re-run"}) + observations[step.analyzer] = done + steps.append({**base, "status": done.status, "reused": True, "fidelity": done.fidelity, + "cost": done.cost, "error": done.error}) + say(f"[triage] {step_no} {step.analyzer}: reused ({done.status})") + continue + + if budget_sec > 0 and ledger.spent_wall_sec() >= budget_sec: + ledger.trace({**base, "event": "skipped", "status": SKIPPED, + "reason": f"wall-clock budget {budget_sec}s spent"}) + steps.append({**base, "status": SKIPPED, "reason": "budget"}) + say(f"[triage] {step_no} {step.analyzer}: skipped (budget)") + continue + + prior = ledger.attempts(action_id) + attempt = prior + 1 + try: + analyzer = _build(step, extra) + except Exception as exc: # noqa: BLE001 - a bad config is an outcome, not a crash + ledger.trace({**base, "event": "skipped", "status": "failed", + "reason": f"could not construct: {type(exc).__name__}: {exc}"}) + steps.append({**base, "status": "failed", "error": str(exc)}) + continue + ledger.trace({ + **base, "event": "planned", "attempt": attempt, "action": action.to_dict(), + "params": canonical(analyzer.get_params()), "fidelity_check": step.fidelity_check, + "rationale": "MVP-0 fixed order", "candidates": [s.analyzer for s in plan], + **({"previous_attempts_uncertain": prior} if prior else {}), + }) + say(f"[triage] {step_no} {step.analyzer}: running on {len(sample)} cases") + obs = execute(action, action_id, attempt, analyzer, model, sample, + fidelity_check=step.fidelity_check, run_logger=run_logger) + ledger.save(obs) + ledger.cost({"kind": "action", "action_id": action_id, "analyzer": step.analyzer, + "attempt": attempt, "reserved_calls": action.reserve, + "baseline_reused": obs.status == OK and not obs.cost.get("calls"), + "judge_calls": 0, **obs.cost}) + ledger.trace({**base, "event": "settled", "attempt": attempt, "status": obs.status, + "fidelity": obs.fidelity.get("status"), "n_measured": len(obs.measured_ids), + "n_missing": len(obs.missing), "error_type": obs.error_type, "error": obs.error}) + observations[step.analyzer] = obs + steps.append({**base, "status": obs.status, "reused": False, "fidelity": obs.fidelity, + "cost": obs.cost, "error": obs.error, "n_measured": len(obs.measured_ids), + "missing": obs.missing}) + say(f"[triage] {step_no} {step.analyzer}: {obs.status} " + f"(fidelity={obs.fidelity.get('status')}, {obs.cost.get('wall_sec')}s, calls={obs.cost.get('calls')})") + + records = triage_cases(sample, observations, host_assumed_finish=host_assumed_finish, + answer_contract=answer_contract) + report = { + "policy": POLICY_VERSION, + "model": model_identity, + "sample": draw.to_dict(), + "settings": {"host_assumed_finish": host_assumed_finish, "answer_contract": answer_contract, + "budget_sec": budget_sec}, + "steps": steps, + "summary": summarize(records), + "checks": _acceptance(plan, steps, observations, draw, ledger), + "cases": records, + } + _write_json(out / "triage_report.json", report) + (out / "triage_report.md").write_text(_markdown(report), encoding="utf-8") + return report + + +def _acceptance(plan: "tuple[PlanStep, ...]", steps: list[dict[str, Any]], observations: dict[str, Any], + draw: Any, ledger: Ledger) -> dict[str, Any]: + """The MVP-0 acceptance properties that can be checked from the run's own records.""" + planned = {s.analyzer for s in plan} + traced = {e.get("analyzer") for e in ledger.trace_events() if e.get("event") in ("planned", "settled")} + case_sets = {name: obs.planned_ids == list(draw.case_ids) and set(obs.measured_ids) <= set(draw.case_ids) + for name, obs in observations.items()} + configs = {} + for s in plan: + obs = observations.get(s.analyzer) + if obs is not None: + configs[s.analyzer] = all(obs.params.get(k) == canonical(v) for k, v in s.config.items()) + costs = ledger.cost_events() + return { + "only_planned_actions": traced <= planned and len(steps) == len(plan), + "case_sets_match_plan": case_sets, + "configs_match_plan": configs, + "stage0_cost_separate": any(e.get("kind") == "stage0" for e in costs), + "no_zero_for_failure": all(obs.findings is None for obs in observations.values() if obs.status != OK), + "fidelity_states": {name: (obs.fidelity or {}).get("status") for name, obs in observations.items()}, + } + + +def _markdown(report: dict[str, Any]) -> str: + s = report["summary"] + lines = [ + f"# Triage report ({report['policy']})", "", + f"Model: `{report['model'].get('spec')}` on `{report['model'].get('backend')}`. " + f"Sample: {len(report['sample']['fail_ids'])} FAIL + {len(report['sample']['pass_ids'])} PASS, " + f"stratum `{report['sample']['stratum_rule']}`, shortfall {report['sample']['shortfall'] or 'none'}.", + "", "## Actions", "", + "| step | analyzer | status | fidelity | wall s | calls |", "|---|---|---|---|---:|---|", + ] + for st in report["steps"]: + cost = st.get("cost") or {} + lines.append(f"| {st['step']} | {st['analyzer']} | {st['status']}{' (reused)' if st.get('reused') else ''} " + f"| {(st.get('fidelity') or {}).get('status', '-')} | {cost.get('wall_sec', '-')} " + f"| {cost.get('calls', '-')} |") + lines += ["", "## Routes on this sample", "", + "| route | FAIL fired/tested | PASS fired/tested | routing signal |", "|---|---|---|---:|"] + for tag in ("H_label_free", "N"): + f, p = s[tag]["fail"], s[tag]["pass"] + lines.append(f"| {tag} | {f['n_fired']}/{f['n_tested']} | {p['n_fired']}/{p['n_tested']} " + f"| {s[tag]['routing_signal']} |") + lines += [f"| X (no H/N signal) | {s['X']['fail']} | {s['X']['pass']} | - |", "", + "The routing signal is max(0, P(tag|FAIL) - P(tag|PASS)) on this matched sample: it steers " + "later actions and is not an explained share of failures. U was not run; S is not assigned."] + split = s.get("N_by_base_answer") + if split: + lines += ["", "N by the unablated answer (unchanged after swap / tested):", "", + "| base answer | FAIL | PASS |", "|---|---|---|"] + for answer, row in split.items(): + if answer.startswith("_"): + continue + lines.append(f"| {answer or '(empty)'} | {row['fail']['n_fired']}/{row['fail']['n_tested']} " + f"| {row['pass']['n_fired']}/{row['pass']['n_tested']} |") + lines += ["", f"_{split['_note']}._"] + ko = s["attention_knockout"] + lines += ["", "## Knockout (descriptive)", "", f"Fidelity: {', '.join(ko['fidelity'])}.", "", + "| label | measured | mean ko_delta_full | mean ko_delta_late |", "|---|---:|---:|---:|"] + for label in ("fail", "pass"): + row = ko[label] + lines.append(f"| {label.upper()} | {row['n_measured']} | {row['mean_ko_delta_full']} " + f"| {row['mean_ko_delta_late']} |") + lines += ["", f"_{ko['_note']}._", "", "## Checks", ""] + for name, value in report["checks"].items(): + lines.append(f"- `{name}`: {value}") + lines.append("") + return "\n".join(lines) diff --git a/evalrx/eval_agent/probing/executor.py b/evalrx/eval_agent/probing/executor.py new file mode 100644 index 00000000..c2beccb7 --- /dev/null +++ b/evalrx/eval_agent/probing/executor.py @@ -0,0 +1,118 @@ +"""Strict execution of one :class:`~evalrx.eval_agent.probing.actions.ProbeAction`. + +Unlike ``ProbeAgent.probe``, nothing here selects, filters, backfills, caps or +generates: the analyzer runs once on exactly the planned cases, and the +outcome is typed instead of swallowed — + +* ``unsupported`` — a required capability or media slot is missing; checked + before anything runs, so no model call is spent; +* ``unfaithful`` — the edit mechanism's own self-check failed + (:class:`~evalrx.analyzers._internals.attn_tap.FidelityError`); +* ``failed`` — any other exception; +* ``ok`` — findings, plus which planned cases actually produced a row. + +Only ``ok`` carries findings; the other outcomes carry the reason, never a zero. +""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING, Any + +from evalrx.eval_agent.probing.actions import ( + FAILED, + OK, + UNFAITHFUL, + UNSUPPORTED, + Observation, + ProbeAction, + canonical, +) +from evalrx.eval_agent.probing.metering import MeteredModel, gpu_peak_mb, gpu_peak_reset + +if TYPE_CHECKING: + from evalrx.core.analyzer import Analyzer + from evalrx.core.case import CaseBatch + + +def gate(analyzer: "Analyzer", model: Any, cases: "CaseBatch") -> "str | None": + """Why *analyzer* cannot run here, or ``None`` when its preconditions hold.""" + have = getattr(model, "capabilities", frozenset()) or frozenset() + missing = sorted(c.value for c in set(getattr(analyzer, "requires", ())) - set(have)) + if missing: + return f"model lacks capabilities {missing}" + slots = set(getattr(analyzer, "requires_modalities", ()) or ()) + if slots and not any(getattr(c.inputs, s, None) is not None for c in cases for s in slots): + return f"no planned case fills a {sorted(slots)} slot" + return None + + +def _fidelity(check: "str | None", findings: dict[str, Any]) -> dict[str, Any]: + if check is None: + return {"status": "not_applicable"} + verdict = findings.get("tap_fidelity") + if not isinstance(verdict, dict): + return {"status": "unchecked", "reason": "analyzer reported no fidelity verdict"} + faithful = verdict.get("faithful", verdict.get("tap_faithful")) + return {"status": "passed" if faithful else "failed", "verdict": canonical(verdict)} + + +def execute(action: ProbeAction, action_id: str, attempt: int, analyzer: "Analyzer", + model: Any, cases: "CaseBatch", *, fidelity_check: "str | None" = None, + run_logger: Any = None) -> Observation: + """Run *analyzer* on *cases* (= ``action.case_ids``) once and type the outcome.""" + from evalrx.analyzers._internals.attn_tap import FidelityError + from evalrx.core.capability import CapabilityError + + planned = [str(c.id) for c in cases] + if planned != list(action.case_ids): + raise ValueError(f"{action.analyzer}: executor got cases {planned}, planned {list(action.case_ids)}") + obs = Observation( + action_id=action_id, analyzer=action.analyzer, attempt=attempt, status=FAILED, + params=canonical(analyzer.get_params()), planned_ids=planned, + fidelity={"status": "not_applicable"} if fidelity_check is None + else {"status": "unchecked", "reason": "action did not reach the check"}, + ) + why = gate(analyzer, model, cases) + if why is not None: + obs.status, obs.error = UNSUPPORTED, why + obs.cost = {"wall_sec": 0.0, "calls": {}, "model_sec": 0.0, "gpu_peak_mb": None} + return obs + + target = model + if run_logger is not None: + from evalrx.eval_agent.model_instrumentation import InstrumentedModel + + target = InstrumentedModel( + model, run_logger, cycle=0, analyzer=action.analyzer, + case_prompts={str(c.inputs.prompt): str(c.id) for c in cases}, + batch_case_ids=planned, + ) + metered = MeteredModel(target) + measured_gpu = gpu_peak_reset() + t0 = time.monotonic() + try: + result = analyzer.run(metered, cases) + except CapabilityError as exc: + obs.status, obs.error_type, obs.error = UNSUPPORTED, type(exc).__name__, str(exc)[:500] + except FidelityError as exc: + obs.status, obs.error_type, obs.error = UNFAITHFUL, type(exc).__name__, str(exc)[:500] + obs.fidelity = {"status": "failed", "verdict": canonical(exc.verdict)} + except Exception as exc: # noqa: BLE001 - typed outcome, not a crash of the controller + obs.status, obs.error_type, obs.error = FAILED, type(exc).__name__, str(exc)[:500] + else: + findings = canonical(result.findings or {}) + obs.status, obs.findings = OK, findings + obs.measured_ids = [i for i in planned if i in obs.per_case()] + skips = findings.get("skip_reasons") or {} + note = f"no per_case row (analyzer skip_reasons: {skips})" if skips else "no per_case row" + obs.missing = {i: note for i in planned if i not in set(obs.measured_ids)} + obs.fidelity = _fidelity(fidelity_check, findings) + obs.cost = { + "wall_sec": round(time.monotonic() - t0, 3), + "calls": dict(metered.calls), + "call_errors": dict(metered.errors), + "model_sec": round(metered.model_sec, 3), + "gpu_peak_mb": gpu_peak_mb() if measured_gpu else None, + } + return obs diff --git a/evalrx/eval_agent/probing/ledger.py b/evalrx/eval_agent/probing/ledger.py new file mode 100644 index 00000000..e8c2a81a --- /dev/null +++ b/evalrx/eval_agent/probing/ledger.py @@ -0,0 +1,89 @@ +"""Append-only run records and resume. + +Layout under the run's ``probing/`` directory:: + + selection_trace.jsonl one line per decision event (planned / settled / reused / skipped) + cost_ledger.jsonl one line per settled cost (the shared Stage-0 baseline first) + observations/.json the full outcome of each terminal action attempt + +Resume rule: an action whose identity already has a terminal observation is +read back, not re-run, and earns no new cost. An attempt that was planned but +never settled (the process died mid-action) is recorded as uncertain; the next +attempt gets a new number and its own cost line, so nothing is silently +counted twice or not at all. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +from evalrx.eval_agent.probing.actions import TERMINAL, Observation, canonical + + +class Ledger: + def __init__(self, root: "str | Path") -> None: + self.root = Path(root) + self.obs_dir = self.root / "observations" + self.obs_dir.mkdir(parents=True, exist_ok=True) + self.trace_path = self.root / "selection_trace.jsonl" + self.cost_path = self.root / "cost_ledger.jsonl" + + # -- append-only logs ---------------------------------------------------- + @staticmethod + def _append(path: Path, record: dict[str, Any]) -> None: + with path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(canonical(record), ensure_ascii=False, sort_keys=True) + "\n") + fh.flush() + os.fsync(fh.fileno()) + + @staticmethod + def _read(path: Path) -> list[dict[str, Any]]: + if not path.is_file(): + return [] + out = [] + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except json.JSONDecodeError: # a torn last line from a killed run + continue + return out + + def trace(self, record: dict[str, Any]) -> None: + self._append(self.trace_path, record) + + def cost(self, record: dict[str, Any]) -> None: + self._append(self.cost_path, record) + + def trace_events(self) -> list[dict[str, Any]]: + return self._read(self.trace_path) + + def cost_events(self) -> list[dict[str, Any]]: + return self._read(self.cost_path) + + # -- observations ---------------------------------------------------------- + def save(self, obs: Observation) -> Path: + path = self.obs_dir / f"{obs.action_id}.json" + tmp = path.with_suffix(".json.tmp") + tmp.write_text(json.dumps(obs.to_dict(), ensure_ascii=False, indent=2, sort_keys=True) + "\n", + encoding="utf-8") + os.replace(tmp, path) + return path + + def settled(self, action_id: str) -> "Observation | None": + path = self.obs_dir / f"{action_id}.json" + if not path.is_file(): + return None + obs = Observation.from_dict(json.loads(path.read_text(encoding="utf-8"))) + return obs if obs.status in TERMINAL else None + + def attempts(self, action_id: str) -> int: + return sum(1 for e in self.trace_events() + if e.get("event") == "planned" and e.get("action_id") == action_id) + + def spent_wall_sec(self) -> float: + return sum(float(e.get("wall_sec") or 0.0) for e in self.cost_events() if e.get("kind") == "action") diff --git a/evalrx/eval_agent/probing/metering.py b/evalrx/eval_agent/probing/metering.py new file mode 100644 index 00000000..1bd80ccc --- /dev/null +++ b/evalrx/eval_agent/probing/metering.py @@ -0,0 +1,73 @@ +"""Per-action resource metering. + +``MeteredModel`` wraps the model for one action and counts every +generate/forward/logprobs/chat call and the seconds spent inside them; the +wall clock and the GPU peak (when torch is already loaded) bracket the whole +action. Calls and seconds are reported side by side, never added together. +""" + +from __future__ import annotations + +import sys +import threading +import time +from collections import Counter +from typing import Any + + +class MeteredModel: + """Transparent proxy that counts model calls (repr and attributes forward).""" + + def __init__(self, model: Any) -> None: + self._metered = model + self.calls: Counter = Counter() + self.errors: Counter = Counter() + self.model_sec = 0.0 + self._lock = threading.Lock() + + def __getattr__(self, name: str) -> Any: + return getattr(self._metered, name) + + def __repr__(self) -> str: + return repr(self._metered) # Result.model and cache keys stay unchanged + + def _timed(self, method: str, fn: Any, *args: Any, **kwargs: Any) -> Any: + t0 = time.monotonic() + try: + return fn(*args, **kwargs) + except Exception: + with self._lock: + self.errors[method] += 1 + raise + finally: + with self._lock: + self.calls[method] += 1 + self.model_sec += time.monotonic() - t0 + + def generate(self, inputs: Any, **kwargs: Any) -> Any: + return self._timed("generate", self._metered.generate, inputs, **kwargs) + + def forward(self, inputs: Any, capture: Any, spec: Any = None) -> Any: + return self._timed("forward", self._metered.forward, inputs, capture, spec) + + def logprobs(self, inputs: Any, **kwargs: Any) -> Any: + return self._timed("logprobs", self._metered.logprobs, inputs, **kwargs) + + def chat(self, messages: list, tools: "list | None" = None) -> Any: + return self._timed("chat", self._metered.chat, messages, tools) + + +def gpu_peak_reset() -> bool: + """Reset the CUDA peak counter; ``False`` when there is no CUDA to measure.""" + torch = sys.modules.get("torch") # never import torch just to meter an API run + if torch is None or not torch.cuda.is_available(): + return False + torch.cuda.reset_peak_memory_stats() + return True + + +def gpu_peak_mb() -> "float | None": + torch = sys.modules.get("torch") + if torch is None or not torch.cuda.is_available(): + return None + return round(torch.cuda.max_memory_allocated() / 2 ** 20, 1) diff --git a/evalrx/eval_agent/probing/partition.py b/evalrx/eval_agent/probing/partition.py new file mode 100644 index 00000000..ff1e18d0 --- /dev/null +++ b/evalrx/eval_agent/probing/partition.py @@ -0,0 +1,28 @@ +"""The EXPLORE/CONFIRM partition, derived by the diagnosis loop's own code. + +A triage run must see exactly the EXPLORE cases a judge-driven run on the same +batch sees, or the two policies cannot be compared case for case. Rather than +re-implementing the stratified split (and drifting from it), this calls +``VLDiagnoseLoop._split_partitions`` with only the attributes it reads. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + + +def explore_confirm_split(data: "CaseBatch", confirm_split: float, + seed: int) -> "tuple[CaseBatch, CaseBatch | None]": + """``(explore, confirm)`` exactly as ``VLDiagnoseLoop(confirm_split=..., confirm_split_seed=seed)``.""" + from evalrx.eval_agent.loop import VLDiagnoseLoop + + view = SimpleNamespace( + confirm_split=float(confirm_split), test_split=0.0, + confirm_split_seed=int(seed), _strat_key=VLDiagnoseLoop._strat_key, + ) + explore, confirm, _test = VLDiagnoseLoop._split_partitions(view, data) + return explore, confirm diff --git a/evalrx/eval_agent/probing/sampler.py b/evalrx/eval_agent/probing/sampler.py new file mode 100644 index 00000000..973e30d3 --- /dev/null +++ b/evalrx/eval_agent/probing/sampler.py @@ -0,0 +1,110 @@ +"""Matched, nested FAIL/PASS samples for triage actions. + +``ProbeAgent._cap_cases`` subsamples each label proportionally by even stride: +fine as a cost backstop, but a larger cap does not contain a smaller one and +the PASS cases are not matched to the FAILs. Triage needs both: + +* **matched** — each FAIL is paired with a PASS from the same stratum (e.g. + the same gold answer on a yes/no task), so a FAIL-vs-PASS contrast is not a + gold-answer contrast in disguise; +* **nested** — every case gets a fixed rank from ``sha1(seed:id)``; a draw + takes rank prefixes, so the 8-FAIL sample is contained in the 16-FAIL one + and an extension reuses every earlier observation. + +A stratum with too few PASS cases is reported as a shortfall; nothing is +borrowed from another stratum to fake balance. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Callable + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + + +def gold_stratum(case: Any) -> str: + """Stratum = the normalised gold answer (for yes/no and letter tasks).""" + meta = getattr(case, "metadata", None) or {} + gold = meta.get("gold", getattr(case, "expected", None)) + if isinstance(gold, (list, tuple)): + gold = "|".join(str(g) for g in gold) + return str(gold).strip().lower() + + +def single_stratum(case: Any) -> str: + return "all" + + +STRATA: dict[str, Callable[[Any], str]] = {"gold": gold_stratum, "none": single_stratum} + + +def _rank(seed: int, case_id: str) -> str: + return hashlib.sha1(f"{seed}:{case_id}".encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class SampleDraw: + """Which cases a draw took and why; ``case_ids`` keeps the batch order.""" + + case_ids: tuple[str, ...] + fail_ids: tuple[str, ...] + pass_ids: tuple[str, ...] + strata: dict[str, dict[str, int]] + shortfall: dict[str, int] + seed: int + stratum_rule: str + n_fail_requested: int + + def to_dict(self) -> dict[str, Any]: + return { + "case_ids": list(self.case_ids), "fail_ids": list(self.fail_ids), + "pass_ids": list(self.pass_ids), "strata": self.strata, + "shortfall": self.shortfall, "seed": self.seed, + "stratum_rule": self.stratum_rule, "n_fail_requested": self.n_fail_requested, + "rule": ("FAIL: first n by sha1(seed:id); PASS: per stratum, as many as the " + "chosen FAILs in that stratum, first by the same rank; no cross-stratum fill"), + } + + +def matched_sample(cases: "CaseBatch", n_fail: int, *, seed: int, + stratum: str = "gold") -> "tuple[CaseBatch, SampleDraw]": + """Draw up to *n_fail* FAIL cases and their stratum-matched PASS controls.""" + from evalrx.core.case import CaseBatch, Label + + key = STRATA[stratum] + pool = list(cases) + fails = sorted((c for c in pool if c.label == Label.FAIL), key=lambda c: _rank(seed, str(c.id))) + passes = sorted((c for c in pool if c.label == Label.PASS), key=lambda c: _rank(seed, str(c.id))) + chosen_fail = fails[:max(0, int(n_fail))] + + need: dict[str, int] = {} + for c in chosen_fail: + need[key(c)] = need.get(key(c), 0) + 1 + by_stratum: dict[str, list] = {} + for c in passes: + by_stratum.setdefault(key(c), []).append(c) + + chosen_pass: list = [] + strata: dict[str, dict[str, int]] = {} + shortfall: dict[str, int] = {} + for s in sorted(need): + available = by_stratum.get(s, []) + take = available[:need[s]] + chosen_pass.extend(take) + strata[s] = {"fail": need[s], "pass": len(take), "pass_available": len(available)} + if len(take) < need[s]: + shortfall[s] = need[s] - len(take) + + chosen = {id(c) for c in chosen_fail} | {id(c) for c in chosen_pass} + ordered = [c for c in pool if id(c) in chosen] # batch order, not rank order + draw = SampleDraw( + case_ids=tuple(str(c.id) for c in ordered), + fail_ids=tuple(str(c.id) for c in chosen_fail), + pass_ids=tuple(str(c.id) for c in chosen_pass), + strata=strata, shortfall=shortfall, seed=int(seed), + stratum_rule=stratum, n_fail_requested=int(n_fail), + ) + return CaseBatch(ordered), draw diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py new file mode 100644 index 00000000..464da0de --- /dev/null +++ b/evalrx/eval_agent/probing/triage.py @@ -0,0 +1,275 @@ +"""Route labels from the triage observations, each traced to case, field and action. + +Every check on every case ends in one of four states — ``fired``, ``clear``, +``untested`` (with the reason) or ``not_applicable`` (the field has no meaning +on this task) — so a missing measurement is never read as a negative one. + +* **H** (output or grading suspect): the answer-extraction and termination + audits. Fields defined through the gold answer or the FAIL label + (``extraction_suspect``, ``extraction_point_miss``) route cases to an audit + but are excluded from the FAIL-vs-PASS routing signal, which they would + produce by construction. Truncation fields are untested when the host, not + the backend, supplied ``finish_reason``. +* **N** (insensitive to a media swap): only a real swap with a different-content + donor and a non-empty baseline answer counts; a swap that fell back to drop + is a different intervention and leaves N untested. +* **U** is untested in MVP-0 (no repeated sampling or perturbation runs), and + **S** is not assigned: it needs the U and other behavioural checks first. +* **X**: no H or N signal fired; the case stays unexplained, with the reasons. + +``attention_knockout`` is not a route: its per-case margins and fidelity +verdict are attached to each case as the first N-layer measurement. +""" + +from __future__ import annotations + +from typing import Any + +from evalrx.eval_agent.probing.actions import OK, Observation + +FIRED, CLEAR, UNTESTED, NOT_APPLICABLE = "fired", "clear", "untested", "not_applicable" + +#: (analyzer, field, label link, kind). A label link names what the field's +#: definition already reads besides the model output. +H_FIELDS: tuple[tuple[str, str, "str | None", str], ...] = ( + ("answer_extraction_audit", "extraction_suspect", "FAIL label + gold", "flag"), + ("answer_extraction_audit", "extraction_point_miss", "gold", "flag"), + ("answer_extraction_audit", "output_truncated", None, "truncation"), + ("answer_extraction_audit", "gave_up", None, "flag"), + ("termination_audit", "looks_truncated", None, "truncation"), + ("termination_audit", "termination_class", None, "class"), + ("termination_audit", "gave_up", None, "flag"), +) +_FIRING_CLASSES = {"truncated", "degenerate", "gave_up"} +_KNOCKOUT_FIELDS = ("ko_margin_clean", "ko_delta_full", "ko_rel_drop_full", "ko_flips_top1", + "ko_delta_early", "ko_delta_mid", "ko_delta_late") + + +def finish_reason_source(case: Any, host_assumed: bool) -> str: + """``host_assumed`` | ``backend`` | ``heuristic`` — where truncation evidence comes from.""" + if host_assumed: + return "host_assumed" + meta = getattr(case, "metadata", None) or {} + return "backend" if meta.get("finish_reason") in ("stop", "length") else "heuristic" + + +def _unavailable(obs: "Observation | None", analyzer: str) -> "str | None": + if obs is None: + return f"{analyzer} not in the plan or not executed" + if obs.status != OK: + return f"{analyzer} {obs.status}: {obs.error or ''}".strip() + return None + + +def _h_field(obs: "Observation | None", analyzer: str, field: str, link: "str | None", kind: str, + cid: str, provenance: str, answer_contract: bool) -> dict[str, Any]: + out: dict[str, Any] = {"analyzer": analyzer, "field": field, "label_link": link} + why = _unavailable(obs, analyzer) + if why is not None: + return {**out, "state": UNTESTED, "reason": why} + out["action_id"] = obs.action_id + row = obs.per_case().get(cid) + if row is None: + return {**out, "state": UNTESTED, "reason": obs.missing.get(cid, "no per_case row")} + if field not in row: + return {**out, "state": UNTESTED, "reason": str(row.get("skipped") or f"{field} not reported")} + value = row[field] + out["value"] = value + if kind == "truncation": + out["provenance"] = provenance + if provenance == "host_assumed": + return {**out, "state": UNTESTED, + "reason": "finish_reason='stop' was set by the host for a short-answer task; " + "truncation was not measured"} + return {**out, "state": FIRED if value else CLEAR} + if kind == "class": + if value == "no_answer" and not answer_contract: + return {**out, "state": NOT_APPLICABLE, + "reason": "the task declares no answer tag or output contract, so 'no_answer' " + "only means none was found"} + return {**out, "state": FIRED if value in _FIRING_CLASSES + or (value == "no_answer" and answer_contract) else CLEAR} + return {**out, "state": FIRED if value else CLEAR} + + +def _combine(fields: list[dict[str, Any]]) -> str: + states = {f["state"] for f in fields} + if FIRED in states: + return FIRED + if CLEAR in states: + return CLEAR + return UNTESTED + + +def _n_check(obs: "Observation | None", cid: str) -> dict[str, Any]: + why = _unavailable(obs, "modality_ablation") + if why is not None: + return {"state": UNTESTED, "reason": why} + out: dict[str, Any] = {"action_id": obs.action_id, "mode": (obs.params or {}).get("mode")} + if out["mode"] != "swap": + return {**out, "state": UNTESTED, "reason": f"modality_ablation ran mode={out['mode']!r}, not swap"} + row = obs.per_case().get(cid) + if row is None: + return {**out, "state": UNTESTED, "reason": obs.missing.get(cid, "no media slot to swap")} + out["base_answer"] = row.get("ablation_base_answer") + if not str(out["base_answer"] or "").strip(): + return {**out, "state": UNTESTED, "reason": "empty baseline answer; the comparison is not reliable"} + slots = [] + for key in sorted(row): + if not key.startswith("grounded_in_"): + continue + slot = key[len("grounded_in_"):] + entry = {"slot": slot, "donor": row.get(f"ablation_{slot}_donor"), + "swapped_answer": row.get(f"ablation_{slot}_answer")} + if row.get(f"ablation_{slot}_is_swap") is not True: + entry.update(state=UNTESTED, reason="no case held different media; the slot was dropped, " + "which is a different intervention") + else: + entry.update(state=FIRED if row[key] is False else CLEAR, answer_changed=bool(row[key])) + slots.append(entry) + if not slots: + return {**out, "state": UNTESTED, "reason": "no slot was ablated"} + state = _combine(slots) + if state == UNTESTED: + out["reason"] = "; ".join(f"{s['slot']}: {s['reason']}" for s in slots) + return {**out, "state": state, "slots": slots} + + +def _knockout(obs: "Observation | None", cid: str) -> dict[str, Any]: + if obs is None: + return {"state": UNTESTED, "reason": "attention_knockout not in the plan or not executed"} + out: dict[str, Any] = {"action_id": obs.action_id, "status": obs.status, + "fidelity": (obs.fidelity or {}).get("status")} + if obs.status != OK: + return {**out, "state": UNTESTED, "reason": obs.error or obs.status} + row = obs.per_case().get(cid) + if row is None: + return {**out, "state": UNTESTED, "reason": obs.missing.get(cid, "no per_case row")} + return {**out, "state": "measured", **{k: row[k] for k in _KNOCKOUT_FIELDS if k in row}} + + +def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assumed_finish: bool, + answer_contract: bool) -> list[dict[str, Any]]: + """One record per case: label, stratum, every H/N check, knockout row, routes.""" + from evalrx.eval_agent.probing.sampler import gold_stratum + + records = [] + for case in cases: + cid = str(case.id) + provenance = finish_reason_source(case, host_assumed_finish) + h_fields = [ + _h_field(observations.get(a), a, f, link, kind, cid, provenance, answer_contract) + for a, f, link, kind in H_FIELDS + ] + free = [f for f in h_fields if f["label_link"] is None] + disagreements = [] + trunc = {f["analyzer"]: f for f in h_fields if f.get("provenance") and f["state"] in (FIRED, CLEAR)} + if len(trunc) == 2 and len({f["state"] for f in trunc.values()}) == 2: + disagreements.append({"fields": ["answer_extraction_audit.output_truncated", + "termination_audit.looks_truncated"], + "note": "the two truncation reads disagree; audit before relying on either"}) + h = { + "state": _combine(h_fields), + "state_label_free": _combine(free), + "fired": [f"{f['analyzer']}.{f['field']}" for f in h_fields if f["state"] == FIRED], + "untested": {f"{f['analyzer']}.{f['field']}": f.get("reason") for f in h_fields + if f["state"] == UNTESTED}, + "fields": h_fields, + "disagreements": disagreements, + } + n = _n_check(observations.get("modality_ablation"), cid) + routes = [tag for tag, state in (("H", h["state"]), ("N", n["state"])) if state == FIRED] + x_reasons = [] + if not routes: + if h["state"] == UNTESTED: + x_reasons.append("H untested") + if n["state"] == UNTESTED: + x_reasons.append(f"N untested: {n.get('reason')}") + x_reasons.append("U untested: MVP-0 runs no repeated sampling or meaning-preserving " + "perturbation; S needs those checks first") + routes = ["X"] + records.append({ + "case_id": cid, + "label": getattr(getattr(case, "label", None), "value", None), + "stratum": gold_stratum(case), + "routes": routes, + "x_reasons": x_reasons, + "H": h, + "N": n, + "U": {"state": UNTESTED, "reason": "not run in MVP-0"}, + "knockout": _knockout(observations.get("attention_knockout"), cid), + }) + return records + + +def _rate(records: list[dict[str, Any]], label: str, state_of: Any) -> dict[str, Any]: + group = [r for r in records if r["label"] == label] + tested = [r for r in group if state_of(r) in (FIRED, CLEAR)] + fired = [r for r in tested if state_of(r) == FIRED] + return {"n": len(group), "n_tested": len(tested), "n_fired": len(fired), + "rate": round(len(fired) / len(tested), 4) if tested else None} + + +def _mean(values: list[float]) -> "float | None": + return round(sum(values) / len(values), 4) if values else None + + +def _n_by_base_answer(records: list[dict[str, Any]], max_answers: int = 5) -> "dict[str, Any] | None": + """N split by the unablated answer, for categorical answers only. + + An unchanged answer is only informative when the donor media should have + changed it. Whether it should is not known here — on POPE, a random donor + image usually lacks the asked-about object too, so an unchanged "No" is + the expected answer while an unchanged "Yes" is not. The split shows which + answers the N signal comes from instead of guessing a donor's gold. + """ + from evalrx.analyzers.perturbation.prompt_contrast import _norm_answer + + tested = [r for r in records if r["N"]["state"] in (FIRED, CLEAR)] + answers = sorted({_norm_answer(str(r["N"].get("base_answer") or "")) for r in tested}) + if not answers or len(answers) > max_answers: + return None + out: dict[str, Any] = {} + for answer in answers: + group = [r for r in tested if _norm_answer(str(r["N"].get("base_answer") or "")) == answer] + out[answer] = {label: {"n_tested": sum(1 for r in group if r["label"] == label), + "n_fired": sum(1 for r in group if r["label"] == label and r["N"]["state"] == FIRED)} + for label in ("fail", "pass")} + out["_note"] = ("unchanged-after-swap counts by the unablated answer; an unchanged answer that the " + "donor media would also warrant is not evidence of ignoring the media") + return out + + +def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: + """Per-route FAIL/PASS rates on this sample, and the descriptive knockout summary. + + ``routing_signal = max(0, P(tag|FAIL) - P(tag|PASS))`` steers where the + next actions go on THIS sample; it is not an explained share of failures + and says nothing about causes. H uses only label-free fields here. + """ + tags = { + "H_label_free": lambda r: r["H"]["state_label_free"], + "N": lambda r: r["N"]["state"], + } + out: dict[str, Any] = {"n_cases": len(records)} + for tag, state_of in tags.items(): + fail, pas = _rate(records, "fail", state_of), _rate(records, "pass", state_of) + signal = (round(max(0.0, fail["rate"] - pas["rate"]), 4) + if fail["rate"] is not None and pas["rate"] is not None else None) + out[tag] = {"fail": fail, "pass": pas, "routing_signal": signal} + out["H_any_audit_only"] = { + label: _rate(records, label, lambda r: r["H"]["state"]) for label in ("fail", "pass") + } + out["N_by_base_answer"] = _n_by_base_answer(records) + out["X"] = {label: sum(1 for r in records if r["label"] == label and r["routes"] == ["X"]) + for label in ("fail", "pass")} + ko: dict[str, Any] = {} + for label in ("fail", "pass"): + rows = [r["knockout"] for r in records if r["label"] == label and r["knockout"]["state"] == "measured"] + ko[label] = {"n_measured": len(rows), + "mean_ko_delta_full": _mean([float(r["ko_delta_full"]) for r in rows if "ko_delta_full" in r]), + "mean_ko_delta_late": _mean([float(r["ko_delta_late"]) for r in rows if "ko_delta_late" in r])} + ko["fidelity"] = sorted({str(r["knockout"].get("fidelity")) for r in records}) + ko["_note"] = "descriptive only: margin deltas of the gold first token, no test, no mechanism claim" + out["attention_knockout"] = ko + return out diff --git a/tests/test_analyzers/test_modality_ablation_swap.py b/tests/test_analyzers/test_modality_ablation_swap.py new file mode 100644 index 00000000..f67b09f6 --- /dev/null +++ b/tests/test_analyzers/test_modality_ablation_swap.py @@ -0,0 +1,112 @@ +"""modality_ablation(mode="swap"): donors are matched on media CONTENT, not case id. + +POPE asks two questions per COCO image and the manifest keeps the pair +adjacent; the old first-non-self donor rule "swapped" the same image back in +for the first pair and gave every other case one shared donor. +""" + +from __future__ import annotations + +import shutil + +from evalrx.analyzers.perturbation.modality_ablation import ModalityAblationAnalyzer, _media_key +from evalrx.core.capability import Capability +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.core.model import Model + + +class _ByImage(Model): + """Answers with the bytes of the image it was given, so a real swap always changes the answer.""" + + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text", "image"}) + + def __init__(self) -> None: + self.calls = 0 + + def generate(self, inputs, **kwargs): + self.calls += 1 + if inputs.image is None: + return "none" + with open(inputs.image, "rb") as fh: + return fh.read().decode() + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +def _images(tmp_path, names): + paths = {} + for name in names: + p = tmp_path / f"{name}.jpg" + p.write_text(name) + paths[name] = str(p) + return paths + + +def _case(i, image, label=Label.FAIL): + return FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"q{i}", image=image), + expected="Yes", label=label) + + +def test_swap_never_reuses_the_same_image(tmp_path): + img = _images(tmp_path, ["a", "b", "c"]) + # POPE layout: two questions per image, adjacent + batch = CaseBatch([_case(0, img["a"]), _case(1, img["a"]), _case(2, img["b"]), + _case(3, img["b"]), _case(4, img["c"]), _case(5, img["c"])]) + f = ModalityAblationAnalyzer(mode="swap").run(_ByImage(), batch).findings + rows = {r["sample_id"]: r for r in f["per_case"]} + image_of = {c.id: c.inputs.image for c in batch} + for cid, row in rows.items(): + assert row["ablation_image_is_swap"] is True + assert image_of[row["ablation_image_donor"]] != image_of[cid] + assert row["grounded_in_image"] is True # a different image always moves this model + # next different-content case in batch order, wrapping: donors spread over the batch + assert rows["c0"]["ablation_image_donor"] == "c2" + assert rows["c1"]["ablation_image_donor"] == "c2" + assert rows["c5"]["ablation_image_donor"] == "c0" + assert f["ablation_mode_image"] == "swap" and f["n_drop_fallback_image"] == 0 + assert f["ungrounded_rate_image"] == 0.0 + + +def test_identical_content_under_two_paths_is_the_same_media(tmp_path): + img = _images(tmp_path, ["a", "b"]) + copy = tmp_path / "a_copy.jpg" + shutil.copy(img["a"], copy) + batch = CaseBatch([_case(0, img["a"]), _case(1, str(copy)), _case(2, img["b"])]) + rows = {r["sample_id"]: r for r in ModalityAblationAnalyzer(mode="swap").run(_ByImage(), batch).findings["per_case"]} + assert rows["c0"]["ablation_image_donor"] == "c2" + assert _media_key(img["a"]) == _media_key(str(copy)) != _media_key(img["b"]) + + +def test_no_different_media_falls_back_to_drop_and_says_so(tmp_path): + img = _images(tmp_path, ["a", "b"]) + batch = CaseBatch([_case(0, img["a"]), _case(1, img["a"])]) + f = ModalityAblationAnalyzer(mode="swap").run(_ByImage(), batch).findings + assert f["ablation_mode_image"] == "drop" and f["n_drop_fallback_image"] == 2 + assert all(r["ablation_image_donor"] is None and r["ablation_image_is_swap"] is False + for r in f["per_case"]) + + mixed = CaseBatch([_case(0, img["a"]), _case(1, img["a"]), _case(2, img["b"])]) + f = ModalityAblationAnalyzer(mode="swap").run(_ByImage(), mixed).findings + assert f["ablation_mode_image"] == "swap" # c2 swaps with c0, c0/c1 with c2 + assert f["n_drop_fallback_image"] == 0 + + +def test_drop_mode_output_is_unchanged(tmp_path): + img = _images(tmp_path, ["a", "b"]) + batch = CaseBatch([_case(0, img["a"]), _case(1, img["b"], Label.PASS)]) + f = ModalityAblationAnalyzer().run(_ByImage(), batch).findings + assert f["ablation_mode_image"] == "drop" + assert "n_drop_fallback_image" not in f + for row in f["per_case"]: + assert set(row) == {"sample_id", "grounded_in_image", "ablation_image_is_swap"} + + +def test_in_memory_images_are_compared_by_pixels(): + from PIL import Image + + a = Image.new("RGB", (4, 4), (255, 0, 0)) + a2 = Image.new("RGB", (4, 4), (255, 0, 0)) + b = Image.new("RGB", (4, 4), (0, 0, 255)) + assert _media_key(a) == _media_key(a2) != _media_key(b) diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py new file mode 100644 index 00000000..fd16280b --- /dev/null +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -0,0 +1,348 @@ +"""MVP-0 triage controller (``--m1-policy triage_active``): the acceptance behaviours. + +* the planned actions run exactly as planned (no backfill, cap or codegen); +* unsupported / failed / unfaithful outcomes carry a reason and never a zero; +* fidelity passed, failed, unchecked and not-applicable stay distinct; +* the Stage-0 baseline cost is separate from the actions' new calls; +* swap donors and the actual mode are traceable per case; +* a resumed run reads finished actions back instead of re-running them; +* route labels never turn a missing measurement into a negative one. +""" + +from __future__ import annotations + +import json + +import pytest + +from evalrx.core.capability import Capability +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.core.model import Model +from evalrx.eval_agent.probing import explore_confirm_split, matched_sample, run_triage_mvp0 +from evalrx.eval_agent.probing.actions import ( + FAILED, + OK, + UNFAITHFUL, + UNSUPPORTED, + Observation, + ProbeAction, +) +from evalrx.eval_agent.probing.executor import execute +from evalrx.eval_agent.probing.triage import summarize, triage_cases + + +def _cases(n_fail=6, n_pass=8, gold_fail="No"): + out = [] + for i in range(n_fail): + out.append(FailureCase(id=f"f{i}", inputs=Inputs(prompt=f"is there a cat {i}?"), + expected=gold_fail, observed="Yes", label=Label.FAIL, + metadata={"gold": gold_fail})) + for i in range(n_pass): + gold = "No" if i % 2 else "Yes" + out.append(FailureCase(id=f"p{i}", inputs=Inputs(prompt=f"is there a dog {i}?"), + expected=gold, observed=gold, label=Label.PASS, + metadata={"gold": gold})) + return CaseBatch(out) + + +# -- sampler --------------------------------------------------------------------- + + +def test_matched_sample_is_nested_matched_and_order_free(): + cases = _cases() + small, d_small = matched_sample(cases, 2, seed=3) + big, d_big = matched_sample(cases, 4, seed=3) + assert set(d_small.fail_ids) <= set(d_big.fail_ids) + assert set(d_small.pass_ids) <= set(d_big.pass_ids) + # every FAIL has gold No, so every control does too + gold = {c.id: c.metadata["gold"] for c in cases} + assert {gold[i] for i in d_big.pass_ids} == {"No"} + assert d_big.strata == {"no": {"fail": 4, "pass": 4, "pass_available": 4}} + assert list(d_big.case_ids) == [c.id for c in cases if c.id in set(d_big.case_ids)] + # the draw depends on ids and seed, not on the input order + _, d_rev = matched_sample(CaseBatch(list(cases)[::-1]), 4, seed=3) + assert set(d_rev.case_ids) == set(d_big.case_ids) + + +def test_matched_sample_reports_shortfall_instead_of_borrowing(): + _, draw = matched_sample(_cases(n_fail=6), 6, seed=0) + assert draw.strata["no"] == {"fail": 6, "pass": 4, "pass_available": 4} + assert draw.shortfall == {"no": 2} + assert len(draw.pass_ids) == 4 # no gold-Yes PASS filled in + + +def test_explore_split_is_the_loops_split(): + from evalrx.eval_agent.loop import VLDiagnoseLoop + from evalrx.eval_agent.stages.protocol import ExperimentProtocol + + cases = _cases(10, 14) + loop = VLDiagnoseLoop(model=_BlackBox(), protocol=ExperimentProtocol(description="d"), + confirm_split=0.5, confirm_split_seed=20260818) + want_e, want_c = loop._split_explore_confirm(cases) + got_e, got_c = explore_confirm_split(cases, 0.5, 20260818) + assert [c.id for c in got_e] == [c.id for c in want_e] + assert [c.id for c in got_c] == [c.id for c in want_c] + + +# -- executor -------------------------------------------------------------------- + + +class _BlackBox(Model): + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text", "image"}) + + def __init__(self): + self.calls = 0 + + def generate(self, inputs, **kwargs): + self.calls += 1 + return "Yes" + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +def _analyzer(behaviour, requires=frozenset()): + from evalrx.analyzers._internals.attn_tap import FidelityError + from evalrx.core.analyzer import Analyzer + from evalrx.core.result import Result + + class _A(Analyzer): + name = "fake" + + def _run(self, model, cases): + if behaviour == "raise": + raise ValueError("boom") + if behaviour == "unfaithful": + raise FidelityError("edit untrustworthy", {"tap_faithful": False, "tap_max_logit_diff": 3.0}) + model.generate(cases[0].inputs) + rows = [{"sample_id": c.id, "v": 1} for c in list(cases)[1:]] + return Result(analyzer="fake", model=repr(model), cases=cases, + findings={"per_case": rows, "skip_reasons": {"no_media": 1}}) + + _A.requires = requires + return _A() + + +def _action(cases, name="fake"): + return ProbeAction(analyzer=name, config={}, case_ids=tuple(c.id for c in cases), route="N", purpose="t") + + +def test_executor_types_every_outcome_and_never_writes_a_zero(): + cases = _cases(2, 2) + model = _BlackBox() + ok = execute(_action(cases), "a1", 1, _analyzer("ok"), model, cases) + assert ok.status == OK and ok.cost["calls"] == {"generate": 1} + assert ok.measured_ids == [c.id for c in list(cases)[1:]] + assert set(ok.missing) == {cases[0].id} and "no_media" in ok.missing[cases[0].id] + assert ok.fidelity == {"status": "not_applicable"} + + failed = execute(_action(cases), "a2", 1, _analyzer("raise"), model, cases) + assert failed.status == FAILED and failed.findings is None and failed.error_type == "ValueError" + + unfaithful = execute(_action(cases), "a3", 1, _analyzer("unfaithful"), model, cases, fidelity_check="edit") + assert unfaithful.status == UNFAITHFUL and unfaithful.findings is None + assert unfaithful.fidelity["status"] == "failed" and unfaithful.fidelity["verdict"]["tap_max_logit_diff"] == 3.0 + + before = model.calls + gated = execute(_action(cases), "a4", 1, _analyzer("ok", frozenset({Capability.ATTENTION})), + model, cases, fidelity_check="edit") + assert gated.status == UNSUPPORTED and "attention" in gated.error and model.calls == before + assert gated.fidelity["status"] == "unchecked" + + +def test_executor_refuses_a_case_set_other_than_the_plan(): + cases = _cases(2, 2) + with pytest.raises(ValueError, match="planned"): + execute(_action(list(cases)[:2]), "a", 1, _analyzer("ok"), _BlackBox(), cases) + + +def test_fidelity_failures_are_typed_runtime_errors(monkeypatch): + torch = pytest.importorskip("torch") # noqa: F841 + pytest.importorskip("transformers") + from evalrx.analyzers._internals import edits + from evalrx.analyzers._internals.attn_tap import FidelityError + from tests.tiny_whitebox import TinyVLM, image + + monkeypatch.setattr(edits, "check_fidelity", lambda *a, **k: {"tap_faithful": False}) + with pytest.raises(FidelityError) as info: + edits.require_edit_fidelity(TinyVLM("qwen2_5_vl"), Inputs(prompt="hi", image=image(0)), [3]) + assert isinstance(info.value, RuntimeError) and info.value.verdict["faithful"] is False + + +# -- triage mapping ------------------------------------------------------------------ + + +def _obs(analyzer, rows, status=OK, params=None, error=None): + return Observation(action_id=f"id-{analyzer}", analyzer=analyzer, attempt=1, status=status, + params=params or {}, planned_ids=[r["sample_id"] for r in rows], + measured_ids=[r["sample_id"] for r in rows], + findings={"per_case": rows} if status == OK else None, error=error) + + +def test_triage_never_reads_missing_as_negative(): + cases = CaseBatch([ + FailureCase(id="f", inputs=Inputs(prompt="q"), expected="No", observed="Yes", label=Label.FAIL), + FailureCase(id="p", inputs=Inputs(prompt="q"), expected="No", observed="No", label=Label.PASS), + ]) + aea = _obs("answer_extraction_audit", [ + {"sample_id": "f", "extraction_suspect": 1, "extraction_point_miss": 0, "output_truncated": 0, "gave_up": 0}, + {"sample_id": "p", "extraction_suspect": 0, "extraction_point_miss": 0, "output_truncated": 0, "gave_up": 0}, + ]) + ta = _obs("termination_audit", [ + {"sample_id": "f", "termination_class": "no_answer", "looks_truncated": 0, "gave_up": 0}, + {"sample_id": "p", "termination_class": "no_answer", "looks_truncated": 0, "gave_up": 0}, + ]) + swap = _obs("modality_ablation", [ + {"sample_id": "f", "ablation_base_answer": "Yes", "grounded_in_image": False, + "ablation_image_is_swap": True, "ablation_image_donor": "p", "ablation_image_answer": "Yes"}, + {"sample_id": "p", "ablation_base_answer": "No", "grounded_in_image": False, + "ablation_image_is_swap": False, "ablation_image_donor": None, "ablation_image_answer": "No"}, + ], params={"mode": "swap"}) + ko = _obs("attention_knockout", [], status=FAILED, error="no case could be analysed") + records = triage_cases(cases, {"answer_extraction_audit": aea, "termination_audit": ta, + "modality_ablation": swap, "attention_knockout": ko}, + host_assumed_finish=True, answer_contract=False) + f, p = records + # extraction_suspect fires, but only the label-free H state feeds the routing signal + assert f["H"]["state"] == "fired" and f["H"]["state_label_free"] == "clear" + fields = {x["field"]: x for x in f["H"]["fields"] if x["analyzer"] == "answer_extraction_audit"} + assert fields["output_truncated"]["state"] == "untested" # host-set finish_reason + term = [x for x in f["H"]["fields"] if x["field"] == "termination_class"][0] + assert term["state"] == "not_applicable" + # real swap, unchanged answer -> N; drop fallback -> N untested, not clear + assert f["N"]["state"] == "fired" and f["N"]["slots"][0]["donor"] == "p" + assert p["N"]["state"] == "untested" and p["routes"] == ["X"] + assert any("N untested" in r for r in p["x_reasons"]) + assert f["knockout"]["state"] == "untested" and "no case" in f["knockout"]["reason"] + s = summarize(records) + assert s["N"]["pass"]["n_tested"] == 0 and s["N"]["routing_signal"] is None + assert s["H_any_audit_only"]["fail"]["n_fired"] == 1 + # only the real swap counts, split by the unablated answer + assert s["N_by_base_answer"]["yes"] == {"fail": {"n_tested": 1, "n_fired": 1}, + "pass": {"n_tested": 0, "n_fired": 0}} + + +def test_triage_truncation_counts_when_the_backend_reported_it(): + cases = CaseBatch([FailureCase(id="f", inputs=Inputs(prompt="q"), expected="1", observed="1 2 3", + label=Label.FAIL, metadata={"finish_reason": "length"})]) + aea = _obs("answer_extraction_audit", [{"sample_id": "f", "output_truncated": 1, "gave_up": 0}]) + rec = triage_cases(cases, {"answer_extraction_audit": aea}, host_assumed_finish=False, + answer_contract=False)[0] + trunc = [x for x in rec["H"]["fields"] if x["field"] == "output_truncated"][0] + assert trunc["state"] == "fired" and trunc["provenance"] == "backend" + assert rec["routes"] == ["H"] and rec["H"]["state_label_free"] == "fired" + + +# -- controller end to end --------------------------------------------------------------- + + +@pytest.fixture() +def vlm_cases(): + pytest.importorskip("torch") + pytest.importorskip("transformers") + from tests.tiny_whitebox import image + + imgs = [image(i) for i in range(4)] + out = [] + for i in range(8): + img = imgs[i // 2] # two questions per image, adjacent, like POPE + fail = i % 4 == 1 + gold = "No" if i % 2 else "Yes" + out.append(FailureCase( + id=f"pope-{i}", inputs=Inputs(prompt=f"Is there a cat in the image {i}?", image=img), + expected=gold, observed="Yes" if fail or gold == "Yes" else "No", + label=Label.FAIL if fail else Label.PASS, + metadata={"gold": gold, "finish_reason": "stop"}, + )) + return CaseBatch(out) + + +def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): + from tests.tiny_whitebox import TinyVLM + + model = TinyVLM("qwen2_5_vl") + ident = {"spec": model.spec.key, "backend": "tiny"} + kw = dict(out_dir=tmp_path / "probing", model_identity=ident, n_fail=2, seed=0, + host_assumed_finish=True, stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, + progress=None) + report = run_triage_mvp0(model, vlm_cases, **kw) + + steps = {s["analyzer"]: s for s in report["steps"]} + assert [s["status"] for s in report["steps"]] == [OK] * 4 + assert steps["answer_extraction_audit"]["cost"]["calls"] == {} # Stage-0 outputs re-read + assert steps["modality_ablation"]["cost"]["calls"] == {"generate": 8} # 4 cases x (base + swap) + assert steps["attention_knockout"]["fidelity"]["status"] == "passed" + assert steps["termination_audit"]["fidelity"]["status"] == "not_applicable" + checks = report["checks"] + assert checks["only_planned_actions"] and checks["stage0_cost_separate"] + assert all(checks["case_sets_match_plan"].values()) and all(checks["configs_match_plan"].values()) + + sample = report["sample"] + assert len(sample["fail_ids"]) == 2 and sample["strata"]["no"]["pass"] == 2 + for rec in report["cases"]: + assert rec["N"]["state"] in ("fired", "clear") # TinyVLM answers "x" whatever it sees + donor = rec["N"]["slots"][0]["donor"] + assert donor != rec["case_id"] + assert rec["knockout"]["state"] == "measured" and rec["knockout"]["fidelity"] == "passed" + + out = tmp_path / "probing" + costs = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] + assert [c["kind"] for c in costs] == ["stage0"] + ["action"] * 4 + assert costs[1]["baseline_reused"] is True and costs[3]["baseline_reused"] is False + for name in ("split_manifest.json", "triage_report.json", "triage_report.md"): + assert (out / name).is_file() + + # resume: same identities -> read back, no model calls, no new action cost + # (only this invocation's Stage 0, which the caller did spend) + n_forwards = model.n_forwards + again = run_triage_mvp0(model, vlm_cases, **kw) + assert all(s["reused"] for s in again["steps"]) and model.n_forwards == n_forwards + costs2 = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] + assert [c["kind"] for c in costs2[len(costs):]] == ["stage0"] and costs2[-1]["invocation"] == 2 + events = [json.loads(line) for line in (out / "selection_trace.jsonl").read_text().splitlines()] + assert [e["event"] for e in events].count("reused") == 4 + + # a different model identity is a different action: nothing is reused + other = run_triage_mvp0(model, vlm_cases, **{**kw, "model_identity": {**ident, "dtype": "fp32"}}) + assert not any(s["reused"] for s in other["steps"]) + + +def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): + from evalrx.eval_agent.probing.ledger import Ledger + from tests.tiny_whitebox import TinyVLM + + model = TinyVLM("qwen2_5_vl") + kw = dict(out_dir=tmp_path / "p", model_identity={"spec": "tiny"}, n_fail=2, progress=None) + first = run_triage_mvp0(model, vlm_cases, **kw) + ko_id = [s for s in first["steps"] if s["analyzer"] == "attention_knockout"][0]["action_id"] + ledger = Ledger(tmp_path / "p") + (ledger.obs_dir / f"{ko_id}.json").unlink() # as if the process died before settling + second = run_triage_mvp0(model, vlm_cases, **kw) + planned = [e for e in ledger.trace_events() if e.get("event") == "planned" and e["action_id"] == ko_id] + assert [e["attempt"] for e in planned] == [1, 2] + assert planned[1]["previous_attempts_uncertain"] == 1 + assert [s["reused"] for s in second["steps"]] == [True, True, True, False] + + +def test_mvp0_black_box_gates_off_the_white_box_step(tmp_path, vlm_cases): + model = _BlackBox() + report = run_triage_mvp0(model, vlm_cases, out_dir=tmp_path / "bb", model_identity={"spec": "bb"}, + n_fail=2, progress=None) + steps = {s["analyzer"]: s for s in report["steps"]} + assert steps["attention_knockout"]["status"] == UNSUPPORTED + assert steps["attention_knockout"]["cost"]["calls"] == {} + assert steps["modality_ablation"]["status"] == OK + assert report["checks"]["no_zero_for_failure"] is True + assert all(r["knockout"]["state"] == "untested" for r in report["cases"]) + + +def test_cli_default_policy_is_judge_and_triage_refuses_held_out(): + from evalrx.benchmark.run import build_parser, run_args + + assert build_parser().parse_args([]).m1_policy == "judge" + args = build_parser().parse_args(["--modality", "vlm", "--model", "qwen3.5-0.8b-vl", + "--m1-policy", "triage_active", "--held-out", + "--diagnosis-mode", "fixed"]) + with pytest.raises(ValueError, match="triage_active"): + run_args(args) From 25b0a7964949477ef63d99c5db3bb7003b8c8676 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sat, 17 Oct 2026 20:28:30 -0700 Subject: [PATCH 02/26] triage: per-case fidelity, counterfactual swaps, U/S routes, API metering Builds on the MVP-0 triage controller (--m1-policy triage_active). - Fidelity: edit analyzers self-check every analysed case (FidelityGate), the first unfaithful case refuses the batch; action identity includes the tool's code hash. Patchscope's patch check raises FidelityError. - modality_ablation(donor_rule="counterfactual", donor_pool): same prompt, different media, donor gold != the model's answer; few-answer tasks test N only on such swaps. - U (self_consistency per case + verbatim prompt wrappers, compared by the task's label-blind answer_key) and S (FAIL with H/N/U all tested and clear); threshold instruction, embed_lens and patchscope as descriptive S readings with case-specific question words. - Fix: logit margins compared an answer with its own other spelling ("Yes" vs " Yes"); answer surface forms are now one answer. - MVP-1: gemini runtime usage counters, per-action and Stage-0 requests, tokens and USD from a dated price table, per-call sampling on gemini, rule-based next candidates gated on the actual model. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 108 ++++++ docs/agentic_benchmark.md | 16 +- evalrx/analyzers/_internals/attn_tap.py | 42 ++- evalrx/analyzers/_internals/edits.py | 101 +++++- evalrx/analyzers/_internals/linear_mix.py | 9 +- evalrx/analyzers/_internals/targets.py | 81 ++++- evalrx/analyzers/_internals/words.py | 64 ++++ evalrx/analyzers/attribution/generic_attn.py | 17 +- evalrx/analyzers/lens/embed_lens.py | 40 +- evalrx/analyzers/lens/patchscope.py | 92 +++-- .../analyzers/patching/attention_knockout.py | 14 +- .../patching/attention_sensitivity.py | 14 +- .../patching/attention_temperature.py | 20 +- .../perturbation/modality_ablation.py | 125 ++++++- .../analyzers/perturbation/prompt_contrast.py | 4 +- evalrx/benchmark/runner.py | 57 ++- evalrx/benchmark/scoring.py | 31 ++ evalrx/benchmark/tasks/__init__.py | 1 + evalrx/benchmark/tasks/base.py | 9 + evalrx/eval_agent/probing/actions.py | 16 +- evalrx/eval_agent/probing/controller.py | 307 +++++++++++++--- evalrx/eval_agent/probing/executor.py | 63 +++- evalrx/eval_agent/probing/metering.py | 24 ++ evalrx/eval_agent/probing/proposals.py | 115 ++++++ evalrx/eval_agent/probing/triage.py | 341 ++++++++++++++++-- evalrx/models/backends/api/backend.py | 13 + evalrx/models/backends/api/gemini.py | 19 +- evalrx/models/backends/api/prices.py | 38 ++ tests/test_analyzers/test_hybrid_analyzers.py | 2 +- .../test_intervention_analyzers.py | 159 +++++++- .../test_modality_ablation_swap.py | 73 ++++ tests/test_eval_agent/test_probing_mvp0.py | 338 ++++++++++++++++- tests/test_examples/test_benchmark_common.py | 20 + tests/test_models/test_gemini_compat.py | 21 ++ 34 files changed, 2142 insertions(+), 252 deletions(-) create mode 100644 evalrx/analyzers/_internals/words.py create mode 100644 evalrx/eval_agent/probing/proposals.py create mode 100644 evalrx/models/backends/api/prices.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d961b887..3c50e7e0 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,114 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — triage on API models: provider usage, dollars, next experiments (MVP-1) + +The gemini runtime now sums the token counts every response reports +(`state["usage"]`: prompt, completion and thought tokens, plus responses that +reported none), and `APIModel.usage_counters()` exposes them with the request +and retry counts. The triage executor differences two reads around each +action (`cost["api_usage"]`), the runner does the same around Stage 0 +(`baseline.json` gains `api_usage` and `usd`), and `usd` comes from a dated +price table (`models/backends/api/prices.py`: only prices read off the +provider's page, checked 2026-10-17; an unlisted model's cost is `None`, never +a guess, and the input part is an upper bound because implicit cache hits are +not reported). The report adds a cost summary for the invocation. On the +gemini backend the U sampling check now runs: the runtime merges per-call +kwargs over its own sampling, so `self_consistency` gets `temperature=1.0` +(the endpoint backend drops per-call kwargs and stays untested). The report +also lists rule-based next candidates (`probing/proposals.py`) for every route +with FAIL cases — behavioural follow-ups first, each built and gated on the +actual model, with `executable` / `unsupported` (and why) / `already_run` / +`not_applicable`; none is run, and sample expansion is listed as not yet an +action. + +### Fixed — logit margins compared an answer with its own other spelling + +`build_margin` (every white-box analyzer's target: knockout, causal trace, +patchscope, gradcam, attribution and path patching, ...) compared the target +token with the strongest OTHER token. A BPE vocabulary holds `"Yes"`, +`" Yes"`, `"yes"` and `" yes"` as different ids, and a model can split one +answer across them: Qwen3.5-0.8B on POPE gives `" Yes"` 0.80 and `"Yes"` 0.20 +on a correct case, so the gold `"Yes"` margin compared "Yes" with " Yes" and +came out negative (−1.375) on a correct answer; `target="prediction"` had the +same problem with its top-2. The comparison token is now the strongest token +outside the answer's surface forms (`answer_variants`: with or without a +leading space, lower-case or capitalised for answers longer than one +character, each confirmed by the decoder; without a decoder only the literal +form), the gold target is the form the clean run scores highest, and +`LogitMargin.variants` lists the forms. On that case the gold margin is now ++7.875 (" Yes" vs " No"). Patchscope sums the readout probability over the +forms and counts a layer as reading the answer when any form ranks first. +Knockout and other margins measured with a decoder-backed tokenizer before +this change are not comparable with new ones. + +### Added — triage U and S routes (policy `mvp0-2`) + +The triage plan now runs five more actions after the knockout. U (an answer +that moves) has two required parts: `self_consistency`, run once per case +(the executor's new `per_case` mode, since the analyzer reads only +`cases[0]`) at the host's sampling settings (`temperature=1.0` plus the run's +`top_p`/`top_k` on local backends; greedy settings leave it untested), and +`prompt_contrast` with the question kept verbatim inside two neutral wrappers +(a wrapper whose answer is unreadable is an invalid control). Answers are +compared with the task's new label-blind `answer_key` (`benchmark.scoring`, +`tasks.answer_key`), never graded. S is a FAIL case on which H, N (cases with +media; N is now `not_applicable` without media) and both U parts ran and none +fired; a missing check leaves it in X, and a PASS case with every check clear +has no route. The S readings on every case are descriptive: a threshold +instruction (`prompt_contrast` "sensitive", yes/no tasks only; others record +the step as `not_applicable`), `embed_lens(layer=0.9)` and +`patchscope(target="gold", media_layers=3)`. Both lenses gain a question-word +reading — prompt words found in at most half of the batch's distinct prompts +(`_internals/words.py`), so template words never count: `el_query_sim`, and +`ps_media_query_hits`/`_share` (media tokens decoded as the case's question +word). Patchscope's patch self-check now raises `FidelityError` (still a +`RuntimeError`) and reports `patch_fidelity`, so the triage records an +unfaithful patch as `unfaithful`. `prompt_contrast` also keeps untruncated +outputs as an `outputs` artifact, and the executor keeps a step's named +result artifacts with its findings (`keep_artifacts`). + +### Added — counterfactual swap donors (`modality_ablation(donor_rule="counterfactual")`) + +An unchanged answer after a media swap is only evidence when the donor's +media should have changed it. On yes/no and few-option tasks a random donor +often leaves the correct answer unchanged (a random COCO image usually lacks +the object POPE asks about, so "No" stays right). The new rule first looks, +in `donor_pool` (default: the probed batch), for a case asking the identical +prompt about different-content media whose gold differs from the model's own +unablated answer (not from the case's gold: on a failed case those differ, and +a donor whose gold equals the wrong answer makes "unchanged" correct); that +gold is what a correct answer must become, recorded as +`ablation__donor_expected`. Otherwise it falls back to the content rule +and records `ablation__donor_kind="content"`. `n_counterfactual_` +counts the former. The default `donor_rule="content"` is unchanged. The triage +controller uses the counterfactual rule with the whole EXPLORE partition as +the pool; on yes/no and letter tasks, N is tested only on counterfactual swaps +(content-only swaps leave it untested with the reason), and the report adds +donor kinds and how often a counterfactual swap moved the answer to the +donor's gold. + +### Changed — edit-free self-checks run on every analysed case + +`attention_knockout`, `attention_sensitivity`, `attention_temperature` and +`generic_attention` used to check the attention tap (and, on hybrid stacks, the +media-absent linear re-run) on the first analysable case only, and the verdict +was cached on the model — so whether a whole batch was accepted depended on +which case came first. On Qwen3.5-0.8B in bf16 the tap differs from `sdpa` by +0.8–2.0% of the largest logit depending on the input, straddling the 1% +tolerance. A new `FidelityGate` (`analyzers/_internals/edits.py`) now checks +every analysed case before measuring it; the first failing case refuses the +whole batch with a `FidelityError` naming it. `tap_fidelity` reports the worst +case per mechanism, the number of argmax changes and every per-case check. +`check_fidelity` / `check_linear_fidelity` are no longer cached and +`check_fidelity` accepts the caller's native logits (`base=`) to save a +forward. Cost: one extra tapped forward per case (plus one linear re-run on a +hybrid stack). Under `sdpa` these analyzers will now usually refuse on +Qwen3.5; use `--attn-impl eager`, where the tap is exact. The triage +controller's action identity now includes a content hash of the analyzer's +module and `analyzers/_internals`, so a code change re-runs the action instead +of reading back an old observation. + ### Added — triage probing controller, MVP-0 (`--m1-policy triage_active`) An opt-in alternative to the judge-selected M1 (`evalrx/eval_agent/probing/`). diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index a4b785f0..9238a53b 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -29,9 +29,21 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend --m1-policy triage_active --run-tag triage0 ``` -After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed plan exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")` — with no backfill, case cap or generated probes. No judge is called, M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl`, `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json`, `split_manifest.json`, and `triage_report.{json,md}` with H/N/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips later actions once the wall-clock budget is spent. +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed plan exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. No judge is called, M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl`, `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json`, `split_manifest.json`, and `triage_report.{json,md}` with H/N/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips later actions once the wall-clock budget is spent. -White-box edits refuse when their edit-free self-check fails. On Qwen3.5-0.8B in bf16, the attention tap reproduces `--attn-impl eager` exactly but differs from `sdpa` by about 1–2% of the largest logit, above the 1% tolerance, so `attention_knockout` reports `unfaithful` under `sdpa`; use `--attn-impl eager` for edit-based analyzers. +The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. + +U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Any readable answer that differs fires U. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the gold answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. + +On an API model (`--backend gemini`) the same plan runs with the white-box steps recorded as `unsupported` (nothing spent). Each action's cost carries what the provider counted — requests, retries, prompt/completion/thought tokens — and its USD at the dated listed price in `evalrx/models/backends/api/prices.py` (unknown for an unlisted model); Stage 0's usage goes into `baseline.json`. The report ends with next candidates proposed by rule for every route with FAIL cases, each gated on the actual model, so a run without internal state still names which behavioural experiment it could run next and why the internal ones cannot; none is run. + +```bash +GEMINI_API_KEY=... python -m evalrx.benchmark.run --modality vlm --model gemini-3.1-flash-lite \ + --dataset pope_adversarial --limit 1000 --concurrency 8 \ + --m1-policy triage_active --triage-n-fail 32 --run-tag triage-api1 +``` + +White-box edits refuse when their edit-free self-check fails, and the check runs on every analysed case: the first failing case refuses the whole batch. On Qwen3.5-0.8B in bf16, the attention tap reproduces `--attn-impl eager` exactly but differs from `sdpa` by 0.8–2.0% of the largest logit depending on the input, around the 1% tolerance, so `attention_knockout` (and the other tap-based analyzers) report `unfaithful` under `sdpa`; use `--attn-impl eager` for edit-based analyzers. This applies to the default `judge` path as well. Action identities include a hash of the analyzer's code, so a rerun after a code change re-executes the action. White-box margins compare the target answer with the strongest token that is not one of its spellings (`"Yes"` and `" Yes"` are different BPE ids that a model can split one answer across), so margins from runs before that change are not comparable. ## Failure and progress semantics diff --git a/evalrx/analyzers/_internals/attn_tap.py b/evalrx/analyzers/_internals/attn_tap.py index 183cd020..0ca4a7a0 100644 --- a/evalrx/analyzers/_internals/attn_tap.py +++ b/evalrx/analyzers/_internals/attn_tap.py @@ -15,9 +15,12 @@ bare registration silently lets every token attend to the future. The tap registers eager's additive mask under the same name. * **Fidelity.** "The tap is installed" proves nothing on an architecture that - bypasses the interface. :func:`check_fidelity` runs one input with an + bypasses the interface. :func:`check_fidelity` runs an input with an edit-free tap: it must be called on every attention layer AND reproduce the - native logits, or :func:`require_fidelity` refuses. + native logits, or :func:`require_fidelity` refuses. Whether it reproduces + them can depend on the input (bf16 ``sdpa`` sits near the tolerance), so + analyzers check every case they report on via + :class:`~evalrx.analyzers._internals.edits.FidelityGate`; nothing is cached. Edits act on the pre-softmax scores, so they compose with the causal mask: @@ -316,41 +319,42 @@ def attention_tap( def check_fidelity(model: "Model", inputs: Any, *, rtol: float = 1e-2, - analyzer: str = "attention tap") -> "dict[str, Any]": - """Does an edit-free tap engage on every attention layer and reproduce the logits? - - Cached on the module per native attention implementation: one extra pair - of forwards per model, not per analyzer run. + analyzer: str = "attention tap", base: Any = None) -> "dict[str, Any]": + """Does an edit-free tap engage on every attention layer and reproduce the logits on *inputs*? + + Measured on this input every call (not cached): the tapped forward must + engage every softmax layer, stay within ``rtol`` of the largest native + logit at the last position, and keep the native top-1. *base* — the native + logits of this same input, when the caller already has them — saves the + native forward. """ from evalrx.core.capability import Capability module = torch_module(model, analyzer) stack = decoder_stack(module) native = tuple(str(_get_impl(getattr(a, "config", None))) for a in stack.attn if a is not None) - cache = module.__dict__.setdefault("_evalrx_tap_fidelity", {}) - if native in cache: - return dict(cache[native]) - n_attn = sum(a is not None for a in stack.attn) - base = model.forward(inputs, capture={Capability.LOGITS}).require(Capability.LOGITS) + if base is None: + base = model.forward(inputs, capture={Capability.LOGITS}).require(Capability.LOGITS) with attention_tap(model, analyzer=analyzer) as state: tapped = model.forward(inputs, capture={Capability.LOGITS}).require(Capability.LOGITS) - b, t = base[-1].float(), tapped[-1].float() + b = base[-1].float() + t = tapped[-1].float().to(b.device) diff = float((b - t).abs().max()) scale = float(b.abs().max()) or 1.0 engaged = len(set(state.calls)) - verdict = { - "tap_faithful": bool( - engaged == n_attn and diff <= rtol * scale and int(b.argmax()) == int(t.argmax()) - ), + argmax_same = int(b.argmax()) == int(t.argmax()) + return { + "tap_faithful": bool(engaged == n_attn and diff <= rtol * scale and argmax_same), "tap_layers_engaged": engaged, "tap_layers_expected": n_attn, "tap_max_logit_diff": round(diff, 6), + "tap_scale": round(scale, 6), + "tap_rel_diff": round(diff / scale, 6), + "tap_argmax_same": argmax_same, "tap_rtol": rtol, "native_attn_implementation": native[0] if native else None, } - cache[native] = verdict - return dict(verdict) class FidelityError(RuntimeError): diff --git a/evalrx/analyzers/_internals/edits.py b/evalrx/analyzers/_internals/edits.py index 9dd46102..7bee4303 100644 --- a/evalrx/analyzers/_internals/edits.py +++ b/evalrx/analyzers/_internals/edits.py @@ -10,7 +10,8 @@ :func:`media_flow_edit` applies both in one block, so an analyzer edits every layer of a hybrid stack (Qwen3.5) the same way it edits a dense one, and -:func:`require_edit_fidelity` checks both mechanisms before anything is reported. +:class:`FidelityGate` checks both mechanisms on every case before anything is +reported (:func:`require_edit_fidelity` is the one-input form). """ from __future__ import annotations @@ -64,9 +65,105 @@ def media_flow_edit( yield +class FidelityGate: + """Every case an analyzer reports on passes the edit-free self-checks, or it refuses. + + Before each case's measurement, :meth:`check` runs the tap check on the + softmax layers and, with ``linear=True``, the media-absent re-run check on + the linear layers, on THAT case's input. The first failing case raises + :class:`FidelityError` carrying the record so far, and the analyzer reports + nothing: keeping only the cases that happen to pass would select on + numerical noise (bf16 ``sdpa`` vs the eager-equivalent tap sits around the + tolerance and varies by input). :meth:`summary` is the analyzer's + ``tap_fidelity`` finding: the worst case per mechanism plus every check. + + ``linear=False`` for edits that touch softmax layers only (temperature, + relevance recording). + """ + + def __init__(self, model: "Model", *, rtol: float = 1e-2, analyzer: str = "media edit", + linear: bool = True) -> None: + stack = decoder_stack(torch_module(model, analyzer)) + self.model, self.rtol, self.analyzer = model, rtol, analyzer + self.n_softmax, self.n_linear = stack.n_softmax, stack.n_linear + self.check_linear = bool(linear and stack.n_linear) + self.checks: list[dict[str, Any]] = [] + self._tap_meta: dict[str, Any] = {} + + def check(self, case_id: Any, inputs: Any, media: Iterable[int] = (), *, + base: Any = None) -> "dict[str, Any]": + """Check one case; *base* = its native logits if the caller already has them.""" + record: dict[str, Any] = {"case": str(case_id)} + if self.n_softmax: + tap = check_fidelity(self.model, inputs, rtol=self.rtol, analyzer=self.analyzer, base=base) + self._tap_meta = {k: tap[k] for k in ("tap_layers_expected", "tap_rtol", + "native_attn_implementation")} + record.update({k: tap[k] for k in ("tap_faithful", "tap_layers_engaged", "tap_max_logit_diff", + "tap_rel_diff", "tap_argmax_same")}) + if self.check_linear: + lin = check_linear_fidelity(self.model, inputs, media, rtol=self.rtol, analyzer=self.analyzer) + record.update({k: lin[k] for k in ("linear_faithful", "linear_layers_engaged", + "linear_prefix_max_rel_diff")}) + record["faithful"] = bool(record.get("tap_faithful", True) and record.get("linear_faithful", True)) + self.checks.append(record) + if not record["faithful"]: + raise FidelityError( + f"{self.analyzer}: the edit-free self-check failed on case {record['case']} " + f"(check {len(self.checks)}; {record}); refusing to report edited-attention effects " + "for this batch. tap: engaged < expected layers means the architecture bypasses the " + "transformers attention interface, a logit diff means its attention is not " + "eager-equivalent (bf16 sdpa often is not: use attn_impl='eager'); linear: the " + "media-absent re-run must engage every linear layer and reproduce the outputs " + "before the first media token.", + self.summary(), + ) + return record + + def summary(self) -> "dict[str, Any]": + out: dict[str, Any] = { + "checked": "every analysed case", + "n_checked": len(self.checks), + "softmax_layers": self.n_softmax, + "linear_layers": self.n_linear, + "faithful": all(c["faithful"] for c in self.checks), + } + taps = [c for c in self.checks if "tap_faithful" in c] + if self.n_softmax: + worst = max(taps, key=lambda c: c["tap_rel_diff"], default=None) + out.update({ + "tap_faithful": all(c["tap_faithful"] for c in taps), + "tap_layers_engaged": min((c["tap_layers_engaged"] for c in taps), default=0), + "tap_max_logit_diff": max((c["tap_max_logit_diff"] for c in taps), default=None), + "tap_max_rel_diff": worst["tap_rel_diff"] if worst else None, + "tap_worst_case": worst["case"] if worst else None, + "tap_n_argmax_changed": sum(not c["tap_argmax_same"] for c in taps), + **self._tap_meta, + }) + lins = [c for c in self.checks if "linear_faithful" in c] + if self.check_linear: + worst = max(lins, key=lambda c: c["linear_prefix_max_rel_diff"], default=None) + out.update({ + "linear_faithful": all(c["linear_faithful"] for c in lins), + "linear_layers_engaged": min((c["linear_layers_engaged"] for c in lins), default=0), + "linear_layers_expected": self.n_linear, + "linear_prefix_max_rel_diff": worst["linear_prefix_max_rel_diff"] if worst else None, + "linear_worst_case": worst["case"] if worst else None, + "linear_rtol": self.rtol, + }) + failed = [c["case"] for c in self.checks if not c["faithful"]] + if failed: + out["failed_case"] = failed[0] + out["cases"] = list(self.checks) + return out + + def require_edit_fidelity(model: "Model", inputs: Any, media: Iterable[int], *, rtol: float = 1e-2, analyzer: str = "media edit") -> "dict[str, Any]": - """Verify every edit mechanism the stack needs; raise when one cannot be trusted.""" + """Verify every edit mechanism the stack needs on one input; raise when one cannot be trusted. + + Analyzers that report on a batch use :class:`FidelityGate`, which runs + this check on every case rather than on the first one. + """ stack = decoder_stack(torch_module(model, analyzer)) verdict: dict[str, Any] = {"softmax_layers": stack.n_softmax, "linear_layers": stack.n_linear} if stack.n_softmax: diff --git a/evalrx/analyzers/_internals/linear_mix.py b/evalrx/analyzers/_internals/linear_mix.py index 6cadcdd2..17d65c47 100644 --- a/evalrx/analyzers/_internals/linear_mix.py +++ b/evalrx/analyzers/_internals/linear_mix.py @@ -134,20 +134,17 @@ def check_linear_fidelity(model: "Model", inputs: Any, media: Iterable[int], *, The re-run calls ``module.forward`` on a shortened sequence without the cache/mask arguments the decoder passed; before the first media token it must reproduce the real outputs, or the re-run is not the same computation. - Cached on the module (one extra forward per model). + Measured on this input and media span every call (one forward), not cached. """ from evalrx.core.capability import Capability module = torch_module(model, analyzer) stack = decoder_stack(module) - cache = module.__dict__.setdefault("_evalrx_linear_fidelity", {}) - if "verdict" in cache: - return dict(cache["verdict"]) with linear_media_edit(model, media, weight=0.0, analyzer=analyzer) as state: model.forward(inputs, capture={Capability.LOGITS}) engaged = len(set(state.calls)) worst = max(state.prefix_rel_diff.values(), default=float("nan")) - verdict = { + return { "linear_faithful": bool(engaged == stack.n_linear and state.prefix_rel_diff and worst <= rtol), "linear_layers_engaged": engaged, @@ -155,8 +152,6 @@ def check_linear_fidelity(model: "Model", inputs: Any, media: Iterable[int], *, "linear_prefix_max_rel_diff": round(worst, 6), "linear_rtol": rtol, } - cache["verdict"] = verdict - return dict(verdict) def _torch_kernel(mod: Any) -> Callable: diff --git a/evalrx/analyzers/_internals/targets.py b/evalrx/analyzers/_internals/targets.py index e993f21a..2eb972d7 100644 --- a/evalrx/analyzers/_internals/targets.py +++ b/evalrx/analyzers/_internals/targets.py @@ -13,6 +13,18 @@ * ``"gold"`` — the gold answer's first token vs the strongest other token of the clean run. Needs ``case.expected`` and a tokenizer; a case without either is skipped (counted, never guessed). It answers "what supported the right answer". + +One answer has several first tokens: a BPE vocabulary holds ``"Yes"`` and +``" Yes"`` (and ``"yes"``) as different ids, and a model can split its +probability between them (Qwen3.5-0.8B on POPE gives " Yes" 0.80 and "Yes" +0.20 on one correct case). Comparing "Yes" with the strongest other token +then measures "Yes" against " Yes", not against "No". So the comparison +token is the strongest token outside the answer's surface forms +(:func:`answer_variants`: with or without a leading space, lower-case or +capitalised), the gold target is the surface form the clean run scores +highest, and :attr:`LogitMargin.variants` lists the forms for readers that +sum probabilities over them. Without a decoder to confirm that a form's first +token carries the answer's text, only the literal form is used. """ from __future__ import annotations @@ -20,6 +32,8 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional +from evalrx.analyzers._internals.words import decode_word + if TYPE_CHECKING: from evalrx.core.case import FailureCase from evalrx.core.model import Model @@ -29,12 +43,17 @@ @dataclass(frozen=True) class LogitMargin: - """``logits[position, positive] - logits[position, negative]``.""" + """``logits[position, positive] - logits[position, negative]``. + + ``variants``: token ids that start the same answer as ``positive`` (its + surface forms, ``positive`` included); ``negative`` is never one of them. + """ positive: int negative: int position: int = -1 kind: str = "prediction" + variants: tuple[int, ...] = () def __call__(self, logits: Any) -> Any: row = logits[self.position] @@ -73,6 +92,42 @@ def first_token_id(tokenizer: Any, text: str) -> Optional[int]: return int(ids[0]) if ids else None +def answer_variants(tokenizer: Any, text: "str | None") -> frozenset: + """First-token ids of the surface forms *text* can start an answer with. + + Forms: the text as given, lower-case and capitalised (for more than one + character, so the option letter "A" never takes in the article "a"), each + with and without a leading space. A form counts only when the decoder + shows its first token carries the start of the answer's text (a + character-level vocabulary would otherwise make the bare space a "form" of + every answer); with no decoder, only the literal form is returned. + """ + base = str(text or "").strip() + literal = first_token_id(tokenizer, base) + if literal is None: + return frozenset() + forms = {base} | ({base.lower(), base[:1].upper() + base[1:]} if len(base) > 1 else set()) + ids = {literal} + for form in forms: + for spelled in (form, " " + form): + tid = first_token_id(tokenizer, spelled) + piece = decode_word(tokenizer, tid) if tid is not None else None + if piece is not None and piece.strip() and form.startswith(piece.strip()): + ids.add(int(tid)) + return frozenset(ids) + + +def _strongest_outside(row: Any, ids: "frozenset", positive: int) -> int: + """The strongest token that is not a form of the answer (only *positive* + is excluded when the forms would cover the whole vocabulary).""" + masked = sorted(i for i in ids if i < row.numel()) + if len(masked) >= row.numel(): + masked = [positive] + others = row.clone() + others[masked] = float("-inf") + return int(others.argmax()) + + def build_margin( target: str, clean_logits: Any, @@ -82,25 +137,27 @@ def build_margin( position: int = -1, ) -> "tuple[LogitMargin | None, str]": """``(margin, "")`` or ``(None, skip_reason)``.""" - import torch - if target not in TARGETS: raise ValueError(f"target must be one of {TARGETS}, got {target!r}") row = clean_logits[position].detach().float() if row.numel() < 2: return None, "vocab_too_small" - if target == "prediction": - top2 = torch.topk(row, 2).indices - return LogitMargin(int(top2[0]), int(top2[1]), position, "prediction"), "" - from evalrx.analyzers._internals.access import tokenizer_of + tokenizer = tokenizer_of(model) if model is not None else None + if target == "prediction": + top1 = int(row.argmax()) + word = decode_word(tokenizer, top1) if tokenizer is not None else None + variants = (answer_variants(tokenizer, word) if word and word.strip() else frozenset()) | {top1} + return LogitMargin(top1, _strongest_outside(row, variants, top1), position, "prediction", + tuple(sorted(variants))), "" + gold = gold_text(getattr(case, "expected", None)) if gold is None: return None, "no_gold" - tid = first_token_id(tokenizer_of(model) if model is not None else None, gold) - if tid is None or tid >= row.numel(): + variants = frozenset(t for t in answer_variants(tokenizer, gold) if t < row.numel()) + if not variants: return None, "gold_untokenizable" - others = row.clone() - others[tid] = float("-inf") - return LogitMargin(tid, int(others.argmax()), position, "gold"), "" + # the surface form this run gives the gold answer, fixed on the clean logits + tid = max(variants, key=lambda t: float(row[t])) + return LogitMargin(tid, _strongest_outside(row, variants, tid), position, "gold", tuple(sorted(variants))), "" diff --git a/evalrx/analyzers/_internals/words.py b/evalrx/analyzers/_internals/words.py new file mode 100644 index 00000000..9af57645 --- /dev/null +++ b/evalrx/analyzers/_internals/words.py @@ -0,0 +1,64 @@ +"""Decoded tokens as content words, and the prompt words specific to one case. + +The lenses that read media tokens as words (``embed_lens``, ``patchscope``) +ask whether a case's own question word shows up there. Which prompt words are +the case's own is told apart from the task's template by the batch itself: a +word found in at most ``max_share`` of the distinct prompts is specific +("snowboard"), one found in most of them is template ("image", "answer"). +""" + +from __future__ import annotations + +from typing import Any + +# Function words the decoder emits for almost any state; kept out of word tallies. +STOP = frozenset("""a an and are as at be but by for from has have in into is it its of on or +that the their there this to was were with""".split()) + + +def decode_word(tokenizer: Any, token_id: int) -> "str | None": + """``tokenizer.decode([token_id])``, or ``None`` when there is no decoder (never a guess).""" + try: + text = tokenizer.decode([int(token_id)]) + except Exception: # noqa: BLE001 - no decoder -> no word + return None + return text if isinstance(text, str) else None + + +def content_word(tokenizer: Any, token_id: int, special: "set[str]") -> "str | None": + """The token as a lower-case content word, or ``None`` (punctuation, function word, special).""" + word = decode_word(tokenizer, token_id) + if word is None or word in special: + return None + key = word.strip().lower() + return key if key.isalpha() and len(key) >= 2 and key not in STOP else None + + +def specific_words(prompt_words: "dict[str, tuple[Any, set[str]]]", *, max_share: float = 0.5, + min_prompts: int = 3) -> "tuple[dict[str, set[str]], bool]": + """Each case's prompt words found in at most *max_share* of the distinct prompts. + + Args: + prompt_words: ``{case_id: (prompt_key, content_words)}``. Cases with the + same ``prompt_key`` (the question asked verbatim of several + media) count as one prompt, so a repeated question does + not make its own words look like template. + max_share: largest share of the distinct prompts a specific word may appear in. + min_prompts: fewest distinct prompts the template can be inferred from. + + Returns: + ``({case_id: specific_words}, inferred)``; below *min_prompts* nothing can + be told apart, so every set is empty and ``inferred`` is ``False``. + """ + distinct: dict[Any, set[str]] = {} + for key, words in prompt_words.values(): + distinct.setdefault(key, set(words)) + if len(distinct) < min_prompts: + return {cid: set() for cid in prompt_words}, False + share: dict[str, int] = {} + for words in distinct.values(): + for word in words: + share[word] = share.get(word, 0) + 1 + limit = max_share * len(distinct) + return {cid: {w for w in words if share.get(w, 0) <= limit} + for cid, (_, words) in prompt_words.items()}, True diff --git a/evalrx/analyzers/attribution/generic_attn.py b/evalrx/analyzers/attribution/generic_attn.py index 18dc69cd..cf734add 100755 --- a/evalrx/analyzers/attribution/generic_attn.py +++ b/evalrx/analyzers/attribution/generic_attn.py @@ -59,7 +59,9 @@ class GenericAttentionExplainability(Analyzer): top_k: relevant tokens listed for the first case. fidelity_rtol: tolerance of the edit-free attention tap vs native logits. max_cases: label-stratified cap; 0 (the default) = every case. - Cost: one forward + one backward per case. + Cost: one forward + one backward per case, plus a + native and a tapped forward for the per-case edit-free + self-check when the stack has softmax layers. """ name = "generic_attention" @@ -97,7 +99,8 @@ def _run(self, model: "Model", cases: "CaseBatch"): media_positions, torch_module, ) - from evalrx.analyzers._internals.attn_tap import attention_tap, require_fidelity + from evalrx.analyzers._internals.attn_tap import attention_tap + from evalrx.analyzers._internals.edits import FidelityGate from evalrx.analyzers._internals.linear_mix import delta_rule_relevance from evalrx.analyzers._internals.maps import ( SpatialMapResult, @@ -116,13 +119,11 @@ def _run(self, model: "Model", cases: "CaseBatch"): per_case: list[dict[str, Any]] = [] per_case_maps: dict[str, Any] = {} skipped: Counter = Counter() - fidelity: "dict | None" = None + # the tap only records here; the linear layers' relevance has no media re-run to check + gate = FidelityGate(model, rtol=self.fidelity_rtol, analyzer=self.name, linear=False) first: "dict[str, Any] | None" = None for case in cases.stratified_head(self.max_cases): - if fidelity is None: - fidelity = (require_fidelity(model, case.inputs, rtol=self.fidelity_rtol, - analyzer=self.name) if stack.n_softmax else {}) - fidelity.update(softmax_layers=stack.n_softmax, linear_layers=stack.n_linear) + gate.check(case.id, case.inputs) abar: dict[int, Any] = {} recorded: dict[int, Any] = {} @@ -208,7 +209,7 @@ def hook(grad: Any, layer: int = layer, held: Any = held) -> None: "skip_reasons": dict(skipped), "n_layers": n_layers, "target": self.target, - "tap_fidelity": fidelity, + "tap_fidelity": gate.summary(), "top_relevant_tokens": first["top"] if first else [], "mean_media_share": round(sum(shares) / len(shares), 4) if shares else None, "per_case": per_case, diff --git a/evalrx/analyzers/lens/embed_lens.py b/evalrx/analyzers/lens/embed_lens.py index 3b994c32..3b18b9ac 100644 --- a/evalrx/analyzers/lens/embed_lens.py +++ b/evalrx/analyzers/lens/embed_lens.py @@ -23,7 +23,10 @@ And one grounding readout per case: each content word of the prompt against the media tokens — the best cosine similarity any media token reaches to that word's embedding. A question about an object the image does contain should -find a media token close to the object's word. +find a media token close to the object's word. ``el_query_sim`` keeps only the +case's own question words — prompt words found in at most half of the batch's +distinct prompts — so a template word ("image", "answer") cannot be the best +match on every case. The paper reads the INPUT (``layer=0``, the default). Whether a model's projector writes into vocabulary space there is itself the finding: on a @@ -46,6 +49,7 @@ from collections import Counter from typing import TYPE_CHECKING, Any +from evalrx.analyzers._internals.words import content_word, decode_word, specific_words from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer @@ -56,17 +60,6 @@ from evalrx.core.model import Model -def content_word(tokenizer: Any, token_id: int, special: "set[str]") -> "str | None": - """The token as a lower-case content word, or ``None`` (punctuation, function word, special).""" - from evalrx.analyzers.lens.patchscope import _STOP, _word - - word = _word(tokenizer, token_id) - if word is None or word in special: - return None - key = word.strip().lower() - return key if key.isalpha() and len(key) >= 2 and key not in _STOP else None - - @register_analyzer("embed_lens") class EmbedLensAnalyzer(Analyzer): """Nearest vocabulary words of every media token at the decoder input, per case. @@ -102,6 +95,7 @@ class EmbedLensAnalyzer(Analyzer): "el_frac_high_norm": ("High-norm tokens", "Share of media tokens with norm ≥ norm_ratio × the image's median token norm (sink-like)."), "el_prompt_best_word": ("Best-grounded prompt word", "The prompt content word some media token is closest to."), "el_prompt_best_sim": ("Its grounding similarity", "Cosine similarity of that word's embedding to its closest media token."), + "el_query_sim": ("Question-word grounding", "Best cosine similarity of the case's own question words (not the task template's) to any media token."), } def __init__(self, layer: "int | float" = 0, top_k: int = 5, recurring_frac: float = 0.5, @@ -126,7 +120,6 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: ) from evalrx.analyzers._internals.residual import residual_hooks from evalrx.analyzers.attention.relative_attn import resolve_attention_layer - from evalrx.analyzers.lens.patchscope import _word from evalrx.core.model import CaptureSpec module = torch_module(model, self.name) @@ -161,6 +154,7 @@ def nearest(x: Any) -> "tuple[Any, Any]": rows: list[dict[str, Any]] = [] per_token: dict[str, dict[str, Any]] = {} prompt_sims: dict[str, dict[str, float]] = {} + prompt_words: dict[str, tuple[Any, set[str]]] = {} images_with: Counter = Counter() # top-1 id -> number of DISTINCT images it is top-1 in seen_media: set = set() # fingerprints of the media already counted skipped: Counter = Counter() @@ -207,6 +201,8 @@ def nearest(x: Any) -> "tuple[Any, Any]": "high_norm": [bool(v >= self.norm_ratio * median) for v in norms.tolist()], } prompt_sims[case.id] = grounding + prompt_words[case.id] = (tuple(t for p, t in enumerate(trace.token_ids) if p not in media_set), + set(words)) row: dict[str, Any] = { "sample_id": case.id, "el_n_media_tokens": len(media), @@ -223,10 +219,16 @@ def nearest(x: Any) -> "tuple[Any, Any]": if not rows: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") n_cases, n_images = len(rows), len(seen_media) + query, query_inferred = specific_words(prompt_words) + for row in rows: + sims = {w: s for w, s in prompt_sims[row["sample_id"]].items() if w in query[row["sample_id"]]} + if sims: + row["el_query_word"] = max(sims, key=sims.get) + row["el_query_sim"] = sims[row["el_query_word"]] recurring: set = set() if n_images >= self.min_images: recurring = {tid for tid, count in images_with.items() if count >= self.recurring_frac * n_images} - specific_words: Counter = Counter() + specific_counts: Counter = Counter() recurring_mass: Counter = Counter() total_tokens = 0 for row in rows: @@ -243,10 +245,10 @@ def nearest(x: Any) -> "tuple[Any, Any]": elif not h and tokenizer is not None: word = content_word(tokenizer, tid, special) if word is not None: - specific_words[word] += 1 + specific_counts[word] += 1 def label(tid: int) -> str: - word = _word(tokenizer, tid) if tokenizer is not None else None + word = decode_word(tokenizer, tid) if tokenizer is not None else None return word if word is not None else str(tid) mean = lambda key: round(sum(r[key] for r in rows) / n_cases, 4) # noqa: E731 @@ -268,7 +270,8 @@ def label(tid: int) -> str: "mean_frac_specific": mean("el_frac_specific"), "mean_frac_recurring": mean("el_frac_recurring"), "mean_frac_high_norm": mean("el_frac_high_norm"), - "specific_word_counts": specific_words.most_common(20), + "specific_word_counts": specific_counts.most_common(20), + "query_words_inferred": query_inferred, "per_case": rows, "_caveat": ( f"Nearest neighbours by cosine similarity in the input-embedding table, read at the " @@ -280,5 +283,6 @@ def label(tid: int) -> str: ), } return Result(analyzer=self.name, model=repr(model), cases=cases, - artifacts={"tokens": per_token, "prompt_sims": prompt_sims}, + artifacts={"tokens": per_token, "prompt_sims": prompt_sims, + "query_words": {cid: sorted(w) for cid, w in query.items()}}, findings=findings) diff --git a/evalrx/analyzers/lens/patchscope.py b/evalrx/analyzers/lens/patchscope.py index 27edef1b..7b054709 100644 --- a/evalrx/analyzers/lens/patchscope.py +++ b/evalrx/analyzers/lens/patchscope.py @@ -13,8 +13,9 @@ * ``last`` (always) — the final prompt position, where the answer is formed, at every layer (or ``n_points`` of them): the probability the decoder gives - the target token (the model's own answer, or the gold one with - ``target="gold"``) and whether it ranks first. The depth where the answer + the target answer (the model's own, or the gold one with ``target="gold"``), + summed over its surface forms (``"Yes"`` / ``" Yes"``, see + :mod:`~evalrx.analyzers._internals.targets`), and whether a form of it ranks first. The depth where the answer first ranks first; the depth where it peaks; and the gap between that peak and what the model finally outputs — positive = the answer was readable more confidently mid-stack than at the output (with ``target="gold"`` on failing @@ -22,10 +23,15 @@ * ``media`` (``media_layers > 0``) — every image / audio token at a few evenly spaced layers above the embedding, decoded the same way: the word the model's own machinery reads off each media token ("what it sees"), kept as a - per-token word map and tallied (content words only) across cases. + per-token word map and tallied (content words only) across cases. Per case, + ``ps_media_query_hits`` counts the media readouts that are one of the case's + own question words — prompt words in at most half of the batch's distinct + prompts, so template words ("image", "answer") never count. -The patch is checked once per model: patching a target position with the -target's own residual must leave its logits unchanged. +The patch is checked once per run, on the fixed decoding prompt (it does not +depend on the case): patching the placeholder with its own residual must leave +its logits unchanged, else :class:`~evalrx.analyzers._internals.attn_tap.FidelityError`. +The verdict is reported as ``patch_fidelity``. References: - Patchscopes: A Unifying Framework for Inspecting Hidden Representations of @@ -38,6 +44,7 @@ from collections import Counter from typing import TYPE_CHECKING, Any +from evalrx.analyzers._internals.words import STOP, content_word, decode_word, specific_words from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer @@ -48,17 +55,7 @@ from evalrx.core.model import Model IDENTITY_PROMPT = "cat -> cat; 1135 -> 1135; hello -> hello; ?" -# Function words the decoder emits for almost any state; kept out of the word tally. -_STOP = frozenset("""a an and are as at be but by for from has have in into is it its of on or -that the their there this to was were with""".split()) - - -def _word(tokenizer: Any, token_id: int) -> "str | None": - try: - text = tokenizer.decode([int(token_id)]) - except Exception: # noqa: BLE001 - no decoder → no word, never a guess - return None - return text if isinstance(text, str) else None +_STOP, _word = STOP, decode_word # the names embed_lens and older callers import @register_analyzer("patchscope") @@ -88,12 +85,14 @@ class PatchscopeAnalyzer(Analyzer): requires = frozenset({Capability.HIDDEN_STATES, Capability.LOGITS}) applies_to_modalities = frozenset({"text", "image", "video", "audio"}) signal_docs = { - "ps_final_prob": ("Answer prob. at the output", "Probability the model itself gives the target token."), - "ps_first_depth_frac": ("Answer readable from (depth)", "First relative depth at which the Patchscope readout of the answer position ranks the target token first (1.0 = never before the last layer)."), - "ps_peak_prob": ("Peak readable answer prob.", "Highest probability the Patchscope readout gives the target token at any depth."), + "ps_final_prob": ("Answer prob. at the output", "Probability the model itself gives the target answer (summed over its surface forms, e.g. 'Yes' and ' Yes')."), + "ps_first_depth_frac": ("Answer readable from (depth)", "First relative depth at which the Patchscope readout of the answer position ranks a form of the target answer first (1.0 = never before the last layer)."), + "ps_peak_prob": ("Peak readable answer prob.", "Highest probability the Patchscope readout gives the target answer at any depth."), "ps_peak_depth_frac": ("Peak readout depth", "Relative depth of that peak."), - "ps_late_drop": ("Readable answer lost late", "Peak readout probability minus the model's final probability of the target token; positive = more confident mid-stack than at the output (suppressed late)."), + "ps_late_drop": ("Readable answer lost late", "Peak readout probability minus the model's final probability of the target answer; positive = more confident mid-stack than at the output (suppressed late)."), "ps_agree_mid": ("Mid-stack readout agrees", "Share of the middle third of the layers whose readout ranks the model's final answer first."), + "ps_media_query_hits": ("Question word read on media", "Media-token readouts (over the media layers) that are one of this case's own question words."), + "ps_media_query_share": ("Share of media read as the question word", "Those readouts as a share of all media-token readouts."), } def __init__(self, target: str = "prediction", target_prompt: str = IDENTITY_PROMPT, @@ -113,7 +112,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: torch_module, ) from evalrx.analyzers._internals.residual import batched_patch, residual_hooks - from evalrx.analyzers._internals.targets import build_margin + from evalrx.analyzers._internals.targets import answer_variants, build_margin from evalrx.core.model import CaptureSpec module = torch_module(model, self.name) @@ -165,14 +164,22 @@ def grab(mod, args, kwargs): handle.remove() patched = decode([(check_layer, own["h"])])[0] patch_diff = float((patched - plain).abs().max()) - if patch_diff > 1e-3 * max(1.0, float(plain.abs().max())): - raise RuntimeError(f"{self.name}: re-writing a residual with itself changed the logits " - f"by {patch_diff:.3g}; the patch does not reach the layer input") + scale = max(1.0, float(plain.abs().max())) + fidelity = {"faithful": patch_diff <= 1e-3 * scale, "max_diff": round(patch_diff, 6), + "rtol": 1e-3, "scale": round(scale, 4), "layer": check_layer, + "scope": "once per run: the decoding prompt is fixed, so the check does not " + "depend on the case"} + if not fidelity["faithful"]: + from evalrx.analyzers._internals.attn_tap import FidelityError + + raise FidelityError(f"{self.name}: re-writing a residual with itself changed the logits " + f"by {patch_diff:.3g}; the patch does not reach the layer input", fidelity) per_case: list[dict[str, Any]] = [] curves: dict[str, dict[str, Any]] = {} media_words: dict[str, dict[int, list]] = {} word_counts: Counter = Counter() + prompt_words: dict[str, tuple[Any, set[str]]] = {} skipped: Counter = Counter() for case in cases.stratified_head(self.max_cases): with torch.no_grad(), residual_hooks(model, capture=dict.fromkeys(set(layers) | set(media_at)), @@ -180,6 +187,7 @@ def grab(mod, args, kwargs): trace = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) last = trace.seq_len - 1 _, media = media_positions(trace) if media_at else (None, []) + trace_ids = list(trace.token_ids or []) logits = trace.require(Capability.LOGITS)[-1:] margin, why = build_margin(self.target, logits, model=model, case=case) if margin is None: @@ -187,31 +195,39 @@ def grab(mod, args, kwargs): continue final_probs = torch.softmax(logits[-1].float(), -1) final_top = int(final_probs.argmax()) - target_id = margin.positive + # the answer in all its surface forms ("Yes" / " Yes"): probabilities + # summed, ranks read as "some form of it is first" + forms = list(margin.variants or (margin.positive,)) + final_forms = set(answer_variants(tokenizer, decode_word(tokenizer, final_top))) | {final_top} del trace states = res.captured # layer -> (seq, dim) readout = torch.softmax(decode([(layer, states[layer][last]) for layer in layers]), -1) - p_target = readout[:, target_id].tolist() + p_target = readout[:, forms].sum(-1).tolist() top1 = readout.argmax(-1).tolist() peak = max(range(len(layers)), key=lambda i: p_target[i]) - p_final = float(final_probs[target_id]) + p_final = float(final_probs[forms].sum()) row: dict[str, Any] = { "sample_id": case.id, "ps_final_prob": round(p_final, 4), "ps_first_depth_frac": round(next( - (depth[layer] for layer, t in zip(layers, top1) if t == target_id), 1.0), 4), + (depth[layer] for layer, t in zip(layers, top1) if t in forms), 1.0), 4), "ps_peak_prob": round(p_target[peak], 4), "ps_peak_depth_frac": round(depth[layers[peak]], 4), "ps_late_drop": round(p_target[peak] - p_final, 4), "ps_agree_mid": round( - sum(top1[layers.index(layer)] == final_top for layer in mid) / len(mid), 4), + sum(top1[layers.index(layer)] in final_forms for layer in mid) / len(mid), 4), } per_case.append(row) curves[case.id] = {"p_target": [round(p, 4) for p in p_target], - "top1": [_word(tokenizer, t) or str(t) for t in top1]} + "top1": [_word(tokenizer, t) or str(t) for t in top1], + "answer_forms": forms} if media_at and media: + media_set = set(media) + prompt = [tid for pos, tid in enumerate(trace_ids) if pos not in media_set] + prompt_words[case.id] = (tuple(prompt), { + w for w in (content_word(tokenizer, t, special) for t in prompt) if w is not None}) rows = [(layer, states[layer][pos]) for layer in media_at for pos in media] ids = decode(rows).argmax(-1).tolist() words: dict[int, list] = {} @@ -226,6 +242,17 @@ def grab(mod, args, kwargs): if not per_case: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") + query, query_inferred = specific_words(prompt_words) + for row in per_case: + words = media_words.get(row["sample_id"]) + own = query.get(row["sample_id"]) + if words is None or not query_inferred: + continue + decoded = [(w or "").strip().lower() for layer_words in words.values() for w in layer_words] + found = sorted({w for w in decoded if w in own}) + row["ps_media_query_hits"] = sum(1 for w in decoded if w in own) + row["ps_media_query_share"] = round(row["ps_media_query_hits"] / max(1, len(decoded)), 4) + row["ps_media_query_found"] = found label_of = {c.id: getattr(getattr(c, "label", None), "value", None) for c in cases} def mean_curve(label: str) -> "list[float] | None": @@ -244,6 +271,7 @@ def mean_curve(label: str) -> "list[float] | None": "target": self.target, "target_prompt": self.target_prompt, "patch_check_max_diff": round(patch_diff, 6), + "patch_fidelity": fidelity, "mean_late_drop": round(sum(r["ps_late_drop"] for r in per_case) / n, 4), "mean_first_depth_frac": round(sum(r["ps_first_depth_frac"] for r in per_case) / n, 4), "mean_p_target_curves": {label: mean_curve(label) for label in ("fail", "pass") @@ -259,6 +287,8 @@ def mean_curve(label: str) -> "list[float] | None": if media_at: findings["media_layers_read"] = media_at findings["media_word_counts"] = word_counts.most_common(20) + findings["query_words_inferred"] = query_inferred return Result(analyzer=self.name, model=repr(model), cases=cases, - artifacts={"readout_curves": curves, "media_words": media_words}, + artifacts={"readout_curves": curves, "media_words": media_words, + "query_words": {cid: sorted(w) for cid, w in query.items()}}, findings=findings) diff --git a/evalrx/analyzers/patching/attention_knockout.py b/evalrx/analyzers/patching/attention_knockout.py index fedf1030..19c9eb0d 100644 --- a/evalrx/analyzers/patching/attention_knockout.py +++ b/evalrx/analyzers/patching/attention_knockout.py @@ -67,7 +67,9 @@ class AttentionKnockoutAnalyzer(Analyzer): linear-layer re-run vs the real prefix outputs (relative to the largest value) before the analyzer refuses. max_cases: label-stratified cap; 0 (the default) = every case. - Cost: 5 logits-only forwards per case. + Cost: 5 logits-only forwards per case, plus the per-case + edit-free self-check (1 tapped forward; +1 media-absent + re-run on a hybrid stack). """ name = "attention_knockout" @@ -102,7 +104,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: media_positions, torch_module, ) - from evalrx.analyzers._internals.edits import media_flow_edit, require_edit_fidelity + from evalrx.analyzers._internals.edits import FidelityGate, media_flow_edit from evalrx.analyzers._internals.targets import build_margin from evalrx.core.model import CaptureSpec @@ -118,7 +120,7 @@ def last_logits(inputs: Any) -> Any: per_case: list[dict[str, Any]] = [] skipped: Counter = Counter() slots: Counter = Counter() - fidelity: "dict | None" = None + gate = FidelityGate(model, rtol=self.fidelity_rtol, analyzer=self.name) for case in cases.stratified_head(self.max_cases): clean = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) slot, media = media_positions(clean) @@ -130,9 +132,7 @@ def last_logits(inputs: Any) -> Any: if margin is None: skipped[why] += 1 continue - if fidelity is None: - fidelity = require_edit_fidelity(model, case.inputs, media, - rtol=self.fidelity_rtol, analyzer=self.name) + gate.check(case.id, case.inputs, media, base=logits) media_set = set(media) queries = ([clean.seq_len - 1] if self.queries == "last" else [i for i in range(clean.seq_len) if i not in media_set]) @@ -171,7 +171,7 @@ def cut(layers: "list[int] | None") -> Any: "target": self.target, "queries": self.queries, "layer_kinds": {"softmax": stack.n_softmax, "linear": stack.n_linear}, - "tap_fidelity": fidelity, + "tap_fidelity": gate.summary(), "mean_delta_full": round(sum(r["ko_delta_full"] for r in per_case) / n, 4), "frac_flips_top1": round(sum(bool(r["ko_flips_top1"]) for r in per_case) / n, 4), "per_case": per_case, diff --git a/evalrx/analyzers/patching/attention_sensitivity.py b/evalrx/analyzers/patching/attention_sensitivity.py index 128956c5..da8effdb 100644 --- a/evalrx/analyzers/patching/attention_sensitivity.py +++ b/evalrx/analyzers/patching/attention_sensitivity.py @@ -59,7 +59,9 @@ class AttentionSensitivityAnalyzer(Analyzer): target: ``"prediction"`` or ``"gold"``. fidelity_rtol: tolerance of the edit-free attention tap vs native logits. max_cases: label-stratified cap; 0 (the default) = every case. - Cost: 3 logits-only forwards per case. + Cost: 3 logits-only forwards per case, plus the per-case + edit-free self-check (1 tapped forward; +1 media-absent + re-run on a hybrid stack). """ name = "attention_sensitivity" @@ -95,7 +97,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: media_positions, torch_module, ) - from evalrx.analyzers._internals.edits import media_flow_edit, require_edit_fidelity + from evalrx.analyzers._internals.edits import FidelityGate, media_flow_edit from evalrx.analyzers._internals.targets import build_margin from evalrx.analyzers.patching.attention_knockout import layer_bands from evalrx.core.model import CaptureSpec @@ -108,7 +110,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: per_case: list[dict[str, Any]] = [] skipped: Counter = Counter() - fidelity: "dict | None" = None + gate = FidelityGate(model, rtol=self.fidelity_rtol, analyzer=self.name) for case in cases.stratified_head(self.max_cases): clean = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) _, media = media_positions(clean) @@ -120,9 +122,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: if margin is None: skipped[why] += 1 continue - if fidelity is None: - fidelity = require_edit_fidelity(model, case.inputs, media, - rtol=self.fidelity_rtol, analyzer=self.name) + gate.check(case.id, case.inputs, media, base=logits) media_set = set(media) queries = [i for i in range(clean.seq_len) if i not in media_set] top1 = int(logits[-1].argmax()) @@ -158,7 +158,7 @@ def scaled(weight: float) -> Any: "weights": [self.down, self.up], "target": self.target, "layer_kinds": {"softmax": stack.n_softmax, "linear": stack.n_linear}, - "tap_fidelity": fidelity, + "tap_fidelity": gate.summary(), "mean_slope": round(sum(r["rw_slope"] for r in per_case) / n, 4), "frac_negative_slope": round(sum(r["rw_slope"] < 0 for r in per_case) / n, 4), "per_case": per_case, diff --git a/evalrx/analyzers/patching/attention_temperature.py b/evalrx/analyzers/patching/attention_temperature.py index 347a9042..45527bca 100644 --- a/evalrx/analyzers/patching/attention_temperature.py +++ b/evalrx/analyzers/patching/attention_temperature.py @@ -62,7 +62,8 @@ class AttentionTemperatureAnalyzer(Analyzer): target: ``"prediction"`` or ``"gold"``. fidelity_rtol: tolerance of the edit-free attention tap vs native logits. max_cases: label-stratified cap; 0 (the default) = every case. - Cost: 3 logits-only forwards per case. + Cost: 3 logits-only forwards per case, plus 1 tapped + forward for the per-case edit-free self-check. """ name = "attention_temperature" @@ -104,11 +105,8 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: media_positions, torch_module, ) - from evalrx.analyzers._internals.attn_tap import ( - attention_tap, - require_fidelity, - temperature, - ) + from evalrx.analyzers._internals.attn_tap import attention_tap, temperature + from evalrx.analyzers._internals.edits import FidelityGate from evalrx.analyzers._internals.targets import build_margin from evalrx.analyzers.patching.attention_knockout import layer_bands from evalrx.core.model import CaptureSpec @@ -125,7 +123,8 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: per_case: list[dict[str, Any]] = [] skipped: Counter = Counter() - fidelity: "dict | None" = None + # temperature edits act on softmax layers only: no linear re-run to check + gate = FidelityGate(model, rtol=self.fidelity_rtol, analyzer=self.name, linear=False) for case in cases.stratified_head(self.max_cases): probe = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) _, media = media_positions(probe) @@ -133,13 +132,14 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: skipped["no_media_tokens"] += 1 continue seq_len = probe.seq_len + native = probe.require(Capability.LOGITS)[-1:].float() del probe queries = list(range(max(media) + 1, seq_len)) if not queries: skipped["no_text_after_media"] += 1 continue - if fidelity is None: - fidelity = require_fidelity(model, case.inputs, rtol=self.fidelity_rtol, analyzer=self.name) + gate.check(case.id, case.inputs, base=native) + del native keys = media if self.scope == "within" else list(range(seq_len)) entropies: list[float] = [] @@ -197,7 +197,7 @@ def tempered(value: float) -> Any: "target": self.target, "tt_edited_layers": len(layers), "layer_kinds": {"softmax": stack.n_softmax, "linear": stack.n_linear}, - "tap_fidelity": fidelity, + "tap_fidelity": gate.summary(), "mean_slope": round(sum(r["tt_slope"] for r in per_case) / n, 4), "frac_negative_slope": round(sum(r["tt_slope"] < 0 for r in per_case) / n, 4), "frac_flips_sharp": round(sum(r["tt_flips_sharp"] for r in per_case) / n, 4), diff --git a/evalrx/analyzers/perturbation/modality_ablation.py b/evalrx/analyzers/perturbation/modality_ablation.py index f7d37f7c..f5c242f5 100644 --- a/evalrx/analyzers/perturbation/modality_ablation.py +++ b/evalrx/analyzers/perturbation/modality_ablation.py @@ -24,6 +24,19 @@ DIFFERENT media: the donor is matched on content, not on case id, and every row records which case it came from. +An unchanged answer after a swap is only evidence when the donor's media +should have changed it. On open-answer tasks a different chart or clip almost +always does; on yes/no and few-option tasks it often does not (a random COCO +image usually lacks the asked-about object too, so "No" stays correct). +``donor_rule="counterfactual"`` therefore prefers a donor where the dataset +asks the SAME question (identical prompt) about different media and its gold +answer differs from the model's own unablated answer: answering correctly on +the donor media then requires a different answer. (Relative to the model's +answer, not the case's gold: on a failed case the two differ, and a donor +whose gold equals the wrong answer makes "unchanged" the correct behaviour.) +When no such case exists it falls back to a content-different donor and says +so per row. + Reported as reliance, never as correctness. ``ungrounded_rate_`` is the share of probed cases whose answer survived the ablation; ``by_strategy`` carries the paired per-case correctness that M2's McNemar reads, which is what makes this @@ -49,6 +62,22 @@ from evalrx.core.model import Model BASELINE = "baseline" +DONOR_RULES = ("content", "counterfactual") + + +def _prompt_key(case: Any) -> str: + return " ".join(str(getattr(case.inputs, "prompt", "") or "").split()).lower() + + +def _gold_key(case: Any) -> "str | None": + """The case's gold answer under the same normalisation the answers get.""" + meta = getattr(case, "metadata", None) or {} + gold = meta.get("gold", getattr(case, "expected", None)) + if gold is None: + return None + if isinstance(gold, (list, tuple)): + gold = "|".join(str(g) for g in gold) + return _norm_answer(str(gold)) def _media_key(media: Any) -> Any: @@ -94,6 +123,16 @@ class ModalityAblationAnalyzer(Analyzer): 'ablation_audio_answer': 'Swap mode: the answer with the audio swapped (or dropped).', 'ablation_image_answer': 'Swap mode: the answer with the image swapped (or dropped).', 'ablation_video_answer': 'Swap mode: the answer with the video swapped (or dropped).', + 'ablation_audio_donor_kind': "Swap mode: 'counterfactual' (same question, different audio, gold differs from the model's answer), 'content' (different audio only) or None (dropped).", + 'ablation_image_donor_kind': "Swap mode: 'counterfactual' (same question, different image, gold differs from the model's answer), 'content' (different image only) or None (dropped).", + 'ablation_video_donor_kind': "Swap mode: 'counterfactual' (same question, different video, gold differs from the model's answer), 'content' (different video only) or None (dropped).", + 'ablation_audio_donor_expected': "Counterfactual donor: the gold answer of the same question on the donor's audio.", + 'ablation_image_donor_expected': "Counterfactual donor: the gold answer of the same question on the donor's image.", + 'ablation_video_donor_expected': "Counterfactual donor: the gold answer of the same question on the donor's video.", + 'n_counterfactual_audio': 'Swap mode: cases whose audio donor is a counterfactual (the answer has to change).', + 'n_counterfactual_image': 'Swap mode: cases whose image donor is a counterfactual (the answer has to change).', + 'n_counterfactual_video': 'Swap mode: cases whose video donor is a counterfactual (the answer has to change).', + 'donor_rule': "Swap mode: how donors were chosen ('content' or 'counterfactual').", 'ablation_audio_donor': "Swap mode: the case whose audio was put in (None = no different audio, so it was dropped).", 'ablation_audio_is_swap': "The audio was replaced with another case's rather than removed.", 'ablation_image_donor': "Swap mode: the case whose image was put in (None = no different image, so it was dropped).", @@ -129,22 +168,35 @@ def __init__( slots: "tuple[str, ...] | None" = None, score_fn: Optional[Callable[["FailureCase", str], Optional[bool]]] = None, max_cases: int = 0, + donor_rule: str = "content", + donor_pool: "CaseBatch | None" = None, ) -> None: """ Args: - mode: ``"drop"`` (remove the slot) or ``"swap"`` (substitute - another case's media). ``swap`` falls back to ``drop`` - per-slot when fewer than two cases fill it. - slots: Restrict to these slots; ``None`` probes every filled one. - score_fn: ``(case, answer) -> bool | None`` for the paired - correctness table. Defaults to the prompt-contrast rubric - scorer; ``None`` verdicts are simply not tabulated. - max_cases: Cap on cases (cost = 1 + n_filled_slots generations each); - 0 (the default) = every case. + mode: ``"drop"`` (remove the slot) or ``"swap"`` (substitute + another case's media). ``swap`` falls back to ``drop`` + per-slot when no eligible case holds different media. + slots: Restrict to these slots; ``None`` probes every filled one. + score_fn: ``(case, answer) -> bool | None`` for the paired + correctness table. Defaults to the prompt-contrast rubric + scorer; ``None`` verdicts are simply not tabulated. + max_cases: Cap on cases (cost = 1 + n_filled_slots generations each); + 0 (the default) = every case. + donor_rule: swap only — ``"content"``: the next case whose media + differs; ``"counterfactual"``: first a case asking the + same prompt about different media whose gold differs + from the model's unablated answer, else the + ``"content"`` donor. + donor_pool: swap only — the cases donors may come from (e.g. the + whole data partition the probed batch was drawn from); + ``None`` = the probed batch itself. """ if mode not in ("drop", "swap"): raise ValueError(f"mode must be 'drop' or 'swap'; got {mode!r}") - super().__init__(mode=mode, slots=slots, score_fn=score_fn, max_cases=max_cases) + if donor_rule not in DONOR_RULES: + raise ValueError(f"donor_rule must be one of {DONOR_RULES}; got {donor_rule!r}") + super().__init__(mode=mode, slots=slots, score_fn=score_fn, max_cases=max_cases, + donor_rule=donor_rule, donor_pool=donor_pool) # -- helpers ------------------------------------------------------- def _slots_of(self, case: "FailureCase") -> "list[str]": @@ -168,14 +220,40 @@ def _donor(cases: "list[FailureCase]", slot: str, case: "FailureCase", "swapping" the same image back in reads as a model that ignores it. """ own = key_of(getattr(case.inputs, slot)) - start = next(i for i, c in enumerate(cases) if c is case) - for step in range(1, len(cases)): + start = next((i for i, c in enumerate(cases) if c.id == case.id), -1) + for step in range(1, len(cases) + 1): other = cases[(start + step) % len(cases)] media = getattr(other.inputs, slot, None) if media is not None and other.id != case.id and key_of(media) != own: return str(other.id), media return None + @staticmethod + def _counterfactual_donor(same_prompt: "list[FailureCase]", slot: str, case: "FailureCase", + answer_key: str, key_of: "Callable[[Any], Any]", + ) -> "tuple[str, Any, str] | None": + """``(donor id, media, donor gold)``: the same question on different media whose + gold differs from the model's own answer *answer_key*. + + The donor case asks this exact prompt about its own media, so its gold + is what a correct answer must become after the swap. Searched from the + case's own position among the same-prompt cases (wrapping), so cases + sharing a question spread over the available donors. + """ + if not answer_key: + return None + own = key_of(getattr(case.inputs, slot)) + start = next((i for i, c in enumerate(same_prompt) if c.id == case.id), -1) + for step in range(1, len(same_prompt) + 1): + other = same_prompt[(start + step) % len(same_prompt)] + media = getattr(other.inputs, slot, None) + gold = _gold_key(other) + if (media is None or other.id == case.id or gold is None or gold == answer_key + or key_of(media) == own): + continue + return str(other.id), media, gold + return None + def _run(self, model: "Model", cases: "CaseBatch") -> Result: score = self.score_fn or _default_score selected = cases.stratified_head(self.max_cases) @@ -189,12 +267,26 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: modes_used: dict[str, set[str]] = {} swap = self.mode == "swap" media_keys: dict[int, Any] = {} + pool = list(self.donor_pool) if self.donor_pool is not None else selected + by_prompt: dict[str, list] = {} + if swap and self.donor_rule == "counterfactual": + for c in pool: + by_prompt.setdefault(_prompt_key(c), []).append(c) def key_of(media: Any) -> Any: # hash each media value once per run if id(media) not in media_keys: media_keys[id(media)] = _media_key(media) return media_keys[id(media)] + def find_donor(slot: str, case: Any, answer_key: str) -> "tuple[str, Any, str, str | None] | None": + if by_prompt: + cf = self._counterfactual_donor(by_prompt.get(_prompt_key(case), []), slot, case, + answer_key, key_of) + if cf is not None: + return cf[0], cf[1], "counterfactual", cf[2] + found = self._donor(pool, slot, case, key_of) + return (found[0], found[1], "content", None) if found else None + for case in selected: base_answer = str(model.generate(case.inputs)) base_key = _norm_answer(base_answer) @@ -206,7 +298,7 @@ def key_of(media: Any) -> Any: # hash each media value once per run if swap: row["ablation_base_answer"] = base_answer[:120] for slot in self._slots_of(case): - found = self._donor(selected, slot, case, key_of) if swap else None + found = find_donor(slot, case, base_key) if swap else None donor = found[1] if found else None # swap with no donor degrades to drop rather than skipping: the # weaker evidence is still evidence, and silently probing nothing @@ -227,6 +319,8 @@ def key_of(media: Any) -> Any: # hash each media value once per run row[f"ablation_{slot}_is_swap"] = effective == "swap" if swap: row[f"ablation_{slot}_donor"] = found[0] if found else None + row[f"ablation_{slot}_donor_kind"] = found[2] if found else None + row[f"ablation_{slot}_donor_expected"] = found[3] if found else None row[f"ablation_{slot}_answer"] = answer[:120] strategy = f"without_{slot}" @@ -259,6 +353,11 @@ def key_of(media: Any) -> Any: # hash each media value once per run findings[f"n_drop_fallback_{slot}"] = sum( 1 for r in per_case if r.get(f"ablation_{slot}_is_swap") is False ) + findings[f"n_counterfactual_{slot}"] = sum( + 1 for r in per_case if r.get(f"ablation_{slot}_donor_kind") == "counterfactual" + ) + if swap: + findings["donor_rule"] = self.donor_rule return Result( analyzer=self.name, model=repr(model), cases=cases, findings=findings, diff --git a/evalrx/analyzers/perturbation/prompt_contrast.py b/evalrx/analyzers/perturbation/prompt_contrast.py index c38329be..f0340485 100755 --- a/evalrx/analyzers/perturbation/prompt_contrast.py +++ b/evalrx/analyzers/perturbation/prompt_contrast.py @@ -173,6 +173,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: score = self.score_fn or _default_score by_strategy: dict[str, dict[str, float]] = {s: {} for s in self.strategies} answers: dict[str, dict[str, str]] = {s: {} for s in self.strategies} + outputs: dict[str, dict[str, str]] = {s: {} for s in self.strategies} # untruncated n_unscored = 0 # Stratified cap: keep FAIL representation so the cases actually carry @@ -194,6 +195,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: out = str(model.generate(dataclasses.replace(case.inputs, prompt=rewritten))) verdict = score(case, out) answers[strat][case.id] = out[:200] + outputs[strat][case.id] = out if verdict is None: n_unscored += 1 continue @@ -261,5 +263,5 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: model=repr(model), cases=cases, findings=findings, - artifacts={"answers": answers, "per_case": per_case}, + artifacts={"answers": answers, "outputs": outputs, "per_case": per_case}, ) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index a69773be..cd625801 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -167,13 +167,40 @@ def load_model(resolved: Resolved, args, task: T.Task): _SAMPLED_M1 = ("self_consistency", "coverage_verification_gap") +def _sampling_kwargs(resolved: Resolved, args) -> "dict | None": + """Per-call sampling settings for re-sampling analyzers; ``None`` where the + backend fixes sampling in its runtime and ignores per-call kwargs. + + The gemini runtime merges per-call kwargs over its own sampling + (``_Runtime.config``), so a temperature reaches the request there; the + endpoint's generate_fn drops them. + """ + if resolved.backend in ("hf_local", "jax_local"): + return {"temperature": 1.0, "top_p": args.top_p, "top_k": args.top_k} + if resolved.backend == "gemini": + return {"temperature": 1.0} + return None + + +def _usage_cost(model, before: "dict | None") -> dict: + """Provider usage since *before* and its listed-price USD (``{}`` for a model with no counters).""" + from evalrx.eval_agent.probing.metering import usage_counters, usage_delta + from evalrx.models.backends.api.prices import usd + + usage = usage_delta(before, usage_counters(model)) + if usage is None: + return {} + model_id = getattr(getattr(model, "spec", None), "hf_repo", None) or getattr(getattr(model, "spec", None), "key", None) + return {"api_usage": usage, "usd": usd(model_id, usage)} + + def _sampling_analyzer_overrides(resolved: Resolved, args) -> dict: - if resolved.backend not in ("hf_local", "jax_local"): + gen = _sampling_kwargs(resolved, args) + if gen is None: return {} from evalrx.analyzers.uncertainty.coverage_gap import CoverageVerificationGap from evalrx.analyzers.uncertainty.self_consistency import SelfConsistencyAnalyzer - gen = {"temperature": 1.0, "top_p": args.top_p, "top_k": args.top_k} return { "self_consistency": SelfConsistencyAnalyzer(gen_kwargs=dict(gen)), "coverage_verification_gap": CoverageVerificationGap(gen_kwargs=dict(gen)), @@ -346,6 +373,13 @@ def run_fix_isolated(loop, run_dir: Path, ctx, report, cases, **fix_kwargs): return loop.run_fix(report, cases, **fix_kwargs) +def _price_fn(spec): + from evalrx.models.backends.api.prices import usd + + model_id = spec.hf_repo or spec.key + return lambda usage: usd(model_id, usage) + + def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, cases, ctx, run_dir: Path, baseline: dict) -> int: """``--m1-policy triage_active`` (MVP-0): the fixed triage plan on EXPLORE, then stop. @@ -364,15 +398,25 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "generation": gen_kwargs, "enable_thinking": bool(args.enable_thinking), } ctx.config.update(m1_policy="triage_active", judge_provider=None, judge_model=None) # none was built + extras: dict = {"modality_ablation": {"score_fn": T.score_case}, + "prompt_contrast": {"score_fn": T.score_case}} + sampling = _sampling_kwargs(resolved, args) + if sampling is not None: + # API backends ignore per-call kwargs (their runtime samples); without + # settings here the U sampling check stays untested, never trivially clear + extras["self_consistency"] = {"gen_kwargs": sampling} report = run_triage_mvp0( model, explore, out_dir=run_dir / "probing", model_identity=identity, n_fail=args.triage_n_fail, seed=args.triage_seed, stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), - analyzer_kwargs={"modality_ablation": {"score_fn": T.score_case}}, + n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), + task_kind=task.kind, answer_fn=T.answer_key, analyzer_kwargs=extras, budget_sec=float(args.triage_budget_sec), stage0_cost={"wall_sec": baseline["seconds"], "calls": {"generate": baseline["n"]}, - "n_cases": baseline["n"]}, + "n_cases": baseline["n"], + **{k: baseline[k] for k in ("api_usage", "usd") if k in baseline}}, + price_fn=_price_fn(spec), partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "confirm_visible_to_controller": False}, @@ -492,6 +536,9 @@ def run(args, task: T.Task, resolved: Resolved) -> int: ) candidates = candidate_list + from evalrx.eval_agent.probing.metering import usage_counters + + usage_before = usage_counters(model) started = time.monotonic() discovery = CaseDiscoveryAgent( scorer=T.label_case, generation_kwargs=gen_kwargs, include_unknown=False, @@ -509,6 +556,8 @@ def run(args, task: T.Task, resolved: Resolved) -> int: "accuracy": round(accuracy, 4), "seconds": round(elapsed, 1), "generation_kwargs": gen_kwargs, "enable_thinking": bool(args.enable_thinking), "manifest": str(manifest), "limit": limit, + # what the provider counted for the discovery pass (API models only) + **_usage_cost(model, usage_before), "cases": [{ "id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value, } for c in cases], diff --git a/evalrx/benchmark/scoring.py b/evalrx/benchmark/scoring.py index b91eefc5..b5fe6358 100644 --- a/evalrx/benchmark/scoring.py +++ b/evalrx/benchmark/scoring.py @@ -161,6 +161,37 @@ def squad_em(observed: str, golds: list) -> bool: return any(candidate == squad_normalize(g) for g in golds) +#: Task kinds whose answers are free text graded by a model or a caption metric: +#: two outputs can agree without being equal strings, so no answer key is read. +_UNKEYED = frozenset({"llm_graded", "chair_caption"}) + + +def answer_key(kind: str, output: str, *, choices: list | None = None) -> "str | None": + """The answer *output* commits to, read the way :func:`score_output` reads it, without the gold. + + Two outputs with the same key give the same answer, so a triage check can tell + whether an answer moved across samples or rewordings without grading either. + ``""`` means the output commits to no readable answer; ``None`` means the + task kind has no categorical answer to compare. + """ + text = str(output if output is not None else "") + if kind in _UNKEYED: + return None + if kind == "multiple_choice_letter": + return parsed_choice(text, "".join(str(c)[0] for c in (choices or [])) or "ABCD") + if kind == "yes_no": + return parsed_yes_no(text).lower() + if kind == "short_answer_em": + return squad_normalize(extract_final_answer(text)) if text.strip() else "" + if kind == "exact_or_numeric": + if not text.strip(): + return "" + candidate = normalize_answer(extract_final_answer(text)) + number = _number(candidate) + return f"{number:g}" if number is not None else candidate + raise ValueError(f"unknown task kind {kind!r}") + + def score_output(kind: str, output: str, gold: Any, *, numeric_tolerance: float = 0.0, choices: list | None = None, dataset: str = "") -> bool: """``True`` iff *output* is correct for a case of task *kind*.""" diff --git a/evalrx/benchmark/tasks/__init__.py b/evalrx/benchmark/tasks/__init__.py index 01dd58ab..018c115c 100644 --- a/evalrx/benchmark/tasks/__init__.py +++ b/evalrx/benchmark/tasks/__init__.py @@ -17,6 +17,7 @@ ) from .base import ( # noqa: F401 Task, + answer_key, build_cases, label_case, load_rows, diff --git a/evalrx/benchmark/tasks/base.py b/evalrx/benchmark/tasks/base.py index ed265e14..13f26654 100644 --- a/evalrx/benchmark/tasks/base.py +++ b/evalrx/benchmark/tasks/base.py @@ -118,6 +118,15 @@ def score_case(case: Any, output: str) -> bool: ) +def answer_key(case: Any, output: str) -> "str | None": + """The answer *output* commits to for this case's task, without the gold + (see :func:`~evalrx.benchmark.scoring.answer_key`).""" + from ..scoring import answer_key as _key + + meta = getattr(case, "metadata", None) or {} + return _key(str(meta.get("task", "exact_or_numeric")), output, choices=meta.get("choices")) + + def label_case(case: Any, output: str): from evalrx.core.case import Label diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/probing/actions.py index dbdd522e..f9152d97 100644 --- a/evalrx/eval_agent/probing/actions.py +++ b/evalrx/eval_agent/probing/actions.py @@ -10,7 +10,7 @@ import hashlib import json -from dataclasses import asdict, dataclass, field +from dataclasses import asdict, dataclass, field, fields from typing import Any #: Terminal outcomes of an executed action. ``skipped`` (budget) is never @@ -27,11 +27,18 @@ def canonical(value: Any) -> Any: """A JSON-stable rendering of *value* for hashing and logging. Callables become their import path (a function's repr carries a memory - address, which would give every run a new identity); sets are sorted; - anything else unknown falls back to its type name and repr. + address, which would give every run a new identity); a case batch (e.g. a + donor pool) becomes its ordered case ids; sets are sorted; anything else + unknown falls back to its type name and repr. """ + from evalrx.core.case import CaseBatch, FailureCase + if value is None or isinstance(value, (bool, int, float, str)): return value + if isinstance(value, CaseBatch): + return {"case_ids": [str(c.id) for c in value]} + if isinstance(value, FailureCase): + return f"case:{value.id}" if isinstance(value, dict): return {str(k): canonical(v) for k, v in sorted(value.items(), key=lambda kv: str(kv[0]))} if isinstance(value, (list, tuple)): @@ -88,7 +95,8 @@ def identity(self, context: dict[str, Any]) -> str: }) def to_dict(self) -> dict[str, Any]: - out = canonical(asdict(self)) + # a shallow read: asdict() would deep-copy a donor pool's cases (and media) + out = canonical({f.name: getattr(self, f.name) for f in fields(self)}) out["n_cases"] = len(self.case_ids) return out diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index a6116bd6..b6516b0c 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -1,12 +1,20 @@ """MVP-0: the fixed triage plan, executed strictly, with its trace and costs. -The plan is four actions on one matched sample, in this order: +The plan is a fixed list of actions on one matched sample, in this order: 1. ``answer_extraction_audit`` (re-reads the Stage-0 outputs; no model call) 2. ``termination_audit`` without continuation (re-reads the outputs too) 3. ``modality_ablation(mode="swap")`` — the N triage check 4. ``attention_knockout(target="gold")`` — the first N-layer measurement, on white-box backends; elsewhere it is gated off as ``unsupported`` +5. ``self_consistency`` — re-samples each case (U) +6. ``prompt_contrast`` with the question kept verbatim in neutral wrappers (U) +7. ``prompt_contrast`` with an instruction not to default to "no" (yes/no tasks + only): which stable errors move under a changed decision criterion (S) +8. ``embed_lens(layer=0.9)`` — is the case's own question word close to the + media tokens late in the stack (S2) +9. ``patchscope(target="gold", media_layers=3)`` — was the gold answer readable + before the output, and is the question word read off the media tokens (S3, S2) No judge is called and nothing is selected adaptively: MVP-0 establishes the execution, metering, fidelity and trace contracts the adaptive controller @@ -18,34 +26,65 @@ from __future__ import annotations +import hashlib +import inspect import json import os from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any, Callable +from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES from evalrx.eval_agent.probing.actions import OK, SKIPPED, ProbeAction, canonical from evalrx.eval_agent.probing.executor import execute from evalrx.eval_agent.probing.ledger import Ledger +from evalrx.eval_agent.probing.proposals import propose from evalrx.eval_agent.probing.sampler import matched_sample from evalrx.eval_agent.probing.triage import summarize, triage_cases if TYPE_CHECKING: from evalrx.core.case import CaseBatch -POLICY_VERSION = "mvp0-1" +POLICY_VERSION = "mvp0-2" @dataclass(frozen=True) class PlanStep: - """One row of the fixed plan: what to build, why, and what it may cost.""" + """One row of the fixed plan: what to build, why, and what it may cost. + + ``key`` names the step when one analyzer serves two steps (default: the + analyzer). ``per_case`` runs a one-case analyzer once per case; + ``keep_artifacts`` keeps those result artifacts with the findings; + ``task_kinds`` limits the step to those task kinds (empty = every kind). + """ analyzer: str config: dict[str, Any] route: str purpose: str - fidelity_check: "str | None" = None # "edit" = tap/linear self-check applies + fidelity_check: "str | None" = None # "edit" = tap/linear self-check, "patch" = patch self-check calls_per_case: dict[str, int] = field(default_factory=dict) + key: str = "" + per_case: bool = False + keep_artifacts: tuple[str, ...] = () + task_kinds: tuple[str, ...] = () + + @property + def name(self) -> str: + return self.key or self.analyzer + + +#: Neutral wrappers around the question, kept verbatim (with its output +#: contract): the meaning cannot change, only the surface. A wrapper whose +#: answer is unreadable is an invalid control, not an unstable answer. +REWORD_STRATEGIES = { + "baseline": "{prompt}", + "question_frame": "Question: {prompt}\nAnswer:", + "instruction_frame": "Answer the following question.\n\n{prompt}", +} +#: A changed decision criterion, not a rewording: tells a stable "no" that +#: moves when the model is told not to default to it from one that does not. +THRESHOLD_STRATEGIES = {"baseline": "{prompt}", "sensitive": _PROMPT_STRATEGIES["sensitive"]} MVP0_PLAN: tuple[PlanStep, ...] = ( @@ -53,12 +92,35 @@ class PlanStep: "re-read Stage-0 outputs for grading and extraction problems"), PlanStep("termination_audit", {"continue_non_clean": False}, "H", "classify how each Stage-0 output ended, without continuing it"), - PlanStep("modality_ablation", {"mode": "swap"}, "N", - "re-ask with a different case's media; an unchanged answer is the N signal", + PlanStep("modality_ablation", {"mode": "swap", "donor_rule": "counterfactual"}, "N", + "re-ask with media on which the same question's gold differs from the model's answer " + "(else any different media); an answer that should change but does not is the N signal", calls_per_case={"generate": 2}), PlanStep("attention_knockout", {"target": "gold"}, "N1", "cut text-to-media attention per layer band; margin change of the gold first token", fidelity_check="edit", calls_per_case={"forward": 5}), + PlanStep("self_consistency", {"n": 5}, "U", + "re-sample each case at the host's frozen sampling settings; an answer that differs " + "from the Stage-0 answer is the U signal", + calls_per_case={"generate": 5}, per_case=True, keep_artifacts=("samples",)), + PlanStep("prompt_contrast", {"strategies": REWORD_STRATEGIES}, "U", + "re-ask with the question verbatim inside two neutral wrappers; an answer that " + "moves is the U signal", + calls_per_case={"generate": 3}, key="prompt_reword", keep_artifacts=("outputs",)), + PlanStep("prompt_contrast", {"strategies": THRESHOLD_STRATEGIES}, "S", + "re-ask with an instruction not to default to a negative answer: which errors move, " + "and which correct answers it breaks", + calls_per_case={"generate": 2}, key="prompt_threshold", keep_artifacts=("outputs",), + task_kinds=("yes_no",)), + PlanStep("embed_lens", {"layer": 0.9}, "S2", + "nearest vocabulary words of the media tokens late in the stack: how close the " + "case's own question word gets", + calls_per_case={"forward": 1}), + PlanStep("patchscope", {"target": "gold", "media_layers": 3}, "S3", + "decode the answer position at every layer and the media tokens at three depths: " + "whether the gold answer was readable before the output, and whether the question " + "word is read off the media", + fidelity_check="patch", calls_per_case={"forward": 1}), ) @@ -74,6 +136,25 @@ def _build(step: PlanStep, extra: dict[str, Any]) -> Any: return registry.analyzers.get(step.analyzer)(**{**step.config, **extra}) +def tool_version(analyzer: Any) -> str: + """Content hash of the analyzer's module and the shared ``analyzers/_internals``. + + Part of every action identity, so changing how a tool measures (or checks + its own fidelity) makes a resumed run re-execute it instead of reading + back an observation the old code produced. + """ + import evalrx.analyzers._internals as internals + + paths = [Path(inspect.getsourcefile(type(analyzer)) or "")] + paths += sorted(Path(internals.__file__).parent.glob("*.py")) + h = hashlib.sha1() + for path in paths: + if path.is_file(): + h.update(path.name.encode()) + h.update(path.read_bytes()) + return h.hexdigest()[:12] + + def run_triage_mvp0( model: Any, explore: "CaseBatch", @@ -85,7 +166,11 @@ def run_triage_mvp0( stratum: str = "gold", host_assumed_finish: bool = False, answer_contract: bool = False, + n_needs_counterfactual: bool = False, + task_kind: "str | None" = None, + answer_fn: "Callable[[Any, str], str | None] | None" = None, analyzer_kwargs: "dict[str, dict[str, Any]] | None" = None, + price_fn: "Callable[[dict[str, Any] | None], float | None] | None" = None, plan: "tuple[PlanStep, ...]" = MVP0_PLAN, budget_sec: float = 0.0, stage0_cost: "dict[str, Any] | None" = None, @@ -107,8 +192,20 @@ def run_triage_mvp0( stratum: ``"gold"`` (match PASS on the gold answer) or ``"none"``. host_assumed_finish: the host, not the backend, set ``finish_reason``. answer_contract: the task declares an answer tag or output contract. + n_needs_counterfactual: few-answer task (yes/no, letters): a swap only tests N + with a counterfactual donor. Donors are drawn from the + whole of *explore*, never from outside it. + task_kind: the task's kind; steps limited to other kinds are + recorded as ``not_applicable`` and not run. + answer_fn: ``(case, output) -> answer key`` (``""`` = no readable + answer, ``None`` = the task has no categorical answer): + how the U checks tell whether an answer moved. Default: + a coarse yes/no-or-prefix key. analyzer_kwargs: per-analyzer constructor extras the host supplies - (e.g. the task's ``score_fn``); recorded in the config. + (e.g. the task's ``score_fn``, the sampling settings); + recorded in the config. + price_fn: ``api_usage -> USD`` (``None`` = no price on record) for + API models; the cost ledger and report carry it. budget_sec: wall-clock cap on executed actions (0 = none). An action already running is not interrupted; later ones are skipped. stage0_cost: the shared baseline cost, logged once and kept separate. @@ -118,7 +215,9 @@ def run_triage_mvp0( say = progress or (lambda _msg: None) out = Path(out_dir) ledger = Ledger(out) - extras = analyzer_kwargs or {} + extras = {k: dict(v) for k, v in (analyzer_kwargs or {}).items()} + # swap donors come from the whole partition the sample was drawn from + extras.setdefault("modality_ablation", {}).setdefault("donor_pool", explore) sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) _write_json(out / "split_manifest.json", { "policy": POLICY_VERSION, "partition": partition or {}, "n_explore": len(explore), @@ -142,44 +241,59 @@ def run_triage_mvp0( route=step.route, purpose=step.purpose, reserve={k: v * len(draw.case_ids) for k, v in step.calls_per_case.items()}, ) - action_id = action.identity(context) - base = {"step": step_no, "action_id": action_id, "analyzer": step.analyzer} + if step.task_kinds and task_kind not in step.task_kinds: + base = {"step": step_no, "key": step.name, "analyzer": step.analyzer} + reason = f"step is for task kinds {list(step.task_kinds)}; this task is {task_kind!r}" + ledger.trace({**base, "event": "not_applicable", "reason": reason}) + steps.append({**base, "status": "not_applicable", "reused": False, "reason": reason}) + say(f"[triage] {step_no} {step.name}: not applicable ({task_kind})") + continue + try: + analyzer = _build(step, extra) + except Exception as exc: # noqa: BLE001 - a bad config is an outcome, not a crash + base = {"step": step_no, "key": step.name, "action_id": action.identity(context), + "analyzer": step.analyzer} + ledger.trace({**base, "event": "skipped", "status": "failed", + "reason": f"could not construct: {type(exc).__name__}: {exc}"}) + steps.append({**base, "status": "failed", "error": str(exc)}) + continue + version = tool_version(analyzer) + action_id = action.identity({**context, "tool_version": version, + "per_case": step.per_case, "keep_artifacts": list(step.keep_artifacts)}) + base = {"step": step_no, "key": step.name, "action_id": action_id, "analyzer": step.analyzer} done = ledger.settled(action_id) if done is not None: ledger.trace({**base, "event": "reused", "status": done.status, "attempt": done.attempt, "note": "terminal observation with the same identity; read back, not re-run"}) - observations[step.analyzer] = done + observations[step.name] = done steps.append({**base, "status": done.status, "reused": True, "fidelity": done.fidelity, "cost": done.cost, "error": done.error}) - say(f"[triage] {step_no} {step.analyzer}: reused ({done.status})") + say(f"[triage] {step_no} {step.name}: reused ({done.status})") continue if budget_sec > 0 and ledger.spent_wall_sec() >= budget_sec: ledger.trace({**base, "event": "skipped", "status": SKIPPED, "reason": f"wall-clock budget {budget_sec}s spent"}) steps.append({**base, "status": SKIPPED, "reason": "budget"}) - say(f"[triage] {step_no} {step.analyzer}: skipped (budget)") + say(f"[triage] {step_no} {step.name}: skipped (budget)") continue prior = ledger.attempts(action_id) attempt = prior + 1 - try: - analyzer = _build(step, extra) - except Exception as exc: # noqa: BLE001 - a bad config is an outcome, not a crash - ledger.trace({**base, "event": "skipped", "status": "failed", - "reason": f"could not construct: {type(exc).__name__}: {exc}"}) - steps.append({**base, "status": "failed", "error": str(exc)}) - continue ledger.trace({ **base, "event": "planned", "attempt": attempt, "action": action.to_dict(), - "params": canonical(analyzer.get_params()), "fidelity_check": step.fidelity_check, - "rationale": "MVP-0 fixed order", "candidates": [s.analyzer for s in plan], + "params": canonical(analyzer.get_params()), "tool_version": version, + "fidelity_check": step.fidelity_check, + "rationale": "MVP-0 fixed order", "candidates": [s.name for s in plan], **({"previous_attempts_uncertain": prior} if prior else {}), }) - say(f"[triage] {step_no} {step.analyzer}: running on {len(sample)} cases") + say(f"[triage] {step_no} {step.name}: running on {len(sample)} cases") obs = execute(action, action_id, attempt, analyzer, model, sample, - fidelity_check=step.fidelity_check, run_logger=run_logger) + fidelity_check=step.fidelity_check, per_case=step.per_case, + keep_artifacts=step.keep_artifacts, run_logger=run_logger) + if obs.cost.get("api_usage") is not None: + obs.cost["usd"] = price_fn(obs.cost["api_usage"]) if price_fn is not None else None ledger.save(obs) ledger.cost({"kind": "action", "action_id": action_id, "analyzer": step.analyzer, "attempt": attempt, "reserved_calls": action.reserve, @@ -188,23 +302,30 @@ def run_triage_mvp0( ledger.trace({**base, "event": "settled", "attempt": attempt, "status": obs.status, "fidelity": obs.fidelity.get("status"), "n_measured": len(obs.measured_ids), "n_missing": len(obs.missing), "error_type": obs.error_type, "error": obs.error}) - observations[step.analyzer] = obs + observations[step.name] = obs steps.append({**base, "status": obs.status, "reused": False, "fidelity": obs.fidelity, "cost": obs.cost, "error": obs.error, "n_measured": len(obs.measured_ids), "missing": obs.missing}) - say(f"[triage] {step_no} {step.analyzer}: {obs.status} " + say(f"[triage] {step_no} {step.name}: {obs.status} " f"(fidelity={obs.fidelity.get('status')}, {obs.cost.get('wall_sec')}s, calls={obs.cost.get('calls')})") records = triage_cases(sample, observations, host_assumed_finish=host_assumed_finish, - answer_contract=answer_contract) + answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, + answer_fn=answer_fn) report = { "policy": POLICY_VERSION, "model": model_identity, "sample": draw.to_dict(), "settings": {"host_assumed_finish": host_assumed_finish, "answer_contract": answer_contract, - "budget_sec": budget_sec}, + "n_needs_counterfactual": n_needs_counterfactual, "budget_sec": budget_sec, + "task_kind": task_kind, "answer_fn": canonical(answer_fn)}, "steps": steps, + "cost": _cost_summary(steps, stage0_cost), "summary": summarize(records), + "next_candidates": propose( + records, model, sample, task_kind=task_kind, extras=extras, + executed={(s.analyzer, str(canonical({**s.config, **extras.get(s.analyzer, {})}))) + for s in plan if s.name in observations}), "checks": _acceptance(plan, steps, observations, draw, ledger), "cases": records, } @@ -213,6 +334,33 @@ def run_triage_mvp0( return report +def _cost_summary(steps: list[dict[str, Any]], stage0_cost: "dict[str, Any] | None") -> dict[str, Any]: + """This invocation's spend: Stage 0, the actions it executed, and (apart) what it read back. + + Token and USD totals only cover actions whose provider reported usage; a + missing price leaves ``usd`` unknown rather than counting it as zero. + """ + def total(rows: list[dict[str, Any]]) -> dict[str, Any]: + costs = [r.get("cost") or {} for r in rows] + usage = [c["api_usage"] for c in costs if c.get("api_usage") is not None] + usd = [c.get("usd") for c in costs if c.get("api_usage") is not None] + calls: dict[str, int] = {} + for c in costs: + for k, v in (c.get("calls") or {}).items(): + calls[k] = calls.get(k, 0) + int(v) + out: dict[str, Any] = {"n_actions": len(rows), "calls": calls, + "wall_sec": round(sum(float(c.get("wall_sec") or 0.0) for c in costs), 3)} + if usage: + out["api_usage"] = {k: sum(int(u.get(k, 0)) for u in usage) for k in usage[0]} + out["usd"] = round(sum(usd), 6) if all(v is not None for v in usd) else None + return out + + ran = [s for s in steps if s.get("status") not in ("not_applicable", SKIPPED) and not s.get("reused")] + reused = [s for s in steps if s.get("reused")] + return {"stage0": stage0_cost or {}, "actions_run": total(ran), + "actions_read_back": {**total(reused), "_note": "spent by the run that executed them"}} + + def _acceptance(plan: "tuple[PlanStep, ...]", steps: list[dict[str, Any]], observations: dict[str, Any], draw: Any, ledger: Ledger) -> dict[str, Any]: """The MVP-0 acceptance properties that can be checked from the run's own records.""" @@ -222,9 +370,9 @@ def _acceptance(plan: "tuple[PlanStep, ...]", steps: list[dict[str, Any]], obser for name, obs in observations.items()} configs = {} for s in plan: - obs = observations.get(s.analyzer) + obs = observations.get(s.name) if obs is not None: - configs[s.analyzer] = all(obs.params.get(k) == canonical(v) for k, v in s.config.items()) + configs[s.name] = all(obs.params.get(k) == canonical(v) for k, v in s.config.items()) costs = ledger.cost_events() return { "only_planned_actions": traced <= planned and len(steps) == len(plan), @@ -236,6 +384,14 @@ def _acceptance(plan: "tuple[PlanStep, ...]", steps: list[dict[str, Any]], obser } +def _why_not(report: dict[str, Any], key: str) -> str: + step = next((st for st in report["steps"] if (st.get("key") or st["analyzer"]) == key), None) + if step is None: + return "not in the plan" + reason = step.get("error") or step.get("reason") or "" + return f"{step['status']}" + (f" ({reason})" if reason else "") + + def _markdown(report: dict[str, Any]) -> str: s = report["summary"] lines = [ @@ -248,18 +404,41 @@ def _markdown(report: dict[str, Any]) -> str: ] for st in report["steps"]: cost = st.get("cost") or {} - lines.append(f"| {st['step']} | {st['analyzer']} | {st['status']}{' (reused)' if st.get('reused') else ''} " + name = st.get("key") or st["analyzer"] + if name != st["analyzer"]: + name = f"{st['analyzer']} ({name})" + lines.append(f"| {st['step']} | {name} | {st['status']}{' (reused)' if st.get('reused') else ''} " f"| {(st.get('fidelity') or {}).get('status', '-')} | {cost.get('wall_sec', '-')} " f"| {cost.get('calls', '-')} |") + cost = report.get("cost") or {} + run, stage0 = cost.get("actions_run") or {}, cost.get("stage0") or {} + lines += ["", f"Cost of this invocation: Stage 0 {stage0.get('wall_sec', '-')} s, {stage0.get('calls', '-')}" + + (f", {stage0['api_usage']}, USD {stage0.get('usd')}" if stage0.get("api_usage") else "") + + f"; actions run {run.get('wall_sec', 0)} s, {run.get('calls', {})}" + + (f", {run['api_usage']}, USD {run.get('usd')}" if run.get("api_usage") else "") + "."] lines += ["", "## Routes on this sample", "", "| route | FAIL fired/tested | PASS fired/tested | routing signal |", "|---|---|---|---:|"] - for tag in ("H_label_free", "N"): + for tag in ("H_label_free", "N", "U"): f, p = s[tag]["fail"], s[tag]["pass"] lines.append(f"| {tag} | {f['n_fired']}/{f['n_tested']} | {p['n_fired']}/{p['n_tested']} " f"| {s[tag]['routing_signal']} |") - lines += [f"| X (no H/N signal) | {s['X']['fail']} | {s['X']['pass']} | - |", "", + for part, rates in s["U_parts"].items(): + f, p = rates["fail"], rates["pass"] + lines.append(f"| U: {part} | {f['n_fired']}/{f['n_tested']} | {p['n_fired']}/{p['n_tested']} | - |") + lines += [f"| S (stable FAIL) / stable PASS | {s['S']['fail']} | {s['S']['stable_pass']} | - |", + f"| X (a required check missing) | {s['X']['fail']} | {s['X']['pass']} | - |", "", "The routing signal is max(0, P(tag|FAIL) - P(tag|PASS)) on this matched sample: it steers " - "later actions and is not an explained share of failures. U was not run; S is not assigned."] + "later actions and is not an explained share of failures. S = a FAIL case on which H, N " + "(with media) and both U parts ran and none fired; a missing check leaves it in X."] + donors = s.get("N_donors") or {} + if donors: + lines += ["", "Swap donors (counterfactual = the same question's gold on the donor media differs " + "from the model's answer, so a correct answer has to change):", "", + "| label | counterfactual | content only | no swap | followed donor |", "|---|---:|---:|---:|---:|"] + for label in ("fail", "pass"): + d = donors[label] + lines.append(f"| {label.upper()} | {d['counterfactual']} | {d['content']} | {d['no_swap']} " + f"| {d['counterfactual_followed_donor']}/{d['counterfactual']} |") split = s.get("N_by_base_answer") if split: lines += ["", "N by the unablated answer (unchanged after swap / tested):", "", @@ -271,13 +450,59 @@ def _markdown(report: dict[str, Any]) -> str: f"| {row['pass']['n_fired']}/{row['pass']['n_tested']} |") lines += ["", f"_{split['_note']}._"] ko = s["attention_knockout"] - lines += ["", "## Knockout (descriptive)", "", f"Fidelity: {', '.join(ko['fidelity'])}.", "", - "| label | measured | mean ko_delta_full | mean ko_delta_late |", "|---|---:|---:|---:|"] - for label in ("fail", "pass"): - row = ko[label] - lines.append(f"| {label.upper()} | {row['n_measured']} | {row['mean_ko_delta_full']} " - f"| {row['mean_ko_delta_late']} |") - lines += ["", f"_{ko['_note']}._", "", "## Checks", ""] + lines += ["", "## Knockout (descriptive)", ""] + if not any(ko[label]["n_measured"] for label in ("fail", "pass")): + lines.append(f"Not measured: {_why_not(report, 'attention_knockout')}.") + else: + lines += [f"Fidelity: {', '.join(ko['fidelity'])}.", "", + "| label | measured | mean ko_delta_full | mean ko_delta_late |", "|---|---:|---:|---:|"] + for label in ("fail", "pass"): + row = ko[label] + lines.append(f"| {label.upper()} | {row['n_measured']} | {row['mean_ko_delta_full']} " + f"| {row['mean_ko_delta_late']} |") + lines += ["", f"_{ko['_note']}._"] + threshold = s.get("S_threshold") + if threshold: + lines += ["", "## Threshold instruction (S, behavioural)", "", + "| label | stratum | measured | answer changed | fixed | broken |", "|---|---|---:|---:|---:|---:|"] + for g in threshold["groups"]: + lines.append(f"| {str(g['label']).upper()} | {g['stratum']} | {g['n_measured']} | {g['n_changed']} " + f"| {g['n_fixed']} | {g['n_broken']} |") + lines += ["", f"_{threshold['_note']}._"] + readings = s.get("S_readings") or {} + cohorts = [(name, stratum, row) for name, by in readings.items() if not name.startswith("_") + for stratum, row in by.items()] + measured = any(row["embed_lens"]["n"] or row["patchscope"]["n"] for _, _, row in cohorts) + if cohorts and not measured: + sizes = ", ".join(f"{name} {stratum} {row['n']}" for name, stratum, row in cohorts) + lines += ["", "## S readings (descriptive)", "", + f"Not measured: embed_lens {_why_not(report, 'embed_lens')}; " + f"patchscope {_why_not(report, 'patchscope')}. Cohort sizes: {sizes}."] + elif cohorts: + lines += ["", "## S readings (descriptive)", "", + "| cohort | stratum | n | mean el_query_sim | gold first before last | mean peak / final prob " + "| mean late drop | question word on media |", "|---|---|---:|---:|---:|---|---:|---:|"] + for name, stratum, row in cohorts: + ps = row["patchscope"] + lines.append(f"| {name} | {stratum} | {row['n']} | {row['embed_lens']['mean_query_sim']} " + f"| {ps['n_target_first_before_last']}/{ps['n']} | {ps['mean_peak_prob']} / " + f"{ps['mean_final_prob']} | {ps['mean_late_drop']} " + f"| {ps['n_media_query_hit']}/{ps['n_media_query_read']} |") + lines += ["", f"_{readings['_note']}._"] + proposals = report.get("next_candidates") or {} + if proposals.get("candidates"): + lines += ["", "## Next candidates (proposed by rule, not run)", "", + "| route | FAIL cases | analyzer | config | status | question / reason |", "|---|---:|---|---|---|---|"] + for c in proposals["candidates"]: + text = c.get("question") or "" + if c.get("reason"): + text = f"{text} ({c['reason']})" if text else c["reason"] + lines.append(f"| {c['route']} | {c['n_fail_cases']} | {c['analyzer']} | {c.get('config', '')} " + f"| {c['status']} | {text} |") + if proposals.get("x_untested"): + lines += ["", f"Why X cases stay untested: {proposals['x_untested']}."] + lines += ["", f"_{proposals['_note']}._"] + lines += ["", "## Checks", ""] for name, value in report["checks"].items(): lines.append(f"- `{name}`: {value}") lines.append("") diff --git a/evalrx/eval_agent/probing/executor.py b/evalrx/eval_agent/probing/executor.py index c2beccb7..ba4069cc 100644 --- a/evalrx/eval_agent/probing/executor.py +++ b/evalrx/eval_agent/probing/executor.py @@ -12,6 +12,12 @@ * ``ok`` — findings, plus which planned cases actually produced a row. Only ``ok`` carries findings; the other outcomes carry the reason, never a zero. + +An analyzer that measures one case per call (``self_consistency`` reads only +``cases[0]``) runs with ``per_case=True``: once per planned case, each call's +findings becoming that case's ``per_case`` row. Artifacts named in +``keep_artifacts`` (e.g. the raw samples) are kept with the findings, since +the triage reads answers out of them. """ from __future__ import annotations @@ -28,7 +34,13 @@ ProbeAction, canonical, ) -from evalrx.eval_agent.probing.metering import MeteredModel, gpu_peak_mb, gpu_peak_reset +from evalrx.eval_agent.probing.metering import ( + MeteredModel, + gpu_peak_mb, + gpu_peak_reset, + usage_counters, + usage_delta, +) if TYPE_CHECKING: from evalrx.core.analyzer import Analyzer @@ -47,20 +59,52 @@ def gate(analyzer: "Analyzer", model: Any, cases: "CaseBatch") -> "str | None": return None +#: Where each kind of self-check reports its verdict in the findings. +FIDELITY_KEYS = {"edit": "tap_fidelity", "patch": "patch_fidelity"} + + def _fidelity(check: "str | None", findings: dict[str, Any]) -> dict[str, Any]: if check is None: return {"status": "not_applicable"} - verdict = findings.get("tap_fidelity") + verdict = findings.get(FIDELITY_KEYS[check]) if not isinstance(verdict, dict): return {"status": "unchecked", "reason": "analyzer reported no fidelity verdict"} faithful = verdict.get("faithful", verdict.get("tap_faithful")) return {"status": "passed" if faithful else "failed", "verdict": canonical(verdict)} +def _kept(result: Any, names: "tuple[str, ...]") -> dict[str, Any]: + artifacts = getattr(result, "artifacts", None) or {} + return {name: canonical(artifacts[name]) for name in names if name in artifacts} + + +def _run_per_case(analyzer: "Analyzer", model: Any, cases: "CaseBatch", + keep_artifacts: "tuple[str, ...]") -> dict[str, Any]: + """One call per case; each call's findings (minus ``_`` notes) become its row.""" + from evalrx.core.case import CaseBatch + + rows, notes = [], {} + for case in cases: + result = analyzer.run(model, CaseBatch([case])) + findings = canonical(result.findings or {}) + row = {k: v for k, v in findings.items() if not k.startswith("_") and k != "per_case"} + row["sample_id"] = str(case.id) + if keep_artifacts: + row["artifacts"] = _kept(result, keep_artifacts) + notes.update({k: v for k, v in findings.items() if k.startswith("_") and k not in notes}) + rows.append(row) + return {"per_case": rows, "per_case_mode": True, **notes} + + def execute(action: ProbeAction, action_id: str, attempt: int, analyzer: "Analyzer", model: Any, cases: "CaseBatch", *, fidelity_check: "str | None" = None, + per_case: bool = False, keep_artifacts: "tuple[str, ...]" = (), run_logger: Any = None) -> Observation: - """Run *analyzer* on *cases* (= ``action.case_ids``) once and type the outcome.""" + """Run *analyzer* on *cases* (= ``action.case_ids``) once and type the outcome. + + With *per_case*, the analyzer runs once per case instead (see the module + docstring); a raise on any case types the whole action, as in batch mode. + """ from evalrx.analyzers._internals.attn_tap import FidelityError from evalrx.core.capability import CapabilityError @@ -90,9 +134,16 @@ def execute(action: ProbeAction, action_id: str, attempt: int, analyzer: "Analyz ) metered = MeteredModel(target) measured_gpu = gpu_peak_reset() + usage_before = usage_counters(model) t0 = time.monotonic() try: - result = analyzer.run(metered, cases) + if per_case: + raw = _run_per_case(analyzer, metered, cases, tuple(keep_artifacts)) + else: + result = analyzer.run(metered, cases) + raw = result.findings or {} + if keep_artifacts: + raw = {**raw, "artifacts": _kept(result, tuple(keep_artifacts))} except CapabilityError as exc: obs.status, obs.error_type, obs.error = UNSUPPORTED, type(exc).__name__, str(exc)[:500] except FidelityError as exc: @@ -101,7 +152,7 @@ def execute(action: ProbeAction, action_id: str, attempt: int, analyzer: "Analyz except Exception as exc: # noqa: BLE001 - typed outcome, not a crash of the controller obs.status, obs.error_type, obs.error = FAILED, type(exc).__name__, str(exc)[:500] else: - findings = canonical(result.findings or {}) + findings = canonical(raw) obs.status, obs.findings = OK, findings obs.measured_ids = [i for i in planned if i in obs.per_case()] skips = findings.get("skip_reasons") or {} @@ -114,5 +165,7 @@ def execute(action: ProbeAction, action_id: str, attempt: int, analyzer: "Analyz "call_errors": dict(metered.errors), "model_sec": round(metered.model_sec, 3), "gpu_peak_mb": gpu_peak_mb() if measured_gpu else None, + # what the provider counted (API models): requests, retries, tokens + "api_usage": usage_delta(usage_before, usage_counters(model)), } return obs diff --git a/evalrx/eval_agent/probing/metering.py b/evalrx/eval_agent/probing/metering.py index 1bd80ccc..c6e9d54f 100644 --- a/evalrx/eval_agent/probing/metering.py +++ b/evalrx/eval_agent/probing/metering.py @@ -4,6 +4,11 @@ generate/forward/logprobs/chat call and the seconds spent inside them; the wall clock and the GPU peak (when torch is already loaded) bracket the whole action. Calls and seconds are reported side by side, never added together. + +An API model also reports what the provider counted — requests (retries +included separately) and prompt / completion / thought tokens — through +``usage_counters()``; :func:`usage_delta` differences two reads of it. A model +without counters reports ``None``, not zeros. """ from __future__ import annotations @@ -57,6 +62,25 @@ def chat(self, messages: list, tools: "list | None" = None) -> Any: return self._timed("chat", self._metered.chat, messages, tools) +def usage_counters(model: Any) -> "dict[str, int] | None": + """The model's cumulative provider counters (through any proxy), or ``None``.""" + read = getattr(model, "usage_counters", None) + if not callable(read): + return None + try: + counters = read() + except Exception: # noqa: BLE001 - metering never fails the action + return None + return dict(counters) if isinstance(counters, dict) else None + + +def usage_delta(before: "dict[str, int] | None", after: "dict[str, int] | None") -> "dict[str, int] | None": + """``after - before`` per counter; ``None`` unless both reads exist.""" + if before is None or after is None: + return None + return {k: int(after.get(k, 0)) - int(before.get(k, 0)) for k in after} + + def gpu_peak_reset() -> bool: """Reset the CUDA peak counter; ``False`` when there is no CUDA to measure.""" torch = sys.modules.get("torch") # never import torch just to meter an API run diff --git a/evalrx/eval_agent/probing/proposals.py b/evalrx/eval_agent/probing/proposals.py new file mode 100644 index 00000000..bcc23d15 --- /dev/null +++ b/evalrx/eval_agent/probing/proposals.py @@ -0,0 +1,115 @@ +"""Next experiments the fixed plan did not run: proposed by rule, checked, never run. + +A run without internal state must still be able to name its next behavioural +experiment. Every route with FAIL cases on this sample gets the follow-ups of +the method table, behavioural ones first; each is built with the host's +extras and gated on the actual model and sample, so the report says which +can run here and why the others cannot. Nothing is executed or scored: +choosing among them is the adaptive controller's job (MVP-3), and only +configurations the tools already support are proposed. +""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass +from typing import Any + +from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES +from evalrx.eval_agent.probing.actions import canonical +from evalrx.eval_agent.probing.executor import gate + +DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} + + +@dataclass(frozen=True) +class FollowUp: + """One candidate: the route it serves, the tool and configuration, the question it asks.""" + + route: str + analyzer: str + config: dict[str, Any] + question: str + task_kinds: tuple[str, ...] = () + caveat: str = "" + + +FOLLOW_UPS: tuple[FollowUp, ...] = ( + FollowUp("H", "answer_extraction_audit", {"reask": True}, + "does a re-ask with a stricter answer request recover the answer the output lost"), + FollowUp("H", "termination_audit", {"continue_non_clean": True}, + "continued past where it stopped, does the output reach an answer"), + FollowUp("N", "prompt_contrast", {"strategies": DESCRIBE_STRATEGIES}, + "asked to describe the media first, does the answer start to follow it", + caveat="the runtime's output cap must leave room for the description"), + FollowUp("N", "causal_trace", {"target": "gold"}, + "which layers and positions carry the media's effect on the gold margin"), + FollowUp("U", "self_consistency", {"n": 10}, + "with twice the samples, how often does the answer move"), + FollowUp("U", "logprob_entropy", {}, + "is the answer that moves a near tie in the answer-token probabilities"), + FollowUp("U", "format_sensitivity", {}, + "with the options rotated, does the answer follow content or position", + task_kinds=("multiple_choice_letter",)), + FollowUp("S", "prompt_contrast", {"strategies": DESCRIBE_STRATEGIES}, + "does a stable error survive when the model first states what it sees", + caveat="the runtime's output cap must leave room for the description"), + FollowUp("S", "gradcam", {"target": "gold"}, + "which image regions the gold margin depends on (no reference regions: " + "concentration only, not 'mislocalised')"), + FollowUp("S", "tuned_lens", {}, + "a fitted per-layer readout of the answer position: at what depth the wrong answer forms"), +) + +#: Not a tool call: extending the nested sample is an action of its own that +#: the controller cannot take yet. +EXPAND = {"analyzer": "(nested sample expansion)", "status": "not_implemented", + "reason": "expansion is not a controller action yet (MVP-2); rerun with a larger --triage-n-fail"} + + +def _route_cases(records: list[dict[str, Any]], route: str) -> list[str]: + return [r["case_id"] for r in records if r["label"] == "fail" and route in r["routes"]] + + +def propose(records: list[dict[str, Any]], model: Any, sample: Any, *, task_kind: "str | None", + extras: "dict[str, dict[str, Any]] | None" = None, + executed: "set[tuple[str, str]] | None" = None) -> dict[str, Any]: + """Follow-ups per route with FAIL cases, each with ``status``: + ``executable`` / ``unsupported`` / ``not_applicable`` / ``already_run`` / ``could_not_build``. + + *executed* holds ``(analyzer, canonical config)`` pairs this run already + executed (the plan's own steps). *extras* are the host's constructor extras + per analyzer, as for the plan. + """ + from evalrx.core.registry import registry + + extras = extras or {} + executed = executed or set() + out: list[dict[str, Any]] = [] + for route in ("H", "N", "U", "S"): + cases = _route_cases(records, route) + if not cases: + continue + for f in (x for x in FOLLOW_UPS if x.route == route): + config = {**f.config, **extras.get(f.analyzer, {})} + row: dict[str, Any] = {"route": route, "n_fail_cases": len(cases), "analyzer": f.analyzer, + "config": canonical(f.config), "question": f.question} + if f.caveat: + row["caveat"] = f.caveat + if f.task_kinds and task_kind not in f.task_kinds: + out.append({**row, "status": "not_applicable", "reason": f"for task kinds {list(f.task_kinds)}"}) + continue + if (f.analyzer, str(canonical(config))) in executed: + out.append({**row, "status": "already_run", "reason": "the plan ran this configuration"}) + continue + try: + analyzer = registry.analyzers.get(f.analyzer)(**config) + except Exception as exc: # noqa: BLE001 - a proposal that cannot be built says so + out.append({**row, "status": "could_not_build", "reason": f"{type(exc).__name__}: {exc}"}) + continue + why = gate(analyzer, model, sample) + out.append({**row, "status": "unsupported" if why else "executable", "reason": why or ""}) + out.append({"route": route, "n_fail_cases": len(cases), **EXPAND}) + untested = Counter(reason.split(":")[0] for r in records if r["routes"] == ["X"] for reason in r["x_reasons"]) + return {"candidates": out, "x_untested": dict(untested), + "_note": "proposed by rule from the routes on this sample, gated on this model; none was run"} diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index 464da0de..2f93305c 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -10,12 +10,25 @@ but are excluded from the FAIL-vs-PASS routing signal, which they would produce by construction. Truncation fields are untested when the host, not the backend, supplied ``finish_reason``. -* **N** (insensitive to a media swap): only a real swap with a different-content - donor and a non-empty baseline answer counts; a swap that fell back to drop - is a different intervention and leaves N untested. -* **U** is untested in MVP-0 (no repeated sampling or perturbation runs), and - **S** is not assigned: it needs the U and other behavioural checks first. -* **X**: no H or N signal fired; the case stays unexplained, with the reasons. +* **N** (an answer that should change with the media does not): only a real + swap with a non-empty baseline answer counts, and on few-answer tasks only a + counterfactual donor (the same question's gold on that media differs from the model's answer); + a content-only swap there, or a swap that fell back to drop, leaves N untested. +* **U** (an answer that moves): two parts, both required. ``self_consistency`` + samples at the host's sampling settings against the Stage-0 answer (greedy + settings leave it untested: identical samples are not a measurement), and + ``prompt_contrast`` wrappers that keep the question verbatim against the + re-asked baseline (a wrapper whose answer is unreadable is an invalid + control, not an unstable answer). Answers are compared by the task's answer + key, never graded. Any readable answer that differs fires U. +* **S** (a stable failure): a FAIL case on which every required check ran and + none fired — H, N (cases with media) and both U parts. S is an + investigation route, not a cause; the S readings attached to every case + (the threshold instruction, the question word on the media tokens, whether + the gold answer was readable before the output) are descriptive. +* **X**: no route fired and a required check is missing, with the reasons. A + missing check never makes a case S. A PASS case with every check clear has + no route (it is a stable control). ``attention_knockout`` is not a route: its per-case margins and fidelity verdict are attached to each case as the first N-layer measurement. @@ -23,8 +36,11 @@ from __future__ import annotations -from typing import Any +from collections import Counter +from typing import Any, Callable +from evalrx.analyzers.perturbation.prompt_contrast import _norm_answer +from evalrx.core.case import MEDIA_SLOTS from evalrx.eval_agent.probing.actions import OK, Observation FIRED, CLEAR, UNTESTED, NOT_APPLICABLE = "fired", "clear", "untested", "not_applicable" @@ -43,6 +59,21 @@ _FIRING_CLASSES = {"truncated", "degenerate", "gave_up"} _KNOCKOUT_FIELDS = ("ko_margin_clean", "ko_delta_full", "ko_rel_drop_full", "ko_flips_top1", "ko_delta_early", "ko_delta_mid", "ko_delta_late") +_EMBED_FIELDS = ("el_query_word", "el_query_sim", "el_frac_specific") +_PATCHSCOPE_FIELDS = ("ps_final_prob", "ps_peak_prob", "ps_peak_depth_frac", "ps_late_drop", + "ps_first_depth_frac", "ps_media_query_hits", "ps_media_query_found") + +AnswerFn = Callable[[Any, str], "str | None"] + + +def default_answer(case: Any, text: str) -> str: + """Coarse answer key when the host gives none: yes/no, else a normalised prefix.""" + return _norm_answer(str(text or "")) + + +def _has_media(case: Any) -> bool: + inputs = getattr(case, "inputs", None) + return any(getattr(inputs, slot, None) is not None for slot in MEDIA_SLOTS) def finish_reason_source(case: Any, host_assumed: bool) -> str: @@ -101,7 +132,10 @@ def _combine(fields: list[dict[str, Any]]) -> str: return UNTESTED -def _n_check(obs: "Observation | None", cid: str) -> dict[str, Any]: +def _n_check(obs: "Observation | None", case: Any, needs_counterfactual: bool) -> dict[str, Any]: + cid = str(case.id) + if not _has_media(case): + return {"state": NOT_APPLICABLE, "reason": "the case has no media to swap"} why = _unavailable(obs, "modality_ablation") if why is not None: return {"state": UNTESTED, "reason": why} @@ -124,8 +158,24 @@ def _n_check(obs: "Observation | None", cid: str) -> dict[str, Any]: if row.get(f"ablation_{slot}_is_swap") is not True: entry.update(state=UNTESTED, reason="no case held different media; the slot was dropped, " "which is a different intervention") + slots.append(entry) + continue + kind = row.get(f"ablation_{slot}_donor_kind") or "content" + expected = row.get(f"ablation_{slot}_donor_expected") + entry.update(donor_kind=kind, donor_expected=expected, answer_changed=bool(row[key])) + if kind == "counterfactual": + # the same question's gold on the donor media differs from the model's answer: + # a correct answer there has to be different + entry.update(state=FIRED if row[key] is False else CLEAR, + follows_donor=_norm_answer(str(entry["swapped_answer"] or "")) == expected) + elif needs_counterfactual: + entry.update(state=UNTESTED, + reason="no counterfactual donor in the partition (same question, different " + "media, gold different from the model's answer); on a few-answer task " + "an unchanged answer after a content-only swap may simply be correct") else: - entry.update(state=FIRED if row[key] is False else CLEAR, answer_changed=bool(row[key])) + entry.update(state=FIRED if row[key] is False else CLEAR, + assumption="open-answer task: different media is assumed to change the answer") slots.append(entry) if not slots: return {**out, "state": UNTESTED, "reason": "no slot was ablated"} @@ -148,11 +198,144 @@ def _knockout(obs: "Observation | None", cid: str) -> dict[str, Any]: return {**out, "state": "measured", **{k: row[k] for k in _KNOCKOUT_FIELDS if k in row}} +def _samples_vary(gen: dict[str, Any]) -> bool: + try: + temperature = float(gen.get("temperature") or 0.0) + except (TypeError, ValueError): + temperature = 0.0 + return bool(gen.get("do_sample")) or temperature > 0.0 + + +def _u_sampling(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: + why = _unavailable(obs, "self_consistency") + if why is not None: + return {"part": "sampling", "state": UNTESTED, "reason": why} + cid = str(case.id) + gen = (obs.params or {}).get("gen_kwargs") or {} + out: dict[str, Any] = {"part": "sampling", "action_id": obs.action_id, "gen_kwargs": gen} + if not _samples_vary(gen): + return {**out, "state": UNTESTED, "reason": "greedy decoding (no temperature or do_sample in " + "gen_kwargs): repeated samples are identical by construction"} + samples = ((obs.per_case().get(cid) or {}).get("artifacts") or {}).get("samples") + if not samples: + return {**out, "state": UNTESTED, "reason": obs.missing.get(cid, "no samples kept for this case")} + base = answer_fn(case, str(getattr(case, "observed", "") or "")) + if base is None: + return {**out, "state": UNTESTED, "reason": "the task has no categorical answer to compare"} + if not base: + return {**out, "state": UNTESTED, "reason": "the Stage-0 output commits to no readable answer"} + answers = [answer_fn(case, str(s)) for s in samples] + readable = [a for a in answers if a] + out.update(base_answer=base, n_samples=len(answers), n_unreadable=len(answers) - len(readable), + answers=dict(Counter(readable))) + if not readable: + return {**out, "state": UNTESTED, "reason": "no sample commits to a readable answer"} + out["agreement"] = round(sum(a == base for a in readable) / len(readable), 4) + return {**out, "state": FIRED if out["agreement"] < 1.0 else CLEAR} + + +def _outputs(obs: Observation) -> dict[str, dict[str, str]]: + return ((obs.findings or {}).get("artifacts") or {}).get("outputs") or {} + + +def _u_reword(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: + why = _unavailable(obs, "prompt_contrast (rewording)") + if why is not None: + return {"part": "reword", "state": UNTESTED, "reason": why} + cid = str(case.id) + outputs = _outputs(obs) + out: dict[str, Any] = {"part": "reword", "action_id": obs.action_id} + if cid not in (outputs.get("baseline") or {}): + return {**out, "state": UNTESTED, "reason": obs.missing.get(cid, "case not re-asked")} + base = answer_fn(case, outputs["baseline"][cid]) + if base is None: + return {**out, "state": UNTESTED, "reason": "the task has no categorical answer to compare"} + if not base: + return {**out, "state": UNTESTED, "reason": "the re-asked question commits to no readable answer"} + variants = {s: answer_fn(case, texts[cid]) for s, texts in outputs.items() if s != "baseline" and cid in texts} + valid = {s: a for s, a in variants.items() if a} + out.update(base_answer=base, answers=valid, invalid_controls=sorted(s for s in variants if s not in valid), + baseline_matches_stage0=answer_fn(case, str(getattr(case, "observed", "") or "")) == base) + if not valid: + return {**out, "state": UNTESTED, + "reason": f"no wrapper gave a readable answer (invalid controls: {out['invalid_controls']})"} + out["changed"] = sorted(s for s, a in valid.items() if a != base) + return {**out, "state": FIRED if out["changed"] else CLEAR} + + +def _u_check(sampling: "Observation | None", reword: "Observation | None", case: Any, + answer_fn: AnswerFn) -> dict[str, Any]: + """U fires when either part fires; it is clear only when both parts ran and are clear.""" + parts = [_u_sampling(sampling, case, answer_fn), _u_reword(reword, case, answer_fn)] + states = [p["state"] for p in parts] + state = FIRED if FIRED in states else CLEAR if all(st == CLEAR for st in states) else UNTESTED + out: dict[str, Any] = {"state": state, "parts": parts} + if state == UNTESTED: + out["reason"] = "; ".join(f"{p['part']}: {p['reason']}" for p in parts if p["state"] == UNTESTED) + return out + + +def _s_threshold(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: + """The answer under the changed decision criterion, against the re-asked baseline.""" + if obs is None: + return {"state": UNTESTED, "reason": "threshold instruction not in the plan for this task"} + why = _unavailable(obs, "prompt_contrast (threshold)") + if why is not None: + return {"state": UNTESTED, "reason": why} + cid = str(case.id) + outputs, scored = _outputs(obs), (obs.findings or {}).get("by_strategy") or {} + variant = next((s for s in outputs if s != "baseline"), None) + if variant is None or cid not in (outputs.get("baseline") or {}) or cid not in (outputs.get(variant) or {}): + return {"state": UNTESTED, "reason": obs.missing.get(cid, "case not re-asked")} + base, alt = answer_fn(case, outputs["baseline"][cid]), answer_fn(case, outputs[variant][cid]) + out: dict[str, Any] = {"action_id": obs.action_id, "strategy": variant, "base_answer": base, "answer": alt} + if not base or not alt: + return {**out, "state": UNTESTED, "reason": "an answer was unreadable or the task has no answer key"} + before, after = (scored.get("baseline") or {}).get(cid), (scored.get(variant) or {}).get(cid) + out.update(changed=alt != base, fixed=before == 0.0 and after == 1.0, broken=before == 1.0 and after == 0.0) + return {**out, "state": "measured"} + + +def _measured_row(obs: "Observation | None", cid: str, analyzer: str, keys: tuple[str, ...]) -> dict[str, Any]: + why = _unavailable(obs, analyzer) + if why is not None: + return {"state": UNTESTED, "reason": why} + row = obs.per_case().get(cid) + if row is None: + return {"state": UNTESTED, "action_id": obs.action_id, "reason": obs.missing.get(cid, "no per_case row")} + return {"state": "measured", "action_id": obs.action_id, **{k: row[k] for k in keys if k in row}} + + +def _s_patchscope(obs: "Observation | None", cid: str) -> dict[str, Any]: + out = _measured_row(obs, cid, "patchscope", _PATCHSCOPE_FIELDS) + if out["state"] == "measured": + out["target"] = (obs.params or {}).get("target") + out["fidelity"] = (obs.fidelity or {}).get("status") + # ranked first at some read layer before the last: formed, then not output + out["target_first_before_last"] = float(out.get("ps_first_depth_frac", 1.0)) < 1.0 + return out + + def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assumed_finish: bool, - answer_contract: bool) -> list[dict[str, Any]]: - """One record per case: label, stratum, every H/N check, knockout row, routes.""" + answer_contract: bool, n_needs_counterfactual: bool = False, + answer_fn: "AnswerFn | None" = None) -> list[dict[str, Any]]: + """One record per case: label, stratum, every H/N/U check, routes, knockout and S readings. + + *observations* are keyed by plan step (``prompt_reword`` and + ``prompt_threshold`` are the two ``prompt_contrast`` steps). + + *n_needs_counterfactual* (few-answer tasks: yes/no, letters): a swap only + tests N when its donor is a counterfactual — the same question's gold on that + media differs from the model's answer — because a content-only swap there often leaves the + correct answer unchanged. + + *answer_fn* ``(case, output) -> key`` reads the answer an output commits to + (``""``: none; ``None``: the task has no categorical answer); default + :func:`default_answer`. + """ from evalrx.eval_agent.probing.sampler import gold_stratum + answer = answer_fn or default_answer records = [] for case in cases: cid = str(case.id) @@ -177,27 +360,38 @@ def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assum "fields": h_fields, "disagreements": disagreements, } - n = _n_check(observations.get("modality_ablation"), cid) - routes = [tag for tag, state in (("H", h["state"]), ("N", n["state"])) if state == FIRED] + n = _n_check(observations.get("modality_ablation"), case, n_needs_counterfactual) + u = _u_check(observations.get("self_consistency"), observations.get("prompt_reword"), case, answer) + label = getattr(getattr(case, "label", None), "value", None) + checks = {"H": h["state"], "N": n["state"], "U": u["state"]} + routes = [tag for tag, state in checks.items() if state == FIRED] + missing = [tag for tag, state in checks.items() if state == UNTESTED] + # every required check ran and none fired: a stable failure, or a stable control + stable = not routes and not missing x_reasons = [] if not routes: - if h["state"] == UNTESTED: - x_reasons.append("H untested") - if n["state"] == UNTESTED: - x_reasons.append(f"N untested: {n.get('reason')}") - x_reasons.append("U untested: MVP-0 runs no repeated sampling or meaning-preserving " - "perturbation; S needs those checks first") - routes = ["X"] + if stable: + routes = ["S"] if label == "fail" else [] + else: + why = {"H": None, "N": n.get("reason"), "U": u.get("reason")} + x_reasons = [f"{tag} untested" + (f": {why[tag]}" if why[tag] else "") for tag in missing] + routes = ["X"] records.append({ "case_id": cid, - "label": getattr(getattr(case, "label", None), "value", None), + "label": label, "stratum": gold_stratum(case), "routes": routes, + "stable": stable, "x_reasons": x_reasons, "H": h, "N": n, - "U": {"state": UNTESTED, "reason": "not run in MVP-0"}, + "U": u, "knockout": _knockout(observations.get("attention_knockout"), cid), + "S_readings": { + "threshold": _s_threshold(observations.get("prompt_threshold"), case, answer), + "embed_lens": _measured_row(observations.get("embed_lens"), cid, "embed_lens", _EMBED_FIELDS), + "patchscope": _s_patchscope(observations.get("patchscope"), cid), + }, }) return records @@ -217,14 +411,11 @@ def _mean(values: list[float]) -> "float | None": def _n_by_base_answer(records: list[dict[str, Any]], max_answers: int = 5) -> "dict[str, Any] | None": """N split by the unablated answer, for categorical answers only. - An unchanged answer is only informative when the donor media should have - changed it. Whether it should is not known here — on POPE, a random donor - image usually lacks the asked-about object too, so an unchanged "No" is - the expected answer while an unchanged "Yes" is not. The split shows which - answers the N signal comes from instead of guessing a donor's gold. + Descriptive: shows which answers the tested N checks come from. Without + counterfactual donors it is also the only guard against reading an + unchanged answer the donor media would warrant anyway (on POPE, a random + image usually lacks the asked-about object, so "No" stays correct). """ - from evalrx.analyzers.perturbation.prompt_contrast import _norm_answer - tested = [r for r in records if r["N"]["state"] in (FIRED, CLEAR)] answers = sorted({_norm_answer(str(r["N"].get("base_answer") or "")) for r in tested}) if not answers or len(answers) > max_answers: @@ -240,8 +431,88 @@ def _n_by_base_answer(records: list[dict[str, Any]], max_answers: int = 5) -> "d return out +def _n_donors(records: list[dict[str, Any]]) -> dict[str, Any]: + """Which donor each case's swap got, and how often a counterfactual swap + moved the answer to the donor's gold (the model followed the new media).""" + out: dict[str, Any] = {} + for label in ("fail", "pass"): + group = [r for r in records if r["label"] == label] + kinds = [(r["N"].get("slots") or [{}])[0] for r in group] + cf = [s for s in kinds if s.get("donor_kind") == "counterfactual"] + out[label] = { + "n": len(group), + "counterfactual": len(cf), + "content": sum(1 for s in kinds if s.get("donor_kind") == "content"), + "no_swap": sum(1 for s in kinds if not s.get("donor_kind")), + "counterfactual_followed_donor": sum(1 for s in cf if s.get("follows_donor")), + } + return out + + +def _threshold_table(records: list[dict[str, Any]]) -> "dict[str, Any] | None": + """Threshold-instruction outcomes by label and stratum (every measured case).""" + groups: dict[tuple[str, str], dict[str, Any]] = {} + for r in records: + t = r["S_readings"]["threshold"] + if t["state"] != "measured": + continue + g = groups.setdefault((str(r["label"]), str(r["stratum"])), { + "label": r["label"], "stratum": r["stratum"], "n_measured": 0, "n_changed": 0, + "n_fixed": 0, "n_broken": 0}) + g["n_measured"] += 1 + g["n_changed"] += int(bool(t["changed"])) + g["n_fixed"] += int(bool(t["fixed"])) + g["n_broken"] += int(bool(t["broken"])) + if not groups: + return None + return {"groups": [groups[k] for k in sorted(groups)], + "_note": ("the same cases re-asked with the instruction against re-asked unchanged; fixed = " + "wrong to right, broken = right to wrong. Fixing missed objects while breaking correct " + "negatives moves the decision criterion; it does not by itself explain the error")} + + +#: Who the S readings are summarised over: the S route, the other failures, and +#: the PASS cases on which every check ran clear (the controls). +_COHORTS: dict[str, Callable[[dict[str, Any]], bool]] = { + "S": lambda r: r["label"] == "fail" and r["stable"], + "fail_not_stable": lambda r: r["label"] == "fail" and not r["stable"], + "stable_pass": lambda r: r["label"] == "pass" and r["stable"], +} + + +def _s_readings(records: list[dict[str, Any]]) -> dict[str, Any]: + """Embed-lens and Patchscope readings per cohort and stratum; descriptive only.""" + out: dict[str, Any] = {} + for name, pick in _COHORTS.items(): + for stratum in sorted({r["stratum"] for r in records if pick(r)}): + group = [r for r in records if pick(r) and r["stratum"] == stratum] + el = [r["S_readings"]["embed_lens"] for r in group + if r["S_readings"]["embed_lens"]["state"] == "measured"] + ps = [r["S_readings"]["patchscope"] for r in group + if r["S_readings"]["patchscope"]["state"] == "measured"] + read = [x for x in ps if "ps_media_query_hits" in x] + out.setdefault(name, {})[stratum] = { + "n": len(group), + "embed_lens": {"n": len(el), "mean_query_sim": _mean( + [float(x["el_query_sim"]) for x in el if "el_query_sim" in x])}, + "patchscope": { + "n": len(ps), + "n_target_first_before_last": sum(1 for x in ps if x["target_first_before_last"]), + "mean_peak_prob": _mean([float(x["ps_peak_prob"]) for x in ps if "ps_peak_prob" in x]), + "mean_final_prob": _mean([float(x["ps_final_prob"]) for x in ps if "ps_final_prob" in x]), + "mean_late_drop": _mean([float(x["ps_late_drop"]) for x in ps if "ps_late_drop" in x]), + "n_media_query_read": len(read), + "n_media_query_hit": sum(1 for x in read if x["ps_media_query_hits"] > 0), + }, + } + out["_note"] = ("descriptive only, no test: el_query_sim = the case's own question word against the media " + "tokens; target_first_before_last = the patchscope target (gold) ranked first at some layer " + "before the last; media_query_hit = the question word decoded off some media token") + return out + + def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: - """Per-route FAIL/PASS rates on this sample, and the descriptive knockout summary. + """Per-route FAIL/PASS rates on this sample, the S cohort and its descriptive readings. ``routing_signal = max(0, P(tag|FAIL) - P(tag|PASS))`` steers where the next actions go on THIS sample; it is not an explained share of failures @@ -250,6 +521,7 @@ def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: tags = { "H_label_free": lambda r: r["H"]["state_label_free"], "N": lambda r: r["N"]["state"], + "U": lambda r: r["U"]["state"], } out: dict[str, Any] = {"n_cases": len(records)} for tag, state_of in tags.items(): @@ -261,8 +533,17 @@ def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: label: _rate(records, label, lambda r: r["H"]["state"]) for label in ("fail", "pass") } out["N_by_base_answer"] = _n_by_base_answer(records) + out["N_donors"] = _n_donors(records) + out["U_parts"] = { + part: {label: _rate(records, label, lambda r, i=i: r["U"]["parts"][i]["state"]) for label in ("fail", "pass")} + for i, part in enumerate(("sampling", "reword")) + } + out["S"] = {"fail": sum(1 for r in records if r["routes"] == ["S"]), + "stable_pass": sum(1 for r in records if r["label"] == "pass" and r["stable"])} out["X"] = {label: sum(1 for r in records if r["label"] == label and r["routes"] == ["X"]) for label in ("fail", "pass")} + out["S_threshold"] = _threshold_table(records) + out["S_readings"] = _s_readings(records) ko: dict[str, Any] = {} for label in ("fail", "pass"): rows = [r["knockout"] for r in records if r["label"] == label and r["knockout"]["state"] == "measured"] diff --git a/evalrx/models/backends/api/backend.py b/evalrx/models/backends/api/backend.py index cc194bd8..820fe18b 100755 --- a/evalrx/models/backends/api/backend.py +++ b/evalrx/models/backends/api/backend.py @@ -115,6 +115,19 @@ def generate(self, inputs: Any, **kwargs) -> str: model_name = self.spec.hf_repo or self.spec.key return self._generate_fn(prompt, model=model_name, **self._media(inputs), **kwargs) + def usage_counters(self) -> "dict[str, int] | None": + """Cumulative requests, retries and token counts of the runtime, or ``None``. + + Read from the ``state`` a runtime factory exposes on its functions + (:mod:`~evalrx.models.backends.api.gemini`); a runtime without one + reports nothing rather than zeros. + """ + state = getattr(self._generate_fn, "state", None) + if not isinstance(state, dict) or "usage" not in state: + return None + return {"requests": int(state.get("calls", 0)), "retries": int(state.get("retries", 0)), + **{k: int(v) for k, v in (state.get("usage") or {}).items()}} + def chat(self, messages: list, tools=None) -> ChatTurn: model_name = self.spec.hf_repo or self.spec.key if self._chat_fn is not None: diff --git a/evalrx/models/backends/api/gemini.py b/evalrx/models/backends/api/gemini.py index 84dfebd1..74e990ee 100644 --- a/evalrx/models/backends/api/gemini.py +++ b/evalrx/models/backends/api/gemini.py @@ -268,10 +268,14 @@ def __init__(self, *, api_key: Optional[str], client: Any, timeout: float, retri self.policy = policy self.top_logprobs = int(top_logprobs) self.sampling = dict(sampling) - #: shared, readable through ``fn.state`` on every factory output + #: shared, readable through ``fn.state`` on every factory output; ``usage`` + #: sums the token counts every successful response reports (cumulative, + #: so a caller meters a stretch of work by differencing two reads) self.state: dict[str, Any] = { "model_version": None, "calls": 0, "retries": 0, "thinking_fallback": [], "headroom_for": [], + "usage": {"prompt_tokens": 0, "completion_tokens": 0, "thought_tokens": 0, + "responses_without_usage": 0}, } self._lock = threading.Lock() silence_sdk_chatter() @@ -342,14 +346,23 @@ def request(self, model: str, contents: Any, extra: dict, *, system: Any = None, continue if attempt < self.retries and _retryable(exc): delay = min(30.0, 1.5 * (2 ** attempt)) + random.uniform(0.0, 0.5) - self.state["retries"] += 1 + with self._lock: + self.state["retries"] += 1 logger.warning("gemini %s: %s; retry %d/%d in %.1fs", model, text[:120], attempt + 1, self.retries, delay) time.sleep(delay) attempt += 1 continue raise - self.state["calls"] += 1 + usage = _usage(response) + with self._lock: # discovery fans requests out over threads + self.state["calls"] += 1 + totals = self.state["usage"] + if usage is None: + totals["responses_without_usage"] += 1 + else: + for key, value in usage.items(): + totals[key] += value version = getattr(response, "model_version", None) if version: self.state["model_version"] = version diff --git a/evalrx/models/backends/api/prices.py b/evalrx/models/backends/api/prices.py new file mode 100644 index 00000000..f4642d4f --- /dev/null +++ b/evalrx/models/backends/api/prices.py @@ -0,0 +1,38 @@ +"""API prices, dated, for turning recorded token counts into an upper-bound USD cost. + +Only prices checked on the provider's page are listed; a model without an +entry costs ``None`` (unknown), never a guess. Prices change, so every entry +carries the date it was read and the page it was read from. The token counts +come from the responses' usage metadata, which does not report implicit cache +hits, so the input part is an upper bound. +""" + +from __future__ import annotations + +from typing import Any + +GEMINI_PRICING_PAGE = "https://ai.google.dev/gemini-api/docs/pricing" + +#: USD per 1M tokens, standard paid tier, not batch. Output includes thinking tokens. +PRICES: dict[str, dict[str, Any]] = { + "gemini-3.1-flash-lite": {"input": 0.25, "output": 1.50, "checked": "2026-10-17", "source": GEMINI_PRICING_PAGE}, + "gemini-3.5-flash-lite": {"input": 0.30, "output": 2.50, "checked": "2026-10-17", "source": GEMINI_PRICING_PAGE}, + "gemini-2.5-flash-lite": {"input": 0.10, "output": 0.40, "checked": "2026-10-17", "source": GEMINI_PRICING_PAGE}, +} + + +def price_of(model: "str | None") -> "dict[str, Any] | None": + """The dated price entry for *model* (a model id, with or without ``models/``), or ``None``.""" + key = str(model or "").removeprefix("models/") + return PRICES.get(key) + + +def usd(model: "str | None", usage: "dict[str, Any] | None") -> "float | None": + """Upper-bound cost of *usage* (``prompt_tokens`` / ``completion_tokens`` / + ``thought_tokens``) at *model*'s listed price; ``None`` when either is unknown.""" + price = price_of(model) + if price is None or not usage: + return None + tokens_in = int(usage.get("prompt_tokens", 0) or 0) + tokens_out = int(usage.get("completion_tokens", 0) or 0) + int(usage.get("thought_tokens", 0) or 0) + return round((tokens_in * price["input"] + tokens_out * price["output"]) / 1e6, 6) diff --git a/tests/test_analyzers/test_hybrid_analyzers.py b/tests/test_analyzers/test_hybrid_analyzers.py index 0fb0d653..a8a28f5c 100644 --- a/tests/test_analyzers/test_hybrid_analyzers.py +++ b/tests/test_analyzers/test_hybrid_analyzers.py @@ -127,7 +127,6 @@ def test_linear_knockout_keeps_the_prefix_and_moves_the_answer(hybrid): def test_linear_fidelity_verdict(hybrid): - hybrid._loaded[0].__dict__.pop("_evalrx_linear_fidelity", None) verdict = check_linear_fidelity(hybrid, Inputs(prompt="x", image=image(1)), MEDIA) assert verdict["linear_faithful"] is True assert verdict["linear_layers_engaged"] == verdict["linear_layers_expected"] == 4 @@ -154,6 +153,7 @@ def test_attention_knockout_on_hybrid(hybrid): assert f["layer_kinds"] == {"softmax": 2, "linear": 4} fid = f["tap_fidelity"] assert fid["faithful"] and fid["tap_layers_engaged"] == 2 and fid["linear_layers_engaged"] == 4 + assert fid["n_checked"] == 4 and all("linear_faithful" in c for c in fid["cases"]) # every case assert any(abs(r["ko_delta_full"]) > 0 for r in f["per_case"]) diff --git a/tests/test_analyzers/test_intervention_analyzers.py b/tests/test_analyzers/test_intervention_analyzers.py index 7ee28686..a6496c05 100644 --- a/tests/test_analyzers/test_intervention_analyzers.py +++ b/tests/test_analyzers/test_intervention_analyzers.py @@ -154,15 +154,55 @@ def with_phantom(module): return stack monkeypatch.setattr(attn_tap, "decoder_stack", with_phantom) - module = vlm._loaded[0] - saved = module.__dict__.pop("_evalrx_tap_fidelity", None) - try: - with pytest.raises(RuntimeError, match="does not faithfully reproduce"): - require_fidelity(vlm, Inputs(prompt="x", image=image(0))) - finally: - module.__dict__.pop("_evalrx_tap_fidelity", None) - if saved is not None: - module.__dict__["_evalrx_tap_fidelity"] = saved + with pytest.raises(attn_tap.FidelityError, match="does not faithfully reproduce"): + require_fidelity(vlm, Inputs(prompt="x", image=image(0))) + + +def test_fidelity_is_measured_on_every_call_not_cached(vlm): + inputs = Inputs(prompt="describe", image=image(0)) + before = vlm.n_forwards + check_fidelity(vlm, inputs) + check_fidelity(vlm, inputs) + assert vlm.n_forwards - before == 4 # native + tapped, twice + base = vlm.forward(inputs, capture={Capability.LOGITS}).require(Capability.LOGITS) + before = vlm.n_forwards + verdict = check_fidelity(vlm, inputs, base=base) + assert vlm.n_forwards - before == 1 # the caller's native logits are reused + assert verdict["tap_faithful"] and verdict["tap_argmax_same"] + assert verdict["tap_rel_diff"] == pytest.approx(verdict["tap_max_logit_diff"] / verdict["tap_scale"], abs=1e-5) + + +def test_knockout_checks_every_analysed_case(vlm): + from evalrx.analyzers.patching.attention_knockout import AttentionKnockoutAnalyzer + + batch = CaseBatch(list(_batch(3)) + list(_batch(1, with_gold=False))) + fid = AttentionKnockoutAnalyzer(target="gold").run(vlm, batch).findings["tap_fidelity"] + assert fid["checked"] == "every analysed case" and fid["n_checked"] == 3 # the no-gold case is skipped + assert [c["case"] for c in fid["cases"]] == [c.id for c in list(batch)[:3]] + assert fid["faithful"] and fid["tap_worst_case"] in {c.id for c in batch} + + +def test_a_later_unfaithful_case_refuses_the_whole_batch(vlm, monkeypatch): + from evalrx.analyzers._internals import edits + from evalrx.analyzers.patching.attention_knockout import AttentionKnockoutAnalyzer + + real = edits.check_fidelity + calls = [] + + def flaky(*args, **kwargs): + verdict = real(*args, **kwargs) + calls.append(1) + if len(calls) == 3: # the third case's input is off by more than rtol + verdict = {**verdict, "tap_faithful": False, "tap_rel_diff": 0.02} + return verdict + + monkeypatch.setattr(edits, "check_fidelity", flaky) + batch = _batch(4) + with pytest.raises(attn_tap.FidelityError) as info: + AttentionKnockoutAnalyzer().run(vlm, batch) + verdict = info.value.verdict + assert verdict["n_checked"] == 3 and verdict["failed_case"] == list(batch)[2].id + assert verdict["faithful"] is False and verdict["tap_max_rel_diff"] == 0.02 # ── residual hooks ───────────────────────────────────────────────────────────── @@ -214,6 +254,48 @@ def test_gold_margin_needs_gold_and_tokenizer(vlm): assert why == "" and margin.positive == ord("c") % 90 + 1 and margin.negative != margin.positive +class _Vocab: + """A BPE-like vocabulary: an answer, its spaced and its lower-case form are three ids.""" + + pieces = ["", "Yes", " Yes", "yes", " yes", "No", " No", "no", " no", " a", "A", " A", "?"] + + def __call__(self, text, add_special_tokens=False): + ids, i = [], 0 + while i < len(text): + hits = [j for j, p in enumerate(self.pieces) if p and text.startswith(p, i)] + best = max(hits, key=lambda j: len(self.pieces[j])) if hits else len(self.pieces) - 1 + ids.append(best) + i += len(self.pieces[best]) if hits else 1 + return {"input_ids": ids} + + def decode(self, ids): + return self.pieces[int(ids[0])] + + +def test_margins_compare_an_answer_with_other_answers_not_with_its_own_spellings(monkeypatch): + # Qwen3.5-0.8B on POPE: " Yes" 0.80, "Yes" 0.20 on a correct case. The old + # comparison token was " Yes" -- a gold "Yes" margin was negative there. + from evalrx.analyzers._internals.targets import answer_variants + + monkeypatch.setattr(access, "tokenizer_of", lambda model: _Vocab()) + tok = _Vocab() + assert answer_variants(tok, "Yes") == {1, 2, 3, 4} + assert answer_variants(tok, "A") == {10, 11} # never the article " a" + logits = torch.zeros(1, len(_Vocab.pieces)) + logits[0, [2, 1, 5]] = torch.tensor([3.0, 2.0, 1.0]) # " Yes" > "Yes" > "No" + gold, _ = build_margin("gold", logits, model=object(), case=FailureCase(inputs=Inputs(prompt="q"), + expected="Yes")) + assert (gold.positive, gold.negative, gold.variants) == (2, 5, (1, 2, 3, 4)) + assert math.isclose(gold.value(logits), 2.0) + pred, _ = build_margin("prediction", logits, model=object()) + assert (pred.positive, pred.negative) == (2, 5) + + class _NoDecoder(_Vocab): + decode = None + + assert answer_variants(_NoDecoder(), "Yes") == {1} # nothing confirms the other forms + + # ── analyzers ───────────────────────────────────────────────────────────────── def _assert_result_contract(result, name: str, n_rows: int) -> dict: @@ -753,6 +835,60 @@ def test_patchscope_reads_text_only_cases_and_skips_missing_gold(vlm): assert f["layers_read"] == [0, 2, 5] +class _CharLetters: + """CharTokenizer ids with a decoder: every id reads as a distinct three-letter word.""" + + def __call__(self, text, add_special_tokens=False): + from tests.tiny_whitebox import CharTokenizer + + return CharTokenizer()(text, add_special_tokens) + + def decode(self, ids): + return _LetterDecoder().decode(ids) + + +def test_specific_words_tell_a_case_from_the_template(): + from evalrx.analyzers._internals.words import specific_words + + words = {"a": ("p1", {"is", "snowboard", "image"}), "b": ("p2", {"is", "car", "image"}), + "c": ("p3", {"is", "dog", "image"}), "d": ("p3", {"is", "dog", "image"})} # d asks c's question + got, inferred = specific_words(words) + assert inferred and got == {"a": {"snowboard"}, "b": {"car"}, "c": {"dog"}, "d": {"dog"}} + few, inferred = specific_words({"a": ("p1", {"x"}), "b": ("p2", {"y"})}) + assert not inferred and few == {"a": set(), "b": set()} + + +def test_patchscope_counts_the_question_word_on_media_and_reports_its_self_check(vlm, monkeypatch): + from evalrx.analyzers.lens.patchscope import PatchscopeAnalyzer + + monkeypatch.setattr(access, "tokenizer_of", lambda model: _CharLetters()) + result = PatchscopeAnalyzer(media_layers=2).run(vlm, _batch()) + f = result.findings + assert f["query_words_inferred"] is True and f["patch_fidelity"]["faithful"] is True + for row in f["per_case"]: + own = set(result.artifacts["query_words"][row["sample_id"]]) + assert len(own) == 1 # only the picture number differs between the prompts + decoded = [w.strip().lower() for ws in result.artifacts["media_words"][row["sample_id"]].values() for w in ws] + assert row["ps_media_query_hits"] == sum(w in own for w in decoded) + assert row["ps_media_query_share"] == round(row["ps_media_query_hits"] / len(decoded), 4) + + +def test_patchscope_refuses_when_the_patch_is_not_inert(vlm, monkeypatch): + from evalrx.analyzers._internals import residual + from evalrx.analyzers.lens.patchscope import PatchscopeAnalyzer + + real = residual.batched_patch + + def scaled(model, patches, analyzer=None): + return real(model, {layer: [(r, p, v * 3.0) for r, p, v in rows] for layer, rows in patches.items()}, + analyzer=analyzer) + + monkeypatch.setattr(residual, "batched_patch", scaled) + with pytest.raises(attn_tap.FidelityError) as info: + PatchscopeAnalyzer().run(vlm, _batch(1)) + assert info.value.verdict["faithful"] is False and "layer" in info.value.verdict + + # ── head attribution ────────────────────────────────────────────────────────── def test_per_head_writes_sum_to_the_output_projection(vlm): @@ -936,6 +1072,11 @@ def test_embed_lens_contract_and_grounding(vlm, monkeypatch): assert parts == pytest.approx(1.0, abs=1e-3) sims = result.artifacts["prompt_sims"][row["sample_id"]] assert row["el_prompt_best_sim"] == max(sims.values()) and row["el_prompt_best_word"] in sims + # the question word: only words most of the prompts do not share + own = result.artifacts["query_words"][row["sample_id"]] + assert own and row["el_query_word"] in own + assert row["el_query_sim"] == max(sims[w] for w in own if w in sims) + assert f["query_words_inferred"] is True def test_embed_lens_reads_any_depth(vlm): diff --git a/tests/test_analyzers/test_modality_ablation_swap.py b/tests/test_analyzers/test_modality_ablation_swap.py index f67b09f6..68198e0f 100644 --- a/tests/test_analyzers/test_modality_ablation_swap.py +++ b/tests/test_analyzers/test_modality_ablation_swap.py @@ -110,3 +110,76 @@ def test_in_memory_images_are_compared_by_pixels(): a2 = Image.new("RGB", (4, 4), (255, 0, 0)) b = Image.new("RGB", (4, 4), (0, 0, 255)) assert _media_key(a) == _media_key(a2) != _media_key(b) + + +# ── counterfactual donors ────────────────────────────────────────────────────── + + +def _q(i, image, obj, gold, label=Label.PASS): + return FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"Is there a {obj} in the image?", image=image), + expected=gold, label=label, metadata={"gold": gold}) + + +class _Says(Model): + """Gives one fixed answer, as a model with a strong yes/no prior would.""" + + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text", "image"}) + + def __init__(self, answer: str) -> None: + self.answer = answer + + def generate(self, inputs, **kwargs): + return self.answer + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +def _pope_pool(img): + # per image one Yes and one No question, adjacent; each question repeats across images + return CaseBatch([_q(0, img["a"], "cat", "Yes"), _q(1, img["a"], "dog", "No"), + _q(2, img["b"], "cat", "No"), _q(3, img["b"], "dog", "Yes"), + _q(4, img["c"], "cat", "Yes"), _q(5, img["c"], "dog", "No"), + _q(6, img["d"], "cat", "No"), _q(7, img["d"], "dog", "Yes")]) + + +def test_counterfactual_donor_needs_a_gold_other_than_the_models_answer(tmp_path): + img = _images(tmp_path, ["a", "b", "c", "d"]) + pool = _pope_pool(img) + batch = CaseBatch([list(pool)[i] for i in (1, 2, 5)]) # the probed sample + swap = ModalityAblationAnalyzer(mode="swap", donor_rule="counterfactual", donor_pool=pool) + + # answered "Yes" where the object is absent (a FAIL): a correct answer only has to + # change on media where the same question's gold is "No" -- not on its own gold's opposite + f = swap.run(_Says("Yes"), batch).findings + rows = {r["sample_id"]: r for r in f["per_case"]} + assert {k: r["ablation_image_donor"] for k, r in rows.items()} == {"c1": "c5", "c2": "c6", "c5": "c1"} + assert {r["ablation_image_donor_expected"] for r in rows.values()} == {"no"} + assert all(r["ablation_image_donor_kind"] == "counterfactual" for r in rows.values()) + assert all(r["grounded_in_image"] is False for r in rows.values()) # it said Yes again + assert f["n_counterfactual_image"] == 3 and f["donor_rule"] == "counterfactual" + + # answered "No": the donor must be one where the same question's gold is "Yes" + row = swap.run(_Says("No"), CaseBatch([list(pool)[1]])).findings["per_case"][0] + assert row["ablation_image_donor"] == "c3" and row["ablation_image_donor_expected"] == "yes" + + +def test_counterfactual_falls_back_to_content_and_says_so(tmp_path): + img = _images(tmp_path, ["a", "b"]) + pool = CaseBatch([_q(0, img["a"], "cat", "Yes"), + _q(1, img["b"], "cat", "Yes"), # same question, gold = the model's answer + _q(2, img["a"], "cat", "No")]) # gold differs, but the SAME image + batch = CaseBatch([list(pool)[0]]) + row = ModalityAblationAnalyzer(mode="swap", donor_rule="counterfactual", + donor_pool=pool).run(_Says("Yes"), batch).findings["per_case"][0] + assert row["ablation_image_donor_kind"] == "content" and row["ablation_image_donor"] == "c1" + assert row["ablation_image_donor_expected"] is None + + +def test_content_rule_never_reports_a_counterfactual(tmp_path): + img = _images(tmp_path, ["a", "b"]) + batch = CaseBatch([_q(0, img["a"], "cat", "Yes"), _q(1, img["b"], "cat", "No")]) + f = ModalityAblationAnalyzer(mode="swap").run(_ByImage(), batch).findings + assert {r["ablation_image_donor_kind"] for r in f["per_case"]} == {"content"} + assert f["n_counterfactual_image"] == 0 and f["donor_rule"] == "content" diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index fd16280b..929ac579 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -182,8 +182,10 @@ def _obs(analyzer, rows, status=OK, params=None, error=None): def test_triage_never_reads_missing_as_negative(): cases = CaseBatch([ - FailureCase(id="f", inputs=Inputs(prompt="q"), expected="No", observed="Yes", label=Label.FAIL), - FailureCase(id="p", inputs=Inputs(prompt="q"), expected="No", observed="No", label=Label.PASS), + FailureCase(id="f", inputs=Inputs(prompt="q", image="f.png"), expected="No", observed="Yes", + label=Label.FAIL), + FailureCase(id="p", inputs=Inputs(prompt="q", image="p.png"), expected="No", observed="No", + label=Label.PASS), ]) aea = _obs("answer_extraction_audit", [ {"sample_id": "f", "extraction_suspect": 1, "extraction_point_miss": 0, "output_truncated": 0, "gave_up": 0}, @@ -223,6 +225,32 @@ def test_triage_never_reads_missing_as_negative(): "pass": {"n_tested": 0, "n_fired": 0}} +def test_few_answer_tasks_test_n_only_with_counterfactual_donors(): + cases = CaseBatch([ + FailureCase(id="cf", inputs=Inputs(prompt="q", image="cf.png"), expected="No", observed="Yes", + label=Label.FAIL), + FailureCase(id="ct", inputs=Inputs(prompt="q", image="ct.png"), expected="No", observed="No", + label=Label.PASS), + ]) + swap = _obs("modality_ablation", [ + {"sample_id": "cf", "ablation_base_answer": "Yes", "grounded_in_image": True, + "ablation_image_is_swap": True, "ablation_image_donor": "d1", "ablation_image_answer": "No", + "ablation_image_donor_kind": "counterfactual", "ablation_image_donor_expected": "no"}, + {"sample_id": "ct", "ablation_base_answer": "No", "grounded_in_image": False, + "ablation_image_is_swap": True, "ablation_image_donor": "d2", "ablation_image_answer": "No", + "ablation_image_donor_kind": "content", "ablation_image_donor_expected": None}, + ], params={"mode": "swap"}) + few = triage_cases(cases, {"modality_ablation": swap}, host_assumed_finish=True, + answer_contract=False, n_needs_counterfactual=True) + assert few[0]["N"]["state"] == "clear" and few[0]["N"]["slots"][0]["follows_donor"] is True + assert few[1]["N"]["state"] == "untested" and "counterfactual" in few[1]["N"]["reason"] + open_answer = triage_cases(cases, {"modality_ablation": swap}, host_assumed_finish=True, + answer_contract=False, n_needs_counterfactual=False) + assert open_answer[1]["N"]["state"] == "fired" and "assumption" in open_answer[1]["N"]["slots"][0] + donors = summarize(few)["N_donors"] + assert donors["fail"]["counterfactual_followed_donor"] == 1 and donors["pass"]["content"] == 1 + + def test_triage_truncation_counts_when_the_backend_reported_it(): cases = CaseBatch([FailureCase(id="f", inputs=Inputs(prompt="q"), expected="1", observed="1 2 3", label=Label.FAIL, metadata={"finish_reason": "length"})]) @@ -234,6 +262,169 @@ def test_triage_truncation_counts_when_the_backend_reported_it(): assert rec["routes"] == ["H"] and rec["H"]["state_label_free"] == "fired" +def test_executor_runs_a_one_case_analyzer_once_per_case_and_keeps_artifacts(): + from evalrx.analyzers._internals.attn_tap import FidelityError + from evalrx.core.analyzer import Analyzer + from evalrx.core.result import Result + + class _OneCase(Analyzer): # like self_consistency: measures cases[0] only + name = "one" + + def __init__(self, fail_on=None): + super().__init__(fail_on=fail_on) + + def _run(self, model, cases): + if cases[0].id == self.fail_on: + raise FidelityError("bad", {"faithful": False}) + out = model.generate(cases[0].inputs) + return Result(analyzer="one", model=repr(model), cases=cases, artifacts={"samples": [out], "big": 1}, + findings={"n_seen": len(cases), "_caveat": "note"}) + + cases = _cases(2, 1) + model = _BlackBox() + obs = execute(_action(cases, "one"), "a", 1, _OneCase(), model, cases, per_case=True, + keep_artifacts=("samples",)) + assert obs.status == OK and obs.cost["calls"] == {"generate": 3} and obs.measured_ids == [c.id for c in cases] + row = obs.per_case()["f0"] + assert row["n_seen"] == 1 and row["artifacts"] == {"samples": ["Yes"]} and "_caveat" not in row + assert obs.findings["_caveat"] == "note" and obs.findings["per_case_mode"] is True + refused = execute(_action(cases, "one"), "b", 1, _OneCase(fail_on="f1"), model, cases, per_case=True, + fidelity_check="patch") + assert refused.status == UNFAITHFUL and refused.findings is None + batch = execute(_action(cases, "one"), "c", 1, _OneCase(), model, cases, keep_artifacts=("samples",)) + assert batch.findings["artifacts"] == {"samples": ["Yes"]} and len(batch.measured_ids) == 0 + + +def _clean_h_and_n(ids, gold_after_swap): + """H rows that fire nothing, and a counterfactual swap each model followed.""" + aea = _obs("answer_extraction_audit", [ + {"sample_id": i, "extraction_suspect": 0, "extraction_point_miss": 0, "output_truncated": 0, "gave_up": 0} + for i in ids]) + ta = _obs("termination_audit", [ + {"sample_id": i, "termination_class": "clean", "looks_truncated": 0, "gave_up": 0} for i in ids]) + swap = _obs("modality_ablation", [ + {"sample_id": i, "ablation_base_answer": "x", "grounded_in_image": True, "ablation_image_is_swap": True, + "ablation_image_donor": "d", "ablation_image_answer": gold_after_swap[i], + "ablation_image_donor_kind": "counterfactual", "ablation_image_donor_expected": gold_after_swap[i].lower()} + for i in ids], params={"mode": "swap"}) + return {"answer_extraction_audit": aea, "termination_audit": ta, "modality_ablation": swap} + + +def _u_obs(samples, reworded, gen_kwargs): + sc = _obs("self_consistency", [{"sample_id": i, "artifacts": {"samples": v}} for i, v in samples.items()], + params={"gen_kwargs": gen_kwargs}) + outputs = {"baseline": {i: v[0] for i, v in reworded.items()}, + "question_frame": {i: v[1] for i, v in reworded.items()}, + "instruction_frame": {i: v[2] for i, v in reworded.items()}} + rw = _obs("prompt_contrast", [{"sample_id": i} for i in reworded]) + rw.findings["artifacts"] = {"outputs": outputs} + return {"self_consistency": sc, "prompt_reword": rw} + + +def _yes_no(case, text): + from evalrx.benchmark.scoring import answer_key + + return answer_key("yes_no", text) + + +def _yn_case(cid, label, gold, observed): + return FailureCase(id=cid, inputs=Inputs(prompt=f"Is there a thing in {cid}?", image=f"{cid}.png"), + expected=gold, observed=observed, label=label, metadata={"gold": gold}) + + +def test_u_needs_both_parts_and_s_is_a_fully_checked_stable_failure(): + cases = CaseBatch([ + _yn_case("s", Label.FAIL, "Yes", "No"), # every check clear -> S + _yn_case("u", Label.FAIL, "Yes", "No"), # one sample says Yes -> U + _yn_case("w", Label.FAIL, "Yes", "No"), # a wrapper flips it -> U + _yn_case("i", Label.FAIL, "Yes", "No"), # wrappers unreadable -> invalid controls -> X + _yn_case("p", Label.PASS, "Yes", "Yes"), # every check clear -> stable control, no route + ]) + ids = [c.id for c in cases] + obs = _clean_h_and_n(ids, {i: "No" if i == "p" else "Yes" for i in ids}) + obs.update(_u_obs( + samples={"s": ["No"] * 5, "u": ["No", "Yes, there is", "No", "no", "No."], "w": ["No"] * 5, + "i": ["No"] * 5, "p": ["Yes"] * 4 + ["I cannot tell"]}, + reworded={"s": ["No", "No.", "no"], "u": ["No", "No", "No"], "w": ["No", "Yes", "No"], + "i": ["No", "Maybe", "Hard to say"], "p": ["Yes", "Yes", "Yes"]}, + gen_kwargs={"temperature": 1.0})) + rec = {r["case_id"]: r for r in triage_cases(cases, obs, host_assumed_finish=True, answer_contract=True, + n_needs_counterfactual=True, answer_fn=_yes_no)} + assert rec["s"]["routes"] == ["S"] and rec["s"]["stable"] + sampling, reword = rec["u"]["U"]["parts"] + assert sampling["state"] == "fired" and sampling["agreement"] == 0.8 and sampling["answers"] == {"no": 4, "yes": 1} + assert rec["u"]["routes"] == ["U"] + assert rec["w"]["routes"] == ["U"] and rec["w"]["U"]["parts"][1]["changed"] == ["question_frame"] + assert rec["i"]["routes"] == ["X"] and rec["i"]["U"]["parts"][1]["invalid_controls"] == [ + "instruction_frame", "question_frame"] + assert any(r.startswith("U untested: reword") for r in rec["i"]["x_reasons"]) + # an unreadable sample is set aside, not counted as a different answer + assert rec["p"]["U"]["parts"][0]["n_unreadable"] == 1 and rec["p"]["U"]["state"] == "clear" + assert rec["p"]["routes"] == [] and rec["p"]["stable"] + s = summarize(list(rec.values())) + assert s["S"] == {"fail": 1, "stable_pass": 1} and s["X"] == {"fail": 1, "pass": 0} + assert s["U"]["fail"] == {"n": 4, "n_tested": 3, "n_fired": 2, "rate": 0.6667} + + # greedy sampling settings: the sampling part is untested, so nothing becomes S + obs.update(_u_obs(samples={i: ["No"] * 5 for i in ids}, reworded={i: ["No"] * 3 for i in ids}, gen_kwargs={})) + greedy = {r["case_id"]: r for r in triage_cases(cases, obs, host_assumed_finish=True, answer_contract=True, + answer_fn=_yes_no)} + assert greedy["s"]["routes"] == ["X"] and "greedy" in greedy["s"]["U"]["reason"] + # a case without media: N does not apply, so it does not block S + text = CaseBatch([FailureCase(id="t", inputs=Inputs(prompt="2+2?"), expected="4", observed="5", + label=Label.FAIL)]) + t_obs = {k: v for k, v in _clean_h_and_n(["t"], {"t": "5"}).items() if k != "modality_ablation"} + t_obs.update(_u_obs(samples={"t": ["5"] * 5}, reworded={"t": ["5", "5", "5"]}, gen_kwargs={"do_sample": True})) + t = triage_cases(text, t_obs, host_assumed_finish=True, answer_contract=True)[0] + assert t["N"]["state"] == "not_applicable" and t["routes"] == ["S"] + + +def test_s_readings_are_summarised_per_cohort_and_stratum(): + cases = CaseBatch([ + _yn_case("s1", Label.FAIL, "Yes", "No"), _yn_case("s2", Label.FAIL, "Yes", "No"), + _yn_case("p1", Label.PASS, "Yes", "Yes"), _yn_case("p2", Label.PASS, "No", "No"), + ]) + ids = [c.id for c in cases] + obs = _clean_h_and_n(ids, {"s1": "Yes", "s2": "Yes", "p1": "No", "p2": "Yes"}) + base = {"s1": "No", "s2": "No", "p1": "Yes", "p2": "No"} + obs.update(_u_obs(samples={i: [base[i]] * 5 for i in ids}, reworded={i: [base[i]] * 3 for i in ids}, + gen_kwargs={"temperature": 1.0})) + th = _obs("prompt_contrast", [{"sample_id": i} for i in ids]) + after = {"s1": "Yes", "s2": "No", "p1": "Yes", "p2": "Yes"} # fixes s1, breaks p2 + th.findings.update( + artifacts={"outputs": {"baseline": base, "sensitive": after}}, + by_strategy={"baseline": {"s1": 0.0, "s2": 0.0, "p1": 1.0, "p2": 1.0}, + "sensitive": {"s1": 1.0, "s2": 0.0, "p1": 1.0, "p2": 0.0}}) + obs["prompt_threshold"] = th + obs["embed_lens"] = _obs("embed_lens", [ + {"sample_id": "s1", "el_query_word": "thing", "el_query_sim": 0.2}, + {"sample_id": "s2", "el_query_word": "thing", "el_query_sim": 0.4}, + {"sample_id": "p1", "el_query_word": "thing", "el_query_sim": 0.5}]) + obs["patchscope"] = _obs("patchscope", [ + {"sample_id": "s1", "ps_first_depth_frac": 0.6, "ps_peak_prob": 0.7, "ps_final_prob": 0.2, + "ps_late_drop": 0.5, "ps_media_query_hits": 3}, + {"sample_id": "s2", "ps_first_depth_frac": 1.0, "ps_peak_prob": 0.1, "ps_final_prob": 0.05, + "ps_late_drop": 0.05, "ps_media_query_hits": 0}, + {"sample_id": "p1", "ps_first_depth_frac": 0.5, "ps_peak_prob": 0.9, "ps_final_prob": 0.9, + "ps_late_drop": 0.0}], params={"target": "gold"}) + rec = triage_cases(cases, obs, host_assumed_finish=True, answer_contract=True, n_needs_counterfactual=True, + answer_fn=_yes_no) + by = {r["case_id"]: r for r in rec} + assert [by[i]["routes"] for i in ids] == [["S"], ["S"], [], []] + assert by["s1"]["S_readings"]["threshold"] == { + "action_id": "id-prompt_contrast", "strategy": "sensitive", "base_answer": "no", "answer": "yes", + "changed": True, "fixed": True, "broken": False, "state": "measured"} + assert by["p2"]["S_readings"]["embed_lens"]["state"] == "untested" + s = summarize(rec) + groups = {(g["label"], g["stratum"]): g for g in s["S_threshold"]["groups"]} + assert groups[("fail", "yes")]["n_fixed"] == 1 and groups[("pass", "no")]["n_broken"] == 1 + cohort = s["S_readings"]["S"]["yes"] + assert cohort["n"] == 2 and cohort["embed_lens"] == {"n": 2, "mean_query_sim": 0.3} + assert cohort["patchscope"]["n_target_first_before_last"] == 1 + assert cohort["patchscope"]["n_media_query_hit"] == 1 and cohort["patchscope"]["n_media_query_read"] == 2 + assert s["S_readings"]["stable_pass"]["yes"]["patchscope"]["n_media_query_read"] == 0 + + # -- controller end to end --------------------------------------------------------------- @@ -243,14 +434,16 @@ def vlm_cases(): pytest.importorskip("transformers") from tests.tiny_whitebox import image + # like POPE: four images, two adjacent questions each (one Yes, one No), and + # the same question asked on several images with opposite golds + layout = [("cat", "Yes"), ("dog", "No"), ("cat", "No"), ("dog", "Yes"), + ("cat", "Yes"), ("dog", "No"), ("cat", "No"), ("dog", "Yes")] imgs = [image(i) for i in range(4)] out = [] - for i in range(8): - img = imgs[i // 2] # two questions per image, adjacent, like POPE - fail = i % 4 == 1 - gold = "No" if i % 2 else "Yes" + for i, (obj, gold) in enumerate(layout): + fail = i in (1, 5) # "dog" absent, answered Yes out.append(FailureCase( - id=f"pope-{i}", inputs=Inputs(prompt=f"Is there a cat in the image {i}?", image=img), + id=f"pope-{i}", inputs=Inputs(prompt=f"Is there a {obj} in the image?", image=imgs[i // 2]), expected=gold, observed="Yes" if fail or gold == "Yes" else "No", label=Label.FAIL if fail else Label.PASS, metadata={"gold": gold, "finish_reason": "stop"}, @@ -264,31 +457,48 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): model = TinyVLM("qwen2_5_vl") ident = {"spec": model.spec.key, "backend": "tiny"} kw = dict(out_dir=tmp_path / "probing", model_identity=ident, n_fail=2, seed=0, - host_assumed_finish=True, stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, - progress=None) + host_assumed_finish=True, n_needs_counterfactual=True, task_kind="yes_no", + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, + stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) report = run_triage_mvp0(model, vlm_cases, **kw) - steps = {s["analyzer"]: s for s in report["steps"]} - assert [s["status"] for s in report["steps"]] == [OK] * 4 + steps = {s["key"]: s for s in report["steps"]} + assert [s["status"] for s in report["steps"]] == [OK] * 9 assert steps["answer_extraction_audit"]["cost"]["calls"] == {} # Stage-0 outputs re-read assert steps["modality_ablation"]["cost"]["calls"] == {"generate": 8} # 4 cases x (base + swap) assert steps["attention_knockout"]["fidelity"]["status"] == "passed" assert steps["termination_audit"]["fidelity"]["status"] == "not_applicable" + assert steps["self_consistency"]["cost"]["calls"] == {"generate": 20} # one call of 5 per case + assert steps["prompt_reword"]["cost"]["calls"] == {"generate": 12} + assert steps["prompt_threshold"]["cost"]["calls"] == {"generate": 8} + assert steps["patchscope"]["fidelity"]["status"] == "passed" checks = report["checks"] assert checks["only_planned_actions"] and checks["stage0_cost_separate"] assert all(checks["case_sets_match_plan"].values()) and all(checks["configs_match_plan"].values()) sample = report["sample"] assert len(sample["fail_ids"]) == 2 and sample["strata"]["no"]["pass"] == 2 + expected_donor = {"pope-1": "pope-3", "pope-5": "pope-7", "pope-2": "pope-4", "pope-6": "pope-0"} for rec in report["cases"]: - assert rec["N"]["state"] in ("fired", "clear") # TinyVLM answers "x" whatever it sees - donor = rec["N"]["slots"][0]["donor"] - assert donor != rec["case_id"] + slot = rec["N"]["slots"][0] + assert slot["donor_kind"] == "counterfactual" and slot["donor"] == expected_donor[rec["case_id"]] + # TinyVLM answers "x" whatever it sees: an answer that had to change did not + assert rec["N"]["state"] == "fired" and slot["follows_donor"] is False assert rec["knockout"]["state"] == "measured" and rec["knockout"]["fidelity"] == "passed" + # ... and not the Stage-0 answer either: re-sampling moved it; the wrappers did not + sampling, reword = rec["U"]["parts"] + assert sampling["state"] == "fired" and sampling["agreement"] == 0.0 and sampling["answers"] == {"x": 5} + assert reword["state"] == "clear" and reword["baseline_matches_stage0"] is False + assert rec["routes"] == ["N", "U"] and not rec["stable"] + assert rec["S_readings"]["threshold"]["state"] == "measured" + assert rec["S_readings"]["patchscope"]["state"] == "measured" + assert rec["S_readings"]["patchscope"]["target"] == "gold" + assert report["summary"]["N_donors"]["fail"]["counterfactual"] == 2 + assert report["summary"]["S"] == {"fail": 0, "stable_pass": 0} out = tmp_path / "probing" costs = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] - assert [c["kind"] for c in costs] == ["stage0"] + ["action"] * 4 + assert [c["kind"] for c in costs] == ["stage0"] + ["action"] * 9 assert costs[1]["baseline_reused"] is True and costs[3]["baseline_reused"] is False for name in ("split_manifest.json", "triage_report.json", "triage_report.md"): assert (out / name).is_file() @@ -301,13 +511,33 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): costs2 = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] assert [c["kind"] for c in costs2[len(costs):]] == ["stage0"] and costs2[-1]["invocation"] == 2 events = [json.loads(line) for line in (out / "selection_trace.jsonl").read_text().splitlines()] - assert [e["event"] for e in events].count("reused") == 4 + assert [e["event"] for e in events].count("reused") == 9 # a different model identity is a different action: nothing is reused other = run_triage_mvp0(model, vlm_cases, **{**kw, "model_identity": {**ident, "dtype": "fp32"}}) assert not any(s["reused"] for s in other["steps"]) +def _rerun(report): + """Steps that executed again instead of being read back (not-applicable steps never run).""" + return [s["key"] for s in report["steps"] if s["status"] != "not_applicable" and not s["reused"]] + + +def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch): + from evalrx.eval_agent.probing import controller + from tests.tiny_whitebox import TinyVLM + + model = TinyVLM("qwen2_5_vl") + kw = dict(out_dir=tmp_path / "v", model_identity={"spec": "tiny"}, n_fail=2, progress=None) + first = run_triage_mvp0(model, vlm_cases, **kw) + real = controller.tool_version + monkeypatch.setattr(controller, "tool_version", + lambda a: real(a) + ("-edited" if a.name == "attention_knockout" else "")) + second = run_triage_mvp0(model, vlm_cases, **kw) + assert _rerun(second) == ["attention_knockout"] + assert second["steps"][3]["action_id"] != first["steps"][3]["action_id"] + + def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): from evalrx.eval_agent.probing.ledger import Ledger from tests.tiny_whitebox import TinyVLM @@ -322,21 +552,81 @@ def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): planned = [e for e in ledger.trace_events() if e.get("event") == "planned" and e["action_id"] == ko_id] assert [e["attempt"] for e in planned] == [1, 2] assert planned[1]["previous_attempts_uncertain"] == 1 - assert [s["reused"] for s in second["steps"]] == [True, True, True, False] + assert _rerun(second) == ["attention_knockout"] def test_mvp0_black_box_gates_off_the_white_box_step(tmp_path, vlm_cases): model = _BlackBox() report = run_triage_mvp0(model, vlm_cases, out_dir=tmp_path / "bb", model_identity={"spec": "bb"}, n_fail=2, progress=None) - steps = {s["analyzer"]: s for s in report["steps"]} + steps = {s["key"]: s for s in report["steps"]} assert steps["attention_knockout"]["status"] == UNSUPPORTED assert steps["attention_knockout"]["cost"]["calls"] == {} assert steps["modality_ablation"]["status"] == OK + assert steps["embed_lens"]["status"] == steps["patchscope"]["status"] == UNSUPPORTED + assert steps["prompt_threshold"]["status"] == "not_applicable" # no task kind given + assert steps["self_consistency"]["status"] == OK assert report["checks"]["no_zero_for_failure"] is True assert all(r["knockout"]["state"] == "untested" for r in report["cases"]) +class _FakeAPI(Model): + """A black-box model that answers Yes and counts requests and tokens like an API runtime.""" + + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text", "image"}) + + def __init__(self): + self.counters = {"requests": 0, "retries": 0, "prompt_tokens": 0, "completion_tokens": 0, + "thought_tokens": 0, "responses_without_usage": 0} + + def generate(self, inputs, **kwargs): + self.counters["requests"] += 1 + self.counters["prompt_tokens"] += 300 + self.counters["completion_tokens"] += 2 + return "Yes" + + def usage_counters(self): + return dict(self.counters) + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +def test_api_run_meters_tokens_and_dollars_and_names_its_next_behavioural_experiments(tmp_path, vlm_cases): + from evalrx.models.backends.api.prices import usd + + model = _FakeAPI() + report = run_triage_mvp0( + model, vlm_cases, out_dir=tmp_path / "api", model_identity={"spec": "fake-api"}, n_fail=2, + task_kind="yes_no", n_needs_counterfactual=True, progress=None, + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, + price_fn=lambda u: usd("gemini-3.1-flash-lite", u), + stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}, "api_usage": {"requests": 8}, "usd": 0.001}) + steps = {s["key"]: s for s in report["steps"]} + for key in ("attention_knockout", "embed_lens", "patchscope"): # no internals: gated, nothing spent + assert steps[key]["status"] == UNSUPPORTED and steps[key]["cost"]["calls"] == {} + swap = steps["modality_ablation"]["cost"] + assert swap["api_usage"]["requests"] == swap["calls"]["generate"] == 8 + assert swap["usd"] == usd("gemini-3.1-flash-lite", swap["api_usage"]) + run = report["cost"]["actions_run"] + assert run["api_usage"]["requests"] == model.counters["requests"] == sum(run["calls"].values()) + assert run["usd"] == round(sum(s["cost"].get("usd") or 0 for s in report["steps"] if s.get("cost")), 6) + assert report["cost"]["stage0"]["usd"] == 0.001 + # sampling ran: the U sampling part is tested, not left untested as on greedy settings + assert all(r["U"]["parts"][0]["state"] in ("fired", "clear") for r in report["cases"]) + # the FAIL cases keep "Yes" after a swap that should make it "no": N, whose next + # behavioural step can run here while the internal one cannot + n_next = {c["analyzer"]: c for c in report["next_candidates"]["candidates"] if c["route"] == "N"} + assert n_next["prompt_contrast"]["status"] == "executable" + assert n_next["causal_trace"]["status"] == "unsupported" and "hidden_states" in n_next["causal_trace"]["reason"] + assert n_next["(nested sample expansion)"]["status"] == "not_implemented" + md = (tmp_path / "api" / "triage_report.md").read_text() + assert "Next candidates" in md and "USD" in md + assert "Not measured: unsupported (model lacks capabilities" in md # knockout, no table of Nones + assert "Not measured: embed_lens unsupported" in md + + def test_cli_default_policy_is_judge_and_triage_refuses_held_out(): from evalrx.benchmark.run import build_parser, run_args @@ -346,3 +636,15 @@ def test_cli_default_policy_is_judge_and_triage_refuses_held_out(): "--diagnosis-mode", "fixed"]) with pytest.raises(ValueError, match="triage_active"): run_args(args) + + +def test_per_call_sampling_is_requested_only_where_the_backend_honours_it(): + from types import SimpleNamespace + + from evalrx.benchmark.runner import _sampling_kwargs + + args = SimpleNamespace(top_p=0.95, top_k=20) + assert _sampling_kwargs(SimpleNamespace(backend="hf_local"), args) == {"temperature": 1.0, "top_p": 0.95, + "top_k": 20} + assert _sampling_kwargs(SimpleNamespace(backend="gemini"), args) == {"temperature": 1.0} # merged per call + assert _sampling_kwargs(SimpleNamespace(backend="endpoint"), args) is None # dropped per call diff --git a/tests/test_examples/test_benchmark_common.py b/tests/test_examples/test_benchmark_common.py index 5353de94..2c293e4b 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -166,6 +166,26 @@ def test_scorers_by_task_kind(common): score("bogus", "x", ["x"]) +def test_answer_keys_read_answers_without_the_gold(common): + # the triage U checks compare these keys across samples and rewordings + _, tasks, scoring, _ = common + key = scoring.answer_key + assert key("yes_no", "Yes, a dog barks.") == key("yes_no", "yes") == "yes" + assert key("yes_no", "maybe") == "" # committed to nothing + assert key("multiple_choice_letter", "the answer: (B)", choices=["A", "B", "C"]) == "B" + assert key("exact_or_numeric", "Final answer: 6.80%") == key("exact_or_numeric", "6.8") == "6.8" + assert key("exact_or_numeric", "Answer: The Beatles") == "beatles" and key("exact_or_numeric", " ") == "" + assert key("short_answer_em", "Answer: The Beatles.") == "beatles" + assert key("llm_graded", "anything") is None # no categorical answer + with pytest.raises(ValueError): + key("bogus", "x") + from evalrx.core.case import FailureCase, Inputs + + case = FailureCase(id="c", inputs=Inputs(prompt="q"), expected="C", + metadata={"task": "multiple_choice_letter", "choices": ["A", "B", "C", "D", "E"]}) + assert tasks.answer_key(case, "E") == "E" # the case's own choices + + def test_parsed_choice_refuses_leaked_thought_preambles_and_enumerations(common): """gemma-4-e2b/MMAU 2026-08-22: 100/256 outputs were a spontaneous ``thought`` channel cut at the 64-token cap while restating the options; the old diff --git a/tests/test_models/test_gemini_compat.py b/tests/test_models/test_gemini_compat.py index c2387cdb..a0743adf 100644 --- a/tests/test_models/test_gemini_compat.py +++ b/tests/test_models/test_gemini_compat.py @@ -364,6 +364,27 @@ def test_api_model_forwards_only_the_modalities_the_spec_declares(): assert client.requests[0]["model"] == "gemini-3.5-flash-lite" +def test_usage_counters_sum_what_each_response_reports(): + """The triage meters an action by differencing two reads of these counters.""" + from evalrx.models.backends.api.prices import usd + from evalrx.models.compose import compose + + no_usage = _reply(Part(text="No")) + no_usage.usage_metadata = None + client = FakeClient([APIError(429, "RESOURCE_EXHAUSTED"), _reply(Part(text="Yes")), no_usage]) + model = compose("gemini-3.1-flash-lite", "api", _runtime(client)) + assert model.usage_counters() == {"requests": 0, "retries": 0, "prompt_tokens": 0, "completion_tokens": 0, + "thought_tokens": 0, "responses_without_usage": 0} + model.generate(Inputs(prompt="a?")) + model.generate(Inputs(prompt="b?")) + counters = model.usage_counters() + assert counters == {"requests": 2, "retries": 1, "prompt_tokens": 10, "completion_tokens": 4, + "thought_tokens": 0, "responses_without_usage": 1} + assert usd("gemini-3.1-flash-lite", counters) == round((10 * 0.25 + 4 * 1.50) / 1e6, 6) + assert usd("models/gemini-3.1-flash-lite", counters) is not None + assert usd("gemini-9-unlisted", counters) is None # no price on record: unknown, not zero + + # ---------------------------------------------------------------------- # Failure handling # ---------------------------------------------------------------------- From a551195d1ddb0a4e8153cc5573db5af185775b53 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:12:48 -0700 Subject: [PATCH 03/26] triage MVP-2: nested expansion as an action, rule-chosen route follow-ups Expansion (rule E1) doubles the nested sample up to --triage-max-fail while a gap more cases can close holds: a positive routing difference whose 95% Newcombe interval still includes zero, or a gold stratum with fewer than 8 S or stable PASS cases. Step evidence is now chunk observations over disjoint case sets (probing/evidence.py): steps whose per-case rows do not depend on the batch (PlanStep.reuse) run on the new cases only, and the batch-dependent descriptive steps (embed_lens, patchscope) run once on the settled sample. An observation index by step identity without the cases lets a later invocation with a larger cap reuse earlier chunks. Follow-ups (probing/rules.py): each route with at least 3 FAIL cases proposes, per round, the next candidate of its first open layer on its FAIL cases plus gold-matched PASS controls; failures fall back within the layer, valid results advance, gated-off candidates are passed over at no cost, and describe-first candidates need an output cap of at least 128 tokens. Every decision is traced with its rule, condition and what it passed over. --triage-max-actions caps the decisions. proposals.py is replaced by the rules; report key steps -> executions. Validated on Qwen3.5-0.8B (8 -> 16 -> 32 FAIL; every case identical to the one-batch 32-FAIL run) and gemini-3.1-flash-lite. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 37 +- docs/agentic_benchmark.md | 10 +- evalrx/benchmark/run.py | 14 +- evalrx/benchmark/runner.py | 17 +- evalrx/eval_agent/probing/__init__.py | 29 +- evalrx/eval_agent/probing/actions.py | 51 ++ evalrx/eval_agent/probing/controller.py | 870 +++++++++++++++------ evalrx/eval_agent/probing/evidence.py | 89 +++ evalrx/eval_agent/probing/ledger.py | 17 +- evalrx/eval_agent/probing/proposals.py | 115 --- evalrx/eval_agent/probing/rules.py | 301 +++++++ evalrx/eval_agent/probing/sampler.py | 6 +- evalrx/eval_agent/probing/triage.py | 138 +++- tests/test_eval_agent/test_probing_mvp0.py | 61 +- tests/test_eval_agent/test_probing_mvp2.py | 407 ++++++++++ 15 files changed, 1763 insertions(+), 399 deletions(-) create mode 100644 evalrx/eval_agent/probing/evidence.py delete mode 100644 evalrx/eval_agent/probing/proposals.py create mode 100644 evalrx/eval_agent/probing/rules.py create mode 100644 tests/test_eval_agent/test_probing_mvp2.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c50e7e0..60668894 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,36 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — triage expansion and rule-chosen follow-ups (MVP-2) + +`--m1-policy triage_active` (policy `mvp2-0`) keeps the nine-step battery and +then lets fixed rules decide what runs next (`probing/rules.py`, version +`mvp2-rules-1`). **Expansion** is a controller action: while a gap holds that +more cases can close — a positive FAIL-minus-PASS routing difference whose 95% +Newcombe interval still includes zero, or a gold stratum with fewer than 8 S +or stable PASS cases — the nested sample doubles up to `--triage-max-fail` +(default 32). A step's observations are now chunks over disjoint case sets +(`probing/evidence.py`): steps whose per-case rows do not depend on the batch +(`PlanStep.reuse`; audits, counterfactual swap with partition donors, +knockout, re-sampling, wrappers) run on the new cases only; `embed_lens` +and `patchscope` (question words inferred from the batch) are not read by any +route, so they run once, on the sample the expansions settle on. An observation index by step identity without the cases lets a +later invocation with a larger cap reuse earlier chunks. **Follow-ups**: each +route with at least 3 FAIL cases proposes, per round, the next candidate of +its first open layer (default representative, then fallbacks), on its FAIL +cases plus gold-matched PASS controls; a failed or refused candidate falls +back within its layer, a valid one advances, candidates the model cannot run +are passed over at no cost, and a layer done on fewer cases is extended +first. `--triage-max-actions` (default 12) caps the decisions; `--triage-budget-sec` +also skips an action whose estimate exceeds what is left. Every decision is a +trace event naming its rule, condition and what it passed over; the report +adds sample revisions, decisions, descriptive follow-up readings (route FAIL +vs controls) and every route's layer states. Report keys changed: `steps` is +now `executions`; `next_candidates` and `probing/proposals.py` are gone (the +rules run the candidates instead of listing them). An edit refused on any +chunk refuses the step on every case. The MVP-0 entry point +`run_triage_mvp0` is the same controller. + ### Added — triage on API models: provider usage, dollars, next experiments (MVP-1) The gemini runtime now sums the token counts every response reports @@ -21,11 +51,8 @@ not reported). The report adds a cost summary for the invocation. On the gemini backend the U sampling check now runs: the runtime merges per-call kwargs over its own sampling, so `self_consistency` gets `temperature=1.0` (the endpoint backend drops per-call kwargs and stays untested). The report -also lists rule-based next candidates (`probing/proposals.py`) for every route -with FAIL cases — behavioural follow-ups first, each built and gated on the -actual model, with `executable` / `unsupported` (and why) / `already_run` / -`not_applicable`; none is run, and sample expansion is listed as not yet an -action. +also listed rule-based next candidates for every route with FAIL cases, each +gated on the actual model (superseded in MVP-2, which runs them). ### Fixed — logit margins compared an answer with its own other spelling diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 9238a53b..a658864a 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -19,7 +19,7 @@ Repair and surgery are excluded from the benchmark controller's tool registry. A Agentic repair does not inject built-in floor candidates. The agent can still propose known repair methods. The existing repair tier/capability constraints and maximum repair rounds remain enforced. This mode is bounded adaptive diagnosis, not an unlimited autonomous training loop. -## Triage policy (opt-in, MVP-0) +## Triage policy (opt-in) `--m1-policy triage_active` replaces the diagnosis with a host-side triage controller (`evalrx/eval_agent/probing/`, design in `evalsmith/probing/probing_design_mix.md`). The default `--m1-policy judge` is unchanged. @@ -29,13 +29,17 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend --m1-policy triage_active --run-tag triage0 ``` -After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed plan exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. No judge is called, M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl`, `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json`, `split_manifest.json`, and `triage_report.{json,md}` with H/N/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips later actions once the wall-clock budget is spent. +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called, M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the wall-clock budget is spent or once its estimate (the same step's earlier seconds per case) exceeds what is left. + +**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Steps whose per-case rows do not depend on the batch (the audits, the swap with donors from the whole partition, the knockout, re-sampling, the wrappers) run on the new cases alone and keep the old rows. `embed_lens` and `patchscope` infer the question words from the batch, but no route reads them, so they wait until the sample stops growing and run once on the whole of it. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). + +**Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls: descriptive, no test, no mechanism named. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Any readable answer that differs fires U. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the gold answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. -On an API model (`--backend gemini`) the same plan runs with the white-box steps recorded as `unsupported` (nothing spent). Each action's cost carries what the provider counted — requests, retries, prompt/completion/thought tokens — and its USD at the dated listed price in `evalrx/models/backends/api/prices.py` (unknown for an unlisted model); Stage 0's usage goes into `baseline.json`. The report ends with next candidates proposed by rule for every route with FAIL cases, each gated on the actual model, so a run without internal state still names which behavioural experiment it could run next and why the internal ones cannot; none is run. +On an API model (`--backend gemini`) the same plan runs with the white-box steps recorded as `unsupported` (nothing spent). Each action's cost carries what the provider counted — requests, retries, prompt/completion/thought tokens — and its USD at the dated listed price in `evalrx/models/backends/api/prices.py` (unknown for an unlisted model); Stage 0's usage goes into `baseline.json`. The rule-chosen follow-ups are gated on the actual model in the same way, so a run without internal state runs its behavioural follow-ups and records why the internal ones cannot run. ```bash GEMINI_API_KEY=... python -m evalrx.benchmark.run --modality vlm --model gemini-3.1-flash-lite \ diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 222af536..b281a199 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -146,12 +146,18 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "(modality-gated on the MODEL, so avoid on multimodal specs for text tasks)") p.add_argument("--m1-policy", choices=["judge", "triage_active"], default="judge", help="judge = the current diagnosis (decision judge over M1-M4, then M5/fix); " - "triage_active = MVP-0 triage controller: after Stage 0, run the fixed " - "triage plan strictly on a matched EXPLORE sample, write the trace, cost " - "ledger and triage report under /probing/, and stop (no judge, no " + "triage_active = triage controller: after Stage 0, run the triage battery " + "strictly on a matched EXPLORE sample, expand it and run route follow-ups " + "chosen by fixed rules, write the trace, cost ledger and triage report " + "under /probing/, and stop (no judge, no " "M2-M5, CONFIRM untouched)") p.add_argument("--triage-n-fail", type=int, default=8, help="triage_active: FAIL cases in the sample (PASS controls are matched per gold answer)") + p.add_argument("--triage-max-fail", type=int, default=32, + help="triage_active: the most FAIL cases the expansion rule may grow the sample to " + "(doubling from --triage-n-fail; a value at or below it disables expansion)") + p.add_argument("--triage-max-actions", type=int, default=12, + help="triage_active: decisions after the battery (expansions + route follow-ups)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, @@ -229,6 +235,8 @@ def run_args(args) -> int: raise ValueError("--m1-policy triage_active works on EXPLORE only; it has no --held-out role yet") if triage and args.triage_n_fail < 1: raise ValueError("--triage-n-fail must be positive") + if triage and args.triage_max_actions < 0: + raise ValueError("--triage-max-actions must be non-negative") dataset = args.dataset or T.DEFAULT_TASK[args.modality] task = T.get(dataset) if task.modality != args.modality: diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index cd625801..a5571757 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -382,13 +382,14 @@ def _price_fn(spec): def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, cases, ctx, run_dir: Path, baseline: dict) -> int: - """``--m1-policy triage_active`` (MVP-0): the fixed triage plan on EXPLORE, then stop. + """``--m1-policy triage_active``: the triage battery, rule-chosen expansions and + follow-ups on EXPLORE, then stop. Same Stage 0 and the same EXPLORE/CONFIRM split as the diagnosis loop; the controller sees EXPLORE only, calls no judge, and runs no M2-M5. Outputs go to ``/probing/``. """ - from evalrx.eval_agent.probing import explore_confirm_split, run_triage_mvp0 + from evalrx.eval_agent.probing import explore_confirm_split, run_triage explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED) runtime = getattr(model, "runtime", None) @@ -397,6 +398,9 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "dtype": getattr(runtime, "dtype", args.dtype), "attn_impl": getattr(runtime, "attn_impl", None), "generation": gen_kwargs, "enable_thinking": bool(args.enable_thinking), } + if not gen_kwargs: + # API backends carry the sampling (and the output cap) in the runtime, not per call + identity["runtime_generation"] = generation_settings(task, args) ctx.config.update(m1_policy="triage_active", judge_provider=None, judge_model=None) # none was built extras: dict = {"modality_ablation": {"score_fn": T.score_case}, "prompt_contrast": {"score_fn": T.score_case}} @@ -405,9 +409,10 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: # API backends ignore per-call kwargs (their runtime samples); without # settings here the U sampling check stays untested, never trivially clear extras["self_consistency"] = {"gen_kwargs": sampling} - report = run_triage_mvp0( + report = run_triage( model, explore, out_dir=run_dir / "probing", model_identity=identity, - n_fail=args.triage_n_fail, seed=args.triage_seed, + n_fail=args.triage_n_fail, max_fail=args.triage_max_fail, max_actions=args.triage_max_actions, + seed=args.triage_seed, stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), @@ -427,7 +432,9 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "model": args.model, "spec": spec.key, "dataset": task.name, "modality": task.modality, "backend": resolved.backend, "n_cases": len(cases), "baseline_accuracy": baseline["accuracy"], "m1_policy": "triage_active", "triage": report["summary"], - "triage_steps": [{k: s.get(k) for k in ("analyzer", "status", "reused")} for s in report["steps"]], + "triage_steps": [{k: s.get(k) for k in ("kind", "key", "analyzer", "status", "reused", "n_cases")} + for s in report["executions"]], + "triage_stop": report["stop"], } (run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n", encoding="utf-8") print(f"Done (triage). {run_dir / 'probing' / 'triage_report.md'}") diff --git a/evalrx/eval_agent/probing/__init__.py b/evalrx/eval_agent/probing/__init__.py index 4a285b98..893a3054 100644 --- a/evalrx/eval_agent/probing/__init__.py +++ b/evalrx/eval_agent/probing/__init__.py @@ -7,34 +7,47 @@ cases and configuration it planned, and records why each action ran, what it cost, and whether its measurement can be trusted. -MVP-0 is a fixed plan with no judge and no M2-M5: +MVP-2 runs a fixed battery, then expansions and follow-ups chosen by fixed +rules, with no judge and no M2-M5: partition.py the same EXPLORE/CONFIRM split the diagnosis loop uses sampler.py matched, nested FAIL/PASS sample (S8 ⊆ S16 ⊆ S32 ...) - actions.py ProbeAction / Observation and their content identities - metering.py per-action call counts, model seconds, GPU peak memory + actions.py PlanStep / ProbeAction / Observation and their content identities + metering.py per-action call counts, model seconds, GPU peak memory, API usage executor.py strict execution: capability gate, typed outcome, no backfill ledger.py append-only selection_trace.jsonl / cost_ledger.jsonl + resume - triage.py H/N/X route labels traced back to case, field and action - controller.py the MVP-0 plan and run_triage_mvp0() + evidence.py one step's observations over a growing sample (per-case reuse) + triage.py H/N/U/S/X route labels traced back to case, field and action + rules.py route layers, follow-up choice, and the expansion rule + controller.py the battery and run_triage() Nothing here is imported by the default ``judge`` path. """ from __future__ import annotations -from evalrx.eval_agent.probing.actions import Observation, ProbeAction -from evalrx.eval_agent.probing.controller import MVP0_PLAN, POLICY_VERSION, run_triage_mvp0 +from evalrx.eval_agent.probing.actions import Observation, PlanStep, ProbeAction +from evalrx.eval_agent.probing.controller import ( + BATTERY, + POLICY_VERSION, + run_triage, + run_triage_mvp0, +) from evalrx.eval_agent.probing.partition import explore_confirm_split +from evalrx.eval_agent.probing.rules import LAYERS, RULES_VERSION from evalrx.eval_agent.probing.sampler import SampleDraw, matched_sample __all__ = [ - "MVP0_PLAN", + "BATTERY", + "LAYERS", "POLICY_VERSION", + "RULES_VERSION", "Observation", + "PlanStep", "ProbeAction", "SampleDraw", "explore_confirm_split", "matched_sample", + "run_triage", "run_triage_mvp0", ] diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/probing/actions.py index f9152d97..c8bc3a1e 100644 --- a/evalrx/eval_agent/probing/actions.py +++ b/evalrx/eval_agent/probing/actions.py @@ -4,6 +4,8 @@ content hash over the analyzer, its full configuration, the ordered case ids and the execution context (model, policy version), so a resumed run recognises a finished action and a changed configuration never reuses an old result. +A :class:`PlanStep` is the template an action is built from; the cases it +runs on are chosen when it is executed. """ from __future__ import annotations @@ -63,6 +65,47 @@ def digest(payload: Any) -> str: return hashlib.sha1(text.encode("utf-8")).hexdigest()[:16] +@dataclass(frozen=True) +class PlanStep: + """What to build, why, and what it may cost: a battery step or a rule's candidate. + + ``key`` names the step when one analyzer serves two steps (default: the + analyzer); evidence is stored under it, so two routes asking the same + step share its observations. ``per_case`` runs a one-case analyzer once + per case; ``keep_artifacts`` keeps those result artifacts with the + findings; ``task_kinds`` limits the step to those task kinds (empty = + every kind). + + ``reuse`` says that a case's row does not depend on which other cases share + the batch, so a larger sample only runs the new cases and keeps the old + rows. A step whose rows do depend on the batch (words inferred from the + batch's prompts, a fit on the batch, noise seeded by batch position) has + ``reuse=False`` and ``reuse_note`` says why: it re-runs on the whole sample. + + ``min_output_tokens``: the step asks for text before the answer (e.g. a + description), so a known output cap below this leaves it nothing to read. + """ + + analyzer: str + config: dict[str, Any] + route: str + purpose: str + fidelity_check: "str | None" = None # "edit" = tap/linear self-check, "patch" = patch self-check + calls_per_case: dict[str, int] = field(default_factory=dict) + key: str = "" + per_case: bool = False + keep_artifacts: tuple[str, ...] = () + task_kinds: tuple[str, ...] = () + reuse: bool = True + reuse_note: str = "" + caveat: str = "" + min_output_tokens: int = 0 + + @property + def name(self) -> str: + return self.key or self.analyzer + + @dataclass(frozen=True) class ProbeAction: """One planned experiment, executed exactly as written. @@ -94,6 +137,14 @@ def identity(self, context: dict[str, Any]) -> str: "case_ids": list(self.case_ids), "context": context, }) + def step_identity(self, context: dict[str, Any]) -> str: + """The identity without the cases: the same experiment, whichever cases it ran on. + + Observations sharing it may be combined case by case only when the + step's rows do not depend on the batch (``PlanStep.reuse``). + """ + return digest({"analyzer": self.analyzer, "config": self.config, "context": context}) + def to_dict(self) -> dict[str, Any]: # a shallow read: asdict() would deep-copy a donor pool's cases (and media) out = canonical({f.name: getattr(self, f.name) for f in fields(self)}) diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index b6516b0c..663dd57c 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -1,24 +1,47 @@ -"""MVP-0: the fixed triage plan, executed strictly, with its trace and costs. - -The plan is a fixed list of actions on one matched sample, in this order: - -1. ``answer_extraction_audit`` (re-reads the Stage-0 outputs; no model call) -2. ``termination_audit`` without continuation (re-reads the outputs too) -3. ``modality_ablation(mode="swap")`` — the N triage check -4. ``attention_knockout(target="gold")`` — the first N-layer measurement, on - white-box backends; elsewhere it is gated off as ``unsupported`` -5. ``self_consistency`` — re-samples each case (U) -6. ``prompt_contrast`` with the question kept verbatim in neutral wrappers (U) -7. ``prompt_contrast`` with an instruction not to default to "no" (yes/no tasks - only): which stable errors move under a changed decision criterion (S) -8. ``embed_lens(layer=0.9)`` — is the case's own question word close to the - media tokens late in the stack (S2) -9. ``patchscope(target="gold", media_layers=3)`` — was the gold answer readable - before the output, and is the question word read off the media tokens (S3, S2) - -No judge is called and nothing is selected adaptively: MVP-0 establishes the -execution, metering, fidelity and trace contracts the adaptive controller -(MVP-3) will be built on. Outputs land in ``out_dir``:: +"""MVP-2: the triage battery, nested expansion and route follow-ups chosen by fixed rules. + +A run goes through three phases: + +1. **Battery.** The battery runs on a matched sample of EXPLORE. Its steps, + in order: + + 1. ``answer_extraction_audit``: re-reads the Stage-0 outputs (no model call). + 2. ``termination_audit`` without continuation: re-reads the outputs too. + 3. ``modality_ablation(mode="swap")``: the N check. + 4. ``attention_knockout(target="gold")``: the first N-layer measurement. + 5. ``self_consistency``: re-samples each case (U). + 6. ``prompt_contrast`` with the question kept verbatim in neutral wrappers (U). + 7. ``prompt_contrast`` with an instruction not to default to "no" (yes/no + tasks only), descriptive S. + 8. ``embed_lens(layer=0.9)``: is the case's own question word near the + media tokens late in the stack (S2). + 9. ``patchscope(target="gold", media_layers=3)``: was the gold answer + readable before the output, and is the question word read off the + media tokens (S3, S2). + +2. **Expansion.** While an evidence gap holds that more cases can close, the + controller decides to expand. The sample then doubles along the sampler's + rank prefixes, and the battery runs again only where it has to: + + * steps whose per-case rows do not depend on the batch run on the new cases + alone, and their old rows stay current; + * steps that infer something from the batch (``embed_lens``, ``patchscope``) + are not read by the routes, so nothing the expansion rule looks at depends + on them: they run once, on the whole sample the expansions settle on. + +3. **Follow-ups.** Each active route proposes its next layer's candidate (see + :mod:`~evalrx.eval_agent.probing.rules`), and the candidate runs on the + route's FAIL cases plus matched PASS controls. + +Every decision is a trace event that names its rule, the condition it read, +and the candidates it passed over and why. The run stops when: + +* no route has a candidate left; +* ``max_actions`` decisions (expansions + follow-ups) have been made; or +* the wall-clock budget is spent, or an action's estimate exceeds what is left. + +No judge is called, no hypothesis is named, and CONFIRM never enters. Outputs +land in ``out_dir``:: split_manifest.json triage_report.json triage_report.md selection_trace.jsonl cost_ledger.jsonl observations/.json @@ -30,49 +53,36 @@ import inspect import json import os -from dataclasses import dataclass, field +from collections import Counter +from functools import partial from pathlib import Path from typing import TYPE_CHECKING, Any, Callable from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES -from evalrx.eval_agent.probing.actions import OK, SKIPPED, ProbeAction, canonical -from evalrx.eval_agent.probing.executor import execute +from evalrx.eval_agent.probing.actions import OK, SKIPPED, PlanStep, ProbeAction, canonical +from evalrx.eval_agent.probing.evidence import StepEvidence +from evalrx.eval_agent.probing.executor import execute, gate from evalrx.eval_agent.probing.ledger import Ledger -from evalrx.eval_agent.probing.proposals import propose -from evalrx.eval_agent.probing.sampler import matched_sample -from evalrx.eval_agent.probing.triage import summarize, triage_cases +from evalrx.eval_agent.probing.rules import ( + LAYERS, + RULES_VERSION, + Layer, + active_routes, + candidate_steps, + expansion_gaps, + next_for_route, + next_size, + public, + route_fail_ids, + route_states, +) +from evalrx.eval_agent.probing.sampler import matched_sample, rank +from evalrx.eval_agent.probing.triage import ROUTE_STEPS, follow_up_reading, summarize, triage_cases if TYPE_CHECKING: from evalrx.core.case import CaseBatch -POLICY_VERSION = "mvp0-2" - - -@dataclass(frozen=True) -class PlanStep: - """One row of the fixed plan: what to build, why, and what it may cost. - - ``key`` names the step when one analyzer serves two steps (default: the - analyzer). ``per_case`` runs a one-case analyzer once per case; - ``keep_artifacts`` keeps those result artifacts with the findings; - ``task_kinds`` limits the step to those task kinds (empty = every kind). - """ - - analyzer: str - config: dict[str, Any] - route: str - purpose: str - fidelity_check: "str | None" = None # "edit" = tap/linear self-check, "patch" = patch self-check - calls_per_case: dict[str, int] = field(default_factory=dict) - key: str = "" - per_case: bool = False - keep_artifacts: tuple[str, ...] = () - task_kinds: tuple[str, ...] = () - - @property - def name(self) -> str: - return self.key or self.analyzer - +POLICY_VERSION = "mvp2-0" #: Neutral wrappers around the question, kept verbatim (with its output #: contract): the meaning cannot change, only the surface. A wrapper whose @@ -86,8 +96,10 @@ def name(self) -> str: #: moves when the model is told not to default to it from one that does not. THRESHOLD_STRATEGIES = {"baseline": "{prompt}", "sensitive": _PROMPT_STRATEGIES["sensitive"]} +_BATCH_WORDS = ("the question words (and recurring media words) are inferred from the batch's prompts " + "and images") -MVP0_PLAN: tuple[PlanStep, ...] = ( +BATTERY: tuple[PlanStep, ...] = ( PlanStep("answer_extraction_audit", {"reask": False}, "H", "re-read Stage-0 outputs for grading and extraction problems"), PlanStep("termination_audit", {"continue_non_clean": False}, "H", @@ -115,12 +127,12 @@ def name(self) -> str: PlanStep("embed_lens", {"layer": 0.9}, "S2", "nearest vocabulary words of the media tokens late in the stack: how close the " "case's own question word gets", - calls_per_case={"forward": 1}), + calls_per_case={"forward": 1}, reuse=False, reuse_note=_BATCH_WORDS), PlanStep("patchscope", {"target": "gold", "media_layers": 3}, "S3", "decode the answer position at every layer and the media tokens at three depths: " "whether the gold answer was readable before the output, and whether the question " "word is read off the media", - fidelity_check="patch", calls_per_case={"forward": 1}), + fidelity_check="patch", calls_per_case={"forward": 1}, reuse=False, reuse_note=_BATCH_WORDS), ) @@ -130,12 +142,6 @@ def _write_json(path: Path, payload: Any) -> None: os.replace(tmp, path) -def _build(step: PlanStep, extra: dict[str, Any]) -> Any: - from evalrx.core.registry import registry - - return registry.analyzers.get(step.analyzer)(**{**step.config, **extra}) - - def tool_version(analyzer: Any) -> str: """Content hash of the analyzer's module and the shared ``analyzers/_internals``. @@ -155,13 +161,232 @@ def tool_version(analyzer: Any) -> str: return h.hexdigest()[:12] -def run_triage_mvp0( +def output_cap(model_identity: dict[str, Any]) -> "int | None": + """The generation cap the host set, per call or in the runtime (``None`` = unknown here).""" + for generation in (model_identity.get("generation") or {}, model_identity.get("runtime_generation") or {}): + for key in ("max_new_tokens", "max_output_tokens", "max_tokens"): + if generation.get(key) is not None: + return int(generation[key]) + return None + + +class _Run: + """The state one invocation carries: evidence per step, the executions, the ledger.""" + + def __init__(self, model: Any, explore: "CaseBatch", ledger: Ledger, *, context: dict[str, Any], + extras: dict[str, dict[str, Any]], task_kind: "str | None", budget_sec: float, + price_fn: Any, run_logger: Any, say: Callable[[str], None]) -> None: + self.model, self.ledger, self.context, self.extras = model, ledger, context, extras + self.task_kind, self.budget_sec, self.price_fn, self.run_logger, self.say = ( + task_kind, budget_sec, price_fn, run_logger, say) + self.by_id = {str(c.id): c for c in explore} + self.order = {str(c.id): i for i, c in enumerate(explore)} + self.evidence: dict[str, StepEvidence] = {} + self.executions: list[dict[str, Any]] = [] + self.blocked: dict[str, str] = {} + + def batch(self, ids: "list[str]") -> "CaseBatch": + from evalrx.core.case import CaseBatch + + return CaseBatch([self.by_id[i] for i in sorted(set(ids), key=self.order.__getitem__)]) + + def config(self, step: PlanStep) -> dict[str, Any]: + return {**step.config, **self.extras.get(step.analyzer, {})} + + def build(self, step: PlanStep) -> Any: + from evalrx.core.registry import registry + + return registry.analyzers.get(step.analyzer)(**self.config(step)) + + def gate(self, step: PlanStep, ids: "list[str]") -> "tuple[str, str] | None": + """Why *step* cannot run on *ids* here — ``(status, reason)`` — before anything is spent.""" + if step.task_kinds and self.task_kind not in step.task_kinds: + return "not_applicable", f"for task kinds {list(step.task_kinds)}; this task is {self.task_kind!r}" + cap = output_cap(self.context.get("model") or {}) + if step.min_output_tokens and cap is not None and cap < step.min_output_tokens: + return "not_applicable", (f"the output cap of {cap} tokens is below the {step.min_output_tokens} " + f"this step needs ({step.caveat or 'text before the answer'})") + try: + analyzer = self.build(step) + except Exception as exc: # noqa: BLE001 - a candidate that cannot be built says so + return "could_not_build", f"{type(exc).__name__}: {exc}" + why = gate(analyzer, self.model, self.batch(ids)) + return ("unsupported", why) if why else None + + def estimate_sec(self, step: PlanStep, n_cases: int) -> "float | None": + ev = self.evidence.get(step.name) + per_case = ev.sec_per_case() if ev is not None else None + return round(per_case * n_cases, 1) if per_case is not None else None + + def over_budget(self, estimate: "float | None") -> "str | None": + if self.budget_sec <= 0: + return None + spent = self.ledger.spent_wall_sec() + if spent >= self.budget_sec: + return f"wall-clock budget {self.budget_sec}s spent" + if estimate is not None and spent + estimate > self.budget_sec: + return f"estimated {estimate}s exceeds the {round(self.budget_sec - spent, 1)}s left" + return None + + def _identity(self, step: PlanStep) -> tuple[Any, str, dict[str, Any], str]: + """``(analyzer, tool version, identity context, step identity)``; raises if it cannot be built.""" + analyzer = self.build(step) + version = tool_version(analyzer) + context = {**self.context, "tool_version": version, "per_case": step.per_case, + "keep_artifacts": list(step.keep_artifacts)} + template = ProbeAction(analyzer=step.analyzer, config=self.config(step), case_ids=(), + route=step.route, purpose=step.purpose) + return analyzer, version, context, template.step_identity(context) + + def adopt_for(self, step: PlanStep, target: "list[str]", *, kind: str, revision: int, + rule_id: "str | None" = None, route: "str | None" = None) -> bool: + """Take up earlier chunks of *step* on *target* before a decision is made about it; + ``True`` when something was taken up (the decision is then re-made).""" + if not step.reuse: + return False + try: + _, _, _, step_id = self._identity(step) + except Exception: # noqa: BLE001 - run_step records the construction failure + return False + ev = self.evidence.setdefault(step.name, StepEvidence(step)) + n = len(ev.chunks) + self._adopt(ev, step_id, target, {"kind": kind, "revision": revision, "key": step.name, + "analyzer": step.analyzer, "rule_id": rule_id, "route": route}) + return len(ev.chunks) > n + + def _log(self, record: dict[str, Any]) -> None: + record["n"] = len(self.executions) + self.executions.append(record) + + def _adopt(self, ev: StepEvidence, step_id: str, target: "list[str]", + base: dict[str, Any]) -> "dict[str, Any] | None": + """Take up chunks of the same step identity measured before (by this run or an earlier + one) on cases of *target* that no chunk covers yet; the last such execution record.""" + record = None + known = {o.action_id for o in ev.chunks} + wanted = set(target) + for obs in self.ledger.chunks_for(step_id): + ids = set(obs.planned_ids) + if obs.action_id in known or not ids & wanted or ids & ev.covered(): + continue + ev.add(obs) + row = {**base, "n_cases": len(ids & wanted), "action_id": obs.action_id, "step_id": step_id} + self.ledger.trace({**row, "event": "reused", "status": obs.status, "attempt": obs.attempt, + "note": "same step identity on other cases; the step's rows do not depend on " + "the batch, so these cases are read from it and not re-run"}) + record = {**row, "status": obs.status, "reused": True, "fidelity": obs.fidelity, + "cost": obs.cost, "error": obs.error} + self._log(record) + self.say(f"[triage] {ev.step.name} ({row['n_cases']} cases): reused chunk ({obs.status})") + return record + + def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: int, + rule_id: "str | None" = None, route: "str | None" = None, + budget_checked: bool = False) -> "dict[str, Any] | None": + """Bring *step*'s evidence up to date on *target*; the execution record, or ``None`` + when every case is already covered.""" + ev = self.evidence.setdefault(step.name, StepEvidence(step)) + base = {"kind": kind, "revision": revision, "key": step.name, "analyzer": step.analyzer, + "rule_id": rule_id, "route": route} + if step.task_kinds and self.task_kind not in step.task_kinds: + if any(e["key"] == step.name and e["status"] == "not_applicable" for e in self.executions): + return None + reason = f"step is for task kinds {list(step.task_kinds)}; this task is {self.task_kind!r}" + self.ledger.trace({**base, "event": "not_applicable", "reason": reason}) + record = {**base, "status": "not_applicable", "reused": False, "reason": reason} + self._log(record) + self.say(f"[triage] {step.name}: not applicable ({self.task_kind})") + return record + config = self.config(step) + try: + analyzer, version, context, step_id = self._identity(step) + except Exception as exc: # noqa: BLE001 - a bad config is an outcome, not a crash + if not ev.todo(target): + return None + reason = f"could not construct: {type(exc).__name__}: {exc}" + self.ledger.trace({**base, "event": "skipped", "status": "failed", "reason": reason}) + self.blocked[step.name] = reason + record = {**base, "status": "failed", "reused": False, "error": str(exc)} + self._log(record) + return record + record = self._adopt(ev, step_id, target, base) if step.reuse else None + + todo = ev.todo(target) + if not todo: + return record + cases = self.batch(todo) + action = ProbeAction( + analyzer=step.analyzer, config=config, case_ids=tuple(str(c.id) for c in cases), + route=step.route, purpose=step.purpose, source=rule_id or kind, + reserve={k: v * len(cases) for k, v in step.calls_per_case.items()}, + ) + action_id = action.identity(context) + base = {**base, "n_cases": len(cases), "action_id": action_id, "step_id": step_id} + + done = self.ledger.settled(action_id) + if done is not None: + self.ledger.trace({**base, "event": "reused", "status": done.status, "attempt": done.attempt, + "note": "terminal observation with the same identity; read back, not re-run"}) + ev.add(done) + record = {**base, "status": done.status, "reused": True, "fidelity": done.fidelity, + "cost": done.cost, "error": done.error} + self._log(record) + self.say(f"[triage] {step.name} ({len(cases)} cases): reused ({done.status})") + return record + + estimate = self.estimate_sec(step, len(cases)) + why = None if budget_checked else self.over_budget(estimate) + if why is not None: + self.ledger.trace({**base, "event": "skipped", "status": SKIPPED, "reason": why}) + self.blocked[step.name] = why + record = {**base, "status": SKIPPED, "reused": False, "reason": why} + self._log(record) + self.say(f"[triage] {step.name}: skipped ({why})") + return record + + prior = self.ledger.attempts(action_id) + attempt = prior + 1 + self.ledger.trace({ + **base, "event": "planned", "attempt": attempt, "action": action.to_dict(), + "params": canonical(analyzer.get_params()), "tool_version": version, + "fidelity_check": step.fidelity_check, "reuse": step.reuse, "estimate_sec": estimate, + **({"previous_attempts_uncertain": prior} if prior else {}), + }) + self.say(f"[triage] {step.name}: running on {len(cases)} cases ({kind}, revision {revision})") + obs = execute(action, action_id, attempt, analyzer, self.model, cases, + fidelity_check=step.fidelity_check, per_case=step.per_case, + keep_artifacts=step.keep_artifacts, run_logger=self.run_logger) + if obs.cost.get("api_usage") is not None: + obs.cost["usd"] = self.price_fn(obs.cost["api_usage"]) if self.price_fn is not None else None + self.ledger.save(obs, step_id=step_id) + self.ledger.cost({"kind": "action", "action_id": action_id, "analyzer": step.analyzer, + "attempt": attempt, "reserved_calls": action.reserve, "estimate_sec": estimate, + "baseline_reused": obs.status == OK and not obs.cost.get("calls"), + "judge_calls": 0, **obs.cost}) + self.ledger.trace({**base, "event": "settled", "attempt": attempt, "status": obs.status, + "fidelity": obs.fidelity.get("status"), "n_measured": len(obs.measured_ids), + "n_missing": len(obs.missing), "error_type": obs.error_type, "error": obs.error}) + ev.add(obs) + record = {**base, "status": obs.status, "reused": False, "fidelity": obs.fidelity, "cost": obs.cost, + "error": obs.error, "n_measured": len(obs.measured_ids), "missing": obs.missing, + "estimate_sec": estimate} + self._log(record) + self.say(f"[triage] {step.name}: {obs.status} (fidelity={obs.fidelity.get('status')}, " + f"{obs.cost.get('wall_sec')}s, calls={obs.cost.get('calls')})") + return record + + +def run_triage( model: Any, explore: "CaseBatch", *, out_dir: "str | Path", model_identity: dict[str, Any], n_fail: int = 8, + max_fail: "int | None" = None, + max_actions: int = 12, + min_route_fail: int = 3, + min_cohort: int = 8, seed: int = 0, stratum: str = "gold", host_assumed_finish: bool = False, @@ -171,14 +396,15 @@ def run_triage_mvp0( answer_fn: "Callable[[Any, str], str | None] | None" = None, analyzer_kwargs: "dict[str, dict[str, Any]] | None" = None, price_fn: "Callable[[dict[str, Any] | None], float | None] | None" = None, - plan: "tuple[PlanStep, ...]" = MVP0_PLAN, + battery: "tuple[PlanStep, ...]" = BATTERY, + layers: "tuple[Layer, ...]" = LAYERS, budget_sec: float = 0.0, stage0_cost: "dict[str, Any] | None" = None, partition: "dict[str, Any] | None" = None, run_logger: Any = None, progress: "Callable[[str], None] | None" = print, ) -> dict[str, Any]: - """Run the fixed triage plan on a matched sample of *explore*; return the report. + """Run the battery, the rule-chosen expansions and follow-ups on *explore*; return the report. Args: model: the model under test. @@ -187,7 +413,13 @@ def run_triage_mvp0( model_identity: spec / weights / backend / dtype / generation settings; part of every action identity, so a different model never reuses an observation. - n_fail: FAIL cases to draw (PASS controls are matched to them). + n_fail: FAIL cases in the first sample (PASS controls are matched to them). + max_fail: the most FAIL cases expansion may reach (``None`` = *n_fail*: + no expansion). + max_actions: decisions after the battery (expansions + follow-ups). + min_route_fail: FAIL cases a route needs before it proposes follow-ups. + min_cohort: S cohort / stable-PASS size per stratum below which the + expansion rule counts a gap. seed: rank seed of the nested sampler. stratum: ``"gold"`` (match PASS on the gold answer) or ``"none"``. host_assumed_finish: the host, not the backend, set ``finish_reason``. @@ -198,16 +430,14 @@ def run_triage_mvp0( task_kind: the task's kind; steps limited to other kinds are recorded as ``not_applicable`` and not run. answer_fn: ``(case, output) -> answer key`` (``""`` = no readable - answer, ``None`` = the task has no categorical answer): - how the U checks tell whether an answer moved. Default: - a coarse yes/no-or-prefix key. + answer, ``None`` = the task has no categorical answer). analyzer_kwargs: per-analyzer constructor extras the host supplies - (e.g. the task's ``score_fn``, the sampling settings); - recorded in the config. - price_fn: ``api_usage -> USD`` (``None`` = no price on record) for - API models; the cost ledger and report carry it. - budget_sec: wall-clock cap on executed actions (0 = none). An action - already running is not interrupted; later ones are skipped. + (e.g. the task's ``score_fn``, the sampling settings). + price_fn: ``api_usage -> USD`` (``None`` = no price on record). + budget_sec: wall-clock cap on executed actions (0 = none). A running + action is not interrupted; one whose estimate (from the + same step's earlier seconds per case) exceeds what is + left is skipped. stage0_cost: the shared baseline cost, logged once and kept separate. partition: how EXPLORE/CONFIRM were split (recorded, not used). run_logger: optional RunLoggerV2 for per-call model logs. @@ -218,11 +448,25 @@ def run_triage_mvp0( extras = {k: dict(v) for k, v in (analyzer_kwargs or {}).items()} # swap donors come from the whole partition the sample was drawn from extras.setdefault("modality_ablation", {}).setdefault("donor_pool", explore) + max_fail = max(int(n_fail), int(max_fail or n_fail)) + n_available = sum(1 for c in explore if getattr(getattr(c, "label", None), "value", None) == "fail") + run = _Run(model, explore, ledger, context={"policy": POLICY_VERSION, "model": model_identity}, + extras=extras, task_kind=task_kind, budget_sec=budget_sec, price_fn=price_fn, + run_logger=run_logger, say=say) + rank_of = partial(rank, seed) + triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, + n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn) + sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) - _write_json(out / "split_manifest.json", { - "policy": POLICY_VERSION, "partition": partition or {}, "n_explore": len(explore), - "sample": draw.to_dict(), - }) + draws = [draw] + + def manifest() -> None: + _write_json(out / "split_manifest.json", { + "policy": POLICY_VERSION, "partition": partition or {}, "n_explore": len(explore), + "sample": draw.to_dict(), "revisions": [d.to_dict() for d in draws], + }) + + manifest() if stage0_cost: # Every invocation's Stage 0 is spent compute (the runner does not cache # it), even when every action is then read back from an earlier run. @@ -231,102 +475,155 @@ def run_triage_mvp0( say(f"[triage] sample: {len(draw.fail_ids)} FAIL + {len(draw.pass_ids)} PASS " f"(stratum={stratum}, shortfall={draw.shortfall or 'none'})") - context = {"policy": POLICY_VERSION, "model": model_identity} - observations: dict[str, Any] = {} - steps: list[dict[str, Any]] = [] - for step_no, step in enumerate(plan): - extra = extras.get(step.analyzer, {}) - action = ProbeAction( - analyzer=step.analyzer, config={**step.config, **extra}, case_ids=draw.case_ids, - route=step.route, purpose=step.purpose, - reserve={k: v * len(draw.case_ids) for k, v in step.calls_per_case.items()}, - ) - if step.task_kinds and task_kind not in step.task_kinds: - base = {"step": step_no, "key": step.name, "analyzer": step.analyzer} - reason = f"step is for task kinds {list(step.task_kinds)}; this task is {task_kind!r}" - ledger.trace({**base, "event": "not_applicable", "reason": reason}) - steps.append({**base, "status": "not_applicable", "reused": False, "reason": reason}) - say(f"[triage] {step_no} {step.name}: not applicable ({task_kind})") - continue - try: - analyzer = _build(step, extra) - except Exception as exc: # noqa: BLE001 - a bad config is an outcome, not a crash - base = {"step": step_no, "key": step.name, "action_id": action.identity(context), - "analyzer": step.analyzer} - ledger.trace({**base, "event": "skipped", "status": "failed", - "reason": f"could not construct: {type(exc).__name__}: {exc}"}) - steps.append({**base, "status": "failed", "error": str(exc)}) - continue - version = tool_version(analyzer) - action_id = action.identity({**context, "tool_version": version, - "per_case": step.per_case, "keep_artifacts": list(step.keep_artifacts)}) - base = {"step": step_no, "key": step.name, "action_id": action_id, "analyzer": step.analyzer} - - done = ledger.settled(action_id) - if done is not None: - ledger.trace({**base, "event": "reused", "status": done.status, "attempt": done.attempt, - "note": "terminal observation with the same identity; read back, not re-run"}) - observations[step.name] = done - steps.append({**base, "status": done.status, "reused": True, "fidelity": done.fidelity, - "cost": done.cost, "error": done.error}) - say(f"[triage] {step_no} {step.name}: reused ({done.status})") - continue - - if budget_sec > 0 and ledger.spent_wall_sec() >= budget_sec: - ledger.trace({**base, "event": "skipped", "status": SKIPPED, - "reason": f"wall-clock budget {budget_sec}s spent"}) - steps.append({**base, "status": SKIPPED, "reason": "budget"}) - say(f"[triage] {step_no} {step.name}: skipped (budget)") + # A step whose rows depend on the batch would have to re-run on every larger + # sample. When the routes do not read it, nothing the expansion rule looks at + # depends on it either, so it runs once, on the sample the expansions settle on. + deferred = [s for s in battery if not s.reuse and s.name not in ROUTE_STEPS] + immediate = [s for s in battery if s not in deferred] + revision = 0 + for step in immediate: + run.run_step(step, list(draw.case_ids), kind="battery", revision=revision) + + def settle() -> None: + for step in deferred: + run.run_step(step, list(draw.case_ids), kind="battery", revision=revision) + + decisions: list[dict[str, Any]] = [] + revisions: list[dict[str, Any]] = [] + followed: list[tuple[str, str, str]] = [] # (route, rule_id, step key), in execution order + stop: "dict[str, Any] | None" = None + expansion_note: "dict[str, Any] | None" = None + round_no = 0 + + def decide(record: dict[str, Any]) -> None: + record = {"event": "decision", "n": len(decisions), "round": round_no, "revision": revision, + "rules_version": RULES_VERSION, **record} + ledger.trace(record) + decisions.append(record) + + def n_actions() -> int: # decisions that spend: expansions and follow-ups + return sum(1 for d in decisions if d["kind"] in ("expand", "follow_up")) + + while stop is None: + records = triage(sample, run.evidence) + summary = summarize(records) + gaps = expansion_gaps(summary, records, min_cohort=min_cohort) + if not revisions or revisions[-1]["revision"] != revision: + revisions.append(_revision_row(revision, draw, summary, records, gaps)) + size = next_size(len(draw.fail_ids), max_fail, n_available) + if gaps and size is not None and expansion_note is None: + if n_actions() >= max_actions: + stop = {"reason": "max_actions", "max_actions": max_actions, "pending": "expansion"} + break + bigger, bigger_draw = matched_sample(explore, size, seed=seed, stratum=stratum) + if not (set(draw.fail_ids) <= set(bigger_draw.fail_ids) and set(draw.pass_ids) <= set(bigger_draw.pass_ids)): + raise RuntimeError("nested sampler returned a draw that does not contain the previous one") + new_ids = [cid for cid in bigger_draw.case_ids if cid not in set(draw.case_ids)] + estimates = [run.estimate_sec(s, len(new_ids) if s.reuse else len(bigger_draw.case_ids)) + for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] + estimate = round(sum(e for e in estimates if e is not None), 1) if any( + e is not None for e in estimates) else None + why = run.over_budget(estimate) + if why is not None: + expansion_note = {"state": "skipped", "reason": why, "gaps": gaps} + decide({"kind": "expand_skipped", "rule_id": "E1", "reason": why, "gaps": gaps, + "estimate_sec": estimate}) + continue + decide({"kind": "expand", "rule_id": "E1", "from_fail": len(draw.fail_ids), "to_fail": len(bigger_draw.fail_ids), + "n_new_cases": len(new_ids), "gaps": gaps, "estimate_sec": estimate, + "rationale": "an evidence gap a larger nested sample can close; expansion precedes the " + "routes' candidates because it revises the routes"}) + say(f"[triage] expand {len(draw.fail_ids)} -> {len(bigger_draw.fail_ids)} FAIL " + f"({len(new_ids)} new cases; gaps: {[g['gap'] for g in gaps]})") + sample, draw = bigger, bigger_draw + draws.append(draw) + revision += 1 + manifest() + ledger.trace({"event": "revision", "revision": revision, "n_fail": len(draw.fail_ids), + "n_pass": len(draw.pass_ids), "n_new_cases": len(new_ids)}) + for step in immediate: + run.run_step(step, list(draw.case_ids), kind="expansion", revision=revision, rule_id="E1", + budget_checked=True) continue - - prior = ledger.attempts(action_id) - attempt = prior + 1 - ledger.trace({ - **base, "event": "planned", "attempt": attempt, "action": action.to_dict(), - "params": canonical(analyzer.get_params()), "tool_version": version, - "fidelity_check": step.fidelity_check, - "rationale": "MVP-0 fixed order", "candidates": [s.name for s in plan], - **({"previous_attempts_uncertain": prior} if prior else {}), - }) - say(f"[triage] {step_no} {step.name}: running on {len(sample)} cases") - obs = execute(action, action_id, attempt, analyzer, model, sample, - fidelity_check=step.fidelity_check, per_case=step.per_case, - keep_artifacts=step.keep_artifacts, run_logger=run_logger) - if obs.cost.get("api_usage") is not None: - obs.cost["usd"] = price_fn(obs.cost["api_usage"]) if price_fn is not None else None - ledger.save(obs) - ledger.cost({"kind": "action", "action_id": action_id, "analyzer": step.analyzer, - "attempt": attempt, "reserved_calls": action.reserve, - "baseline_reused": obs.status == OK and not obs.cost.get("calls"), - "judge_calls": 0, **obs.cost}) - ledger.trace({**base, "event": "settled", "attempt": attempt, "status": obs.status, - "fidelity": obs.fidelity.get("status"), "n_measured": len(obs.measured_ids), - "n_missing": len(obs.missing), "error_type": obs.error_type, "error": obs.error}) - observations[step.name] = obs - steps.append({**base, "status": obs.status, "reused": False, "fidelity": obs.fidelity, - "cost": obs.cost, "error": obs.error, "n_measured": len(obs.measured_ids), - "missing": obs.missing}) - say(f"[triage] {step_no} {step.name}: {obs.status} " - f"(fidelity={obs.fidelity.get('status')}, {obs.cost.get('wall_sec')}s, calls={obs.cost.get('calls')})") - - records = triage_cases(sample, observations, host_assumed_finish=host_assumed_finish, - answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, - answer_fn=answer_fn) + if gaps and expansion_note is None: + expansion_note = {"state": "not_possible", "gaps": gaps, + "reason": (f"the sample has the cap of {max_fail} FAIL cases" if len(draw.fail_ids) >= max_fail + else f"EXPLORE has no FAIL case beyond the {n_available} drawn")} + decide({"kind": "expand_not_possible", "rule_id": "E1", **expansion_note}) + + settle() # the sample is final: the deferred battery steps run once, before any follow-up + records = triage(sample, run.evidence) + ran = 0 + for row in active_routes(records, min_route_fail): + if not row["active"]: + continue + route = row["route"] + proposal = next_for_route(route, records, run.evidence, run.gate, rank_of, layers=layers, + blocked=run.blocked) + if proposal is None: + continue + if n_actions() >= max_actions: + stop = {"reason": "max_actions", "max_actions": max_actions, + "pending": f"{route}:{proposal.layer.rule_id}:{proposal.step.name}"} + break + # chunks of the same step measured before (an earlier invocation, a smaller sample) + # are read back first, so the decision states what it actually runs + adopted = run.adopt_for(proposal.step, proposal.target_ids, kind="follow_up", revision=revision, + rule_id=proposal.layer.rule_id, route=route) + todo = run.evidence[proposal.step.name].todo(proposal.target_ids) + decide({"kind": "follow_up", "rule_id": proposal.layer.rule_id, "route": route, + "proposal": proposal.kind, "key": proposal.step.name, "analyzer": proposal.step.analyzer, + "question": proposal.layer.question, "n_route_fail": len(proposal.fail_ids), + "n_controls": len(proposal.control_ids), "n_new_cases": len(todo), + "n_read_back": len(proposal.todo) - len(todo), + "passed_over": proposal.tried, "earlier_layers": proposal.before, + "rationale": (f"route {route} active with {row['n_fail']} FAIL cases; " + + ("extend the layer's step to the route's new cases" if proposal.kind == "extend" + else "first open layer in the soft order"))}) + record = run.run_step(proposal.step, proposal.target_ids, kind="follow_up", revision=revision, + rule_id=proposal.layer.rule_id, route=route) + if record is None and not adopted: # defensive: an open layer always has cases to run + run.blocked.setdefault(proposal.step.name, "nothing left to run") + elif record is not None and record["status"] == SKIPPED: + stop = {"reason": "budget", "detail": record.get("reason")} + break + if (route, proposal.layer.rule_id, proposal.step.name) not in followed: + followed.append((route, proposal.layer.rule_id, proposal.step.name)) + ran += 1 + round_no += 1 + if stop is None and not ran: + stop = {"reason": "no_candidate", "detail": "every active route's layers are done or exhausted"} + + settle() # a stop before the sample settled (max_actions with an expansion pending) + records = triage(sample, run.evidence) + summary = summarize(records) + ledger.trace({"event": "stop", "round": round_no, "revision": revision, **stop}) + say(f"[triage] stop: {stop['reason']} after {n_actions()} actions") + final_gaps = expansion_gaps(summary, records, min_cohort=min_cohort) + n_expansions = sum(1 for d in decisions if d["kind"] == "expand") report = { "policy": POLICY_VERSION, + "rules_version": RULES_VERSION, "model": model_identity, "sample": draw.to_dict(), "settings": {"host_assumed_finish": host_assumed_finish, "answer_contract": answer_contract, "n_needs_counterfactual": n_needs_counterfactual, "budget_sec": budget_sec, - "task_kind": task_kind, "answer_fn": canonical(answer_fn)}, - "steps": steps, - "cost": _cost_summary(steps, stage0_cost), - "summary": summarize(records), - "next_candidates": propose( - records, model, sample, task_kind=task_kind, extras=extras, - executed={(s.analyzer, str(canonical({**s.config, **extras.get(s.analyzer, {})}))) - for s in plan if s.name in observations}), - "checks": _acceptance(plan, steps, observations, draw, ledger), + "task_kind": task_kind, "answer_fn": canonical(answer_fn), "n_fail": n_fail, + "max_fail": max_fail, "max_actions": max_actions, "min_route_fail": min_route_fail, + "min_cohort": min_cohort}, + "executions": run.executions, + "battery": _battery_state(battery, run, draw), + "revisions": revisions, + "expansion": {"n_expansions": n_expansions, "final_gaps": final_gaps, + **(expansion_note or {"state": ("closed" if n_expansions else "no_gap") if not final_gaps + else "pending"})}, + "decisions": decisions, + "stop": stop, + "cost": _cost_summary(run.executions, stage0_cost), + "summary": summary, + "follow_ups": _follow_ups(followed, records, run, sample, rank_of, layers, answer_fn), + "routes": _route_report(records, run, rank_of, layers, min_route_fail), + "checks": _acceptance(battery, layers, run, draw, ledger), "cases": records, } _write_json(out / "triage_report.json", report) @@ -334,7 +631,80 @@ def run_triage_mvp0( return report -def _cost_summary(steps: list[dict[str, Any]], stage0_cost: "dict[str, Any] | None") -> dict[str, Any]: +#: The MVP-0 entry point, now the same controller (no expansion unless ``max_fail`` is given). +run_triage_mvp0 = run_triage + + +def _revision_row(revision: int, draw: Any, summary: dict[str, Any], records: list[dict[str, Any]], + gaps: list[dict[str, Any]]) -> dict[str, Any]: + routes = Counter(tag for r in records if r["label"] == "fail" for tag in r["routes"]) + return { + "revision": revision, "n_fail": len(draw.fail_ids), "n_pass": len(draw.pass_ids), + "signals": {tag: {"fail": f"{summary[tag]['fail']['n_fired']}/{summary[tag]['fail']['n_tested']}", + "pass": f"{summary[tag]['pass']['n_fired']}/{summary[tag]['pass']['n_tested']}", + "routing_signal": summary[tag]["routing_signal"], "ci95": summary[tag]["signal_ci95"]} + for tag in ("H_label_free", "N", "U")}, + "fail_routes": dict(sorted(routes.items())), + "gaps": gaps, + } + + +def _battery_state(battery: "tuple[PlanStep, ...]", run: _Run, draw: Any) -> list[dict[str, Any]]: + """Per battery step: which observations the current sample is read from.""" + out = [] + for step in battery: + ev = run.evidence.get(step.name) + if ev is None or not ev.chunks: + status = next((e["status"] for e in run.executions if e["key"] == step.name), "not run") + out.append({"key": step.name, "analyzer": step.analyzer, "reuse": step.reuse, "status": status}) + continue + used = Counter(o.action_id for cid in draw.case_ids if (o := ev.for_case(cid)) is not None) + out.append({"key": step.name, "analyzer": step.analyzer, "reuse": step.reuse, + **({"reuse_note": step.reuse_note} if step.reuse_note else {}), + "statuses": ev.statuses_on(draw.case_ids), "read_from": dict(used), + "n_chunks": len(ev.chunks), + "covers_sample": all(ev.for_case(cid) is not None for cid in draw.case_ids)}) + return out + + +def _follow_ups(followed: list[tuple[str, str, str]], records: list[dict[str, Any]], run: _Run, sample: Any, + rank_of: Callable[[str], Any], layers: "tuple[Layer, ...]", + answer_fn: Any) -> list[dict[str, Any]]: + """Descriptive readings of every follow-up that ran, on the route's current cases.""" + from evalrx.eval_agent.probing.rules import matched_controls + + by_rule = {x.rule_id: x for x in layers} + out = [] + for route, rule_id, key in followed: + layer, ev = by_rule[rule_id], run.evidence[key] + fail_ids = route_fail_ids(records, route, layer.case_filter) + controls, shortfall = matched_controls(records, fail_ids, rank_of) + chunks = [o for o in ev.chunks if set(o.planned_ids) & set(fail_ids)] + out.append({ + "route": route, "rule_id": rule_id, "key": key, "analyzer": ev.step.analyzer, + "config": canonical(ev.step.config), "question": layer.question, + "statuses": ev.statuses_on([*fail_ids, *controls]), + "fidelity": sorted({str((o.fidelity or {}).get("status")) for o in chunks}), + "n_route_fail": len(fail_ids), "n_controls": len(controls), "control_shortfall": shortfall, + "not_run_on": len(ev.todo([*fail_ids, *controls])) if ev.step.reuse else None, + **({"caveat": ev.step.caveat} if ev.step.caveat else {}), + "reading": follow_up_reading(ev, sample, fail_ids, controls, answer_fn), + }) + return out + + +def _route_report(records: list[dict[str, Any]], run: _Run, rank_of: Callable[[str], Any], + layers: "tuple[Layer, ...]", min_route_fail: int) -> list[dict[str, Any]]: + """Every route with FAIL cases: active or not, and each layer's state when the run stopped.""" + out = [] + for row in active_routes(records, min_route_fail): + states = route_states(row["route"], records, run.evidence, run.gate, rank_of, layers=layers, + blocked=run.blocked) + out.append({**row, "layers": [public(s) for s in states]}) + return out + + +def _cost_summary(executions: list[dict[str, Any]], stage0_cost: "dict[str, Any] | None") -> dict[str, Any]: """This invocation's spend: Stage 0, the actions it executed, and (apart) what it read back. Token and USD totals only cover actions whose provider reported usage; a @@ -355,39 +725,51 @@ def total(rows: list[dict[str, Any]]) -> dict[str, Any]: out["usd"] = round(sum(usd), 6) if all(v is not None for v in usd) else None return out - ran = [s for s in steps if s.get("status") not in ("not_applicable", SKIPPED) and not s.get("reused")] - reused = [s for s in steps if s.get("reused")] - return {"stage0": stage0_cost or {}, "actions_run": total(ran), + ran = [e for e in executions if e.get("cost") is not None and not e.get("reused")] + reused = [e for e in executions if e.get("reused")] + by_kind = {kind: total([e for e in ran if e["kind"] == kind]) for kind in ("battery", "expansion", "follow_up")} + return {"stage0": stage0_cost or {}, "actions_run": total(ran), "actions_run_by_kind": by_kind, "actions_read_back": {**total(reused), "_note": "spent by the run that executed them"}} -def _acceptance(plan: "tuple[PlanStep, ...]", steps: list[dict[str, Any]], observations: dict[str, Any], - draw: Any, ledger: Ledger) -> dict[str, Any]: - """The MVP-0 acceptance properties that can be checked from the run's own records.""" - planned = {s.analyzer for s in plan} +def _acceptance(battery: "tuple[PlanStep, ...]", layers: "tuple[Layer, ...]", run: _Run, draw: Any, + ledger: Ledger) -> dict[str, Any]: + """The acceptance properties that can be checked from the run's own records.""" + allowed = {s.analyzer for s in battery} | {s.analyzer for s in candidate_steps(layers)} traced = {e.get("analyzer") for e in ledger.trace_events() if e.get("event") in ("planned", "settled")} - case_sets = {name: obs.planned_ids == list(draw.case_ids) and set(obs.measured_ids) <= set(draw.case_ids) - for name, obs in observations.items()} - configs = {} - for s in plan: - obs = observations.get(s.name) - if obs is not None: - configs[s.name] = all(obs.params.get(k) == canonical(v) for k, v in s.config.items()) + disjoint, one_batch, configs = {}, {}, {} + for key, ev in run.evidence.items(): + if not ev.chunks: + continue + counts = Counter(cid for o in ev.chunks for cid in o.planned_ids) + if ev.step.reuse: + disjoint[key] = all(n == 1 for n in counts.values()) + else: + read = {o.action_id for cid in draw.case_ids if (o := ev.for_case(cid)) is not None} + if key in {s.name for s in battery}: + one_batch[key] = len(read) == 1 and set(ev.chunks[-1].planned_ids) == set(draw.case_ids) + configs[key] = all(o.params.get(k) == canonical(v) for o in ev.chunks for k, v in ev.step.config.items()) costs = ledger.cost_events() + observations = [o for ev in run.evidence.values() for o in ev.chunks] return { - "only_planned_actions": traced <= planned and len(steps) == len(plan), - "case_sets_match_plan": case_sets, + "only_rule_actions": traced <= allowed, + "battery_covers_sample": {b["key"]: b.get("covers_sample") for b in _battery_state(battery, run, draw) + if "covers_sample" in b}, + "reused_chunks_disjoint": disjoint, + "batch_dependent_read_from_current_sample": one_batch, "configs_match_plan": configs, "stage0_cost_separate": any(e.get("kind") == "stage0" for e in costs), - "no_zero_for_failure": all(obs.findings is None for obs in observations.values() if obs.status != OK), - "fidelity_states": {name: (obs.fidelity or {}).get("status") for name, obs in observations.items()}, + "no_zero_for_failure": all(o.findings is None for o in observations if o.status != OK), + "fidelity_states": {key: sorted({str((o.fidelity or {}).get("status")) for o in ev.chunks}) + for key, ev in run.evidence.items() if ev.chunks}, } def _why_not(report: dict[str, Any], key: str) -> str: - step = next((st for st in report["steps"] if (st.get("key") or st["analyzer"]) == key), None) - if step is None: + rows = [e for e in report["executions"] if e["key"] == key] + if not rows: return "not in the plan" + step = rows[-1] reason = step.get("error") or step.get("reason") or "" return f"{step['status']}" + (f" ({reason})" if reason else "") @@ -395,38 +777,64 @@ def _why_not(report: dict[str, Any], key: str) -> str: def _markdown(report: dict[str, Any]) -> str: s = report["summary"] lines = [ - f"# Triage report ({report['policy']})", "", + f"# Triage report ({report['policy']}, {report['rules_version']})", "", f"Model: `{report['model'].get('spec')}` on `{report['model'].get('backend')}`. " f"Sample: {len(report['sample']['fail_ids'])} FAIL + {len(report['sample']['pass_ids'])} PASS, " - f"stratum `{report['sample']['stratum_rule']}`, shortfall {report['sample']['shortfall'] or 'none'}.", - "", "## Actions", "", - "| step | analyzer | status | fidelity | wall s | calls |", "|---|---|---|---|---:|---|", + f"stratum `{report['sample']['stratum_rule']}`, shortfall {report['sample']['shortfall'] or 'none'}. " + f"Stopped: {report['stop']['reason']}" + + (f" ({report['stop'].get('detail') or report['stop'].get('pending')})" + if report["stop"].get("detail") or report["stop"].get("pending") else "") + ".", + "", "## Sample revisions", "", + "| revision | FAIL | PASS | H (label-free) | N | U | FAIL routes | gaps |", "|---:|---:|---:|---|---|---|---|---|", ] - for st in report["steps"]: - cost = st.get("cost") or {} - name = st.get("key") or st["analyzer"] - if name != st["analyzer"]: - name = f"{st['analyzer']} ({name})" - lines.append(f"| {st['step']} | {name} | {st['status']}{' (reused)' if st.get('reused') else ''} " - f"| {(st.get('fidelity') or {}).get('status', '-')} | {cost.get('wall_sec', '-')} " + for rev in report["revisions"]: + sig = rev["signals"] + cells = [f"{sig[t]['fail']} vs {sig[t]['pass']}, CI {sig[t]['ci95']}" for t in ("H_label_free", "N", "U")] + gaps = "; ".join(f"{g['gap']} {g.get('route') or g.get('stratum')}" for g in rev["gaps"]) or "none" + lines.append(f"| {rev['revision']} | {rev['n_fail']} | {rev['n_pass']} | {' | '.join(cells)} " + f"| {rev['fail_routes']} | {gaps} |") + exp = report.get("expansion") or {} + if exp.get("state") in ("skipped", "not_possible"): + lines += ["", f"Expansion {exp['state']}: {exp['reason']}."] + lines += ["", "## Decisions", "", "| # | round | kind | rule | route | step | new cases | rationale / passed over |", + "|---:|---:|---|---|---|---|---:|---|"] + for d in report["decisions"]: + passed = "; ".join(f"{t['key']}: {t['status']}" + (f" ({t['reason']})" if t.get("reason") else "") + for t in d.get("passed_over") or []) + text = d.get("rationale") or d.get("reason") or "" + if passed: + text = f"{text}. Passed over: {passed}" + lines.append(f"| {d['n']} | {d['round']} | {d['kind']} | {d['rule_id']} | {d.get('route', '-')} " + f"| {d.get('key', '-')} | {d.get('n_new_cases', '-')} | {text} |") + lines += ["", "## Actions", "", + "| # | kind | rev | step | cases | status | fidelity | wall s | calls |", "|---:|---|---:|---|---:|---|---|---:|---|"] + for e in report["executions"]: + cost = e.get("cost") or {} + name = e["key"] if e["key"] == e["analyzer"] else f"{e['analyzer']} ({e['key']})" + lines.append(f"| {e['n']} | {e['kind']} | {e['revision']} | {name} | {e.get('n_cases', '-')} " + f"| {e['status']}{' (reused)' if e.get('reused') else ''} " + f"| {(e.get('fidelity') or {}).get('status', '-')} | {cost.get('wall_sec', '-')} " f"| {cost.get('calls', '-')} |") cost = report.get("cost") or {} run, stage0 = cost.get("actions_run") or {}, cost.get("stage0") or {} + by_kind = ", ".join(f"{k} {v['wall_sec']} s" for k, v in (cost.get("actions_run_by_kind") or {}).items() + if v["n_actions"]) lines += ["", f"Cost of this invocation: Stage 0 {stage0.get('wall_sec', '-')} s, {stage0.get('calls', '-')}" + (f", {stage0['api_usage']}, USD {stage0.get('usd')}" if stage0.get("api_usage") else "") - + f"; actions run {run.get('wall_sec', 0)} s, {run.get('calls', {})}" + + f"; actions run {run.get('wall_sec', 0)} s ({by_kind or 'none'}), {run.get('calls', {})}" + (f", {run['api_usage']}, USD {run.get('usd')}" if run.get("api_usage") else "") + "."] - lines += ["", "## Routes on this sample", "", - "| route | FAIL fired/tested | PASS fired/tested | routing signal |", "|---|---|---|---:|"] + lines += ["", "## Routes on the final sample", "", + "| route | FAIL fired/tested | PASS fired/tested | routing signal | 95% CI of the difference |", + "|---|---|---|---:|---|"] for tag in ("H_label_free", "N", "U"): f, p = s[tag]["fail"], s[tag]["pass"] lines.append(f"| {tag} | {f['n_fired']}/{f['n_tested']} | {p['n_fired']}/{p['n_tested']} " - f"| {s[tag]['routing_signal']} |") + f"| {s[tag]['routing_signal']} | {s[tag]['signal_ci95']} |") for part, rates in s["U_parts"].items(): f, p = rates["fail"], rates["pass"] - lines.append(f"| U: {part} | {f['n_fired']}/{f['n_tested']} | {p['n_fired']}/{p['n_tested']} | - |") - lines += [f"| S (stable FAIL) / stable PASS | {s['S']['fail']} | {s['S']['stable_pass']} | - |", - f"| X (a required check missing) | {s['X']['fail']} | {s['X']['pass']} | - |", "", + lines.append(f"| U: {part} | {f['n_fired']}/{f['n_tested']} | {p['n_fired']}/{p['n_tested']} | - | - |") + lines += [f"| S (stable FAIL) / stable PASS | {s['S']['fail']} | {s['S']['stable_pass']} | - | - |", + f"| X (a required check missing) | {s['X']['fail']} | {s['X']['pass']} | - | - |", "", "The routing signal is max(0, P(tag|FAIL) - P(tag|PASS)) on this matched sample: it steers " "later actions and is not an explained share of failures. S = a FAIL case on which H, N " "(with media) and both U parts ran and none fired; a missing check leaves it in X."] @@ -489,19 +897,37 @@ def _markdown(report: dict[str, Any]) -> str: f"{ps['mean_final_prob']} | {ps['mean_late_drop']} " f"| {ps['n_media_query_hit']}/{ps['n_media_query_read']} |") lines += ["", f"_{readings['_note']}._"] - proposals = report.get("next_candidates") or {} - if proposals.get("candidates"): - lines += ["", "## Next candidates (proposed by rule, not run)", "", - "| route | FAIL cases | analyzer | config | status | question / reason |", "|---|---:|---|---|---|---|"] - for c in proposals["candidates"]: - text = c.get("question") or "" - if c.get("reason"): - text = f"{text} ({c['reason']})" if text else c["reason"] - lines.append(f"| {c['route']} | {c['n_fail_cases']} | {c['analyzer']} | {c.get('config', '')} " - f"| {c['status']} | {text} |") - if proposals.get("x_untested"): - lines += ["", f"Why X cases stay untested: {proposals['x_untested']}."] - lines += ["", f"_{proposals['_note']}._"] + if report["follow_ups"]: + lines += ["", "## Follow-ups (descriptive)", ""] + for fu in report["follow_ups"]: + reading = fu["reading"] + fail, ctrl = reading["route_fail"], reading["controls"] + lines += [f"### {fu['route']} / {fu['rule_id']}: `{fu['analyzer']}` ({fu['key']})", "", + f"{fu['question']}. Status {fu['statuses']}, fidelity {fu['fidelity']}; " + f"measured {fail['n_measured']}/{fail['n']} route FAIL, {ctrl['n_measured']}/{ctrl['n']} " + f"PASS controls" + (f"; control shortfall {fu['control_shortfall']}" if fu["control_shortfall"] else "") + + (f"; not run on {fu['not_run_on']} current cases" if fu.get("not_run_on") else "") + "."] + if fu.get("caveat"): + lines += ["", f"Caveat: {fu['caveat']}."] + fields = sorted(set(fail["means"]) | set(ctrl["means"])) + if fields: + lines += ["", "| reading | route FAIL mean (n) | PASS control mean (n) |", "|---|---:|---:|"] + lines += [f"| {f} | {fail['means'].get(f)} ({fail['n_by_field'].get(f, 0)}) " + f"| {ctrl['means'].get(f)} ({ctrl['n_by_field'].get(f, 0)}) |" for f in fields] + untested = {**fail["untested"], **{f"(controls) {k}": v for k, v in ctrl["untested"].items()}} + if untested: + lines += ["", f"Untested: {untested}."] + lines.append("") + lines.append("_Means over the route's FAIL cases and their stratum-matched PASS controls; descriptive, " + "no test, no mechanism named._") + if report["routes"]: + lines += ["", "## Route layers when the run stopped", "", + "| route | FAIL | active | layer | state | via / next | passed over |", "|---|---:|---|---|---|---|---|"] + for row in report["routes"]: + for st in row["layers"]: + passed = "; ".join(f"{t['key']}: {t['status']}" for t in st.get("tried") or []) + lines.append(f"| {row['route']} | {row['n_fail']} | {row['active']} | {st['rule_id']} | {st['state']} " + f"| {st.get('via') or st.get('key') or '-'} | {passed or '-'} |") lines += ["", "## Checks", ""] for name, value in report["checks"].items(): lines.append(f"- `{name}`: {value}") diff --git a/evalrx/eval_agent/probing/evidence.py b/evalrx/eval_agent/probing/evidence.py new file mode 100644 index 00000000..803e8d2a --- /dev/null +++ b/evalrx/eval_agent/probing/evidence.py @@ -0,0 +1,89 @@ +"""One step's evidence on a growing sample, assembled from chunk observations. + +A step that ran on the 8-FAIL sample and then on the cases the 16-FAIL sample +added holds two observations over disjoint case sets; which one measured a +case is a lookup, so the triage reads each case from the observation that +measured it and nothing is merged or recomputed by hand. + +* ``reuse`` steps (a case's row does not depend on the rest of the batch) + run only the cases not yet covered; the old rows stay current. +* other steps re-run on the whole current sample, and the latest run that + covers a case is the one read: an earlier batch's rows were computed + against a different batch and are kept on disk, not read. +* a step with an edit self-check that refused on any chunk is refused on + every case: keeping the chunks that happened to pass would select on + numerical noise, as the per-case gate inside one batch already rules out. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Iterable + +from evalrx.eval_agent.probing.actions import OK, UNFAITHFUL, Observation, PlanStep + + +@dataclass +class StepEvidence: + step: PlanStep + chunks: list[Observation] = field(default_factory=list) + + def add(self, obs: Observation) -> None: + self.chunks.append(obs) + + def refused(self) -> "Observation | None": + if self.step.fidelity_check is None: + return None + return next((c for c in self.chunks if c.status == UNFAITHFUL), None) + + def for_case(self, cid: str) -> "Observation | None": + """The observation that measured *cid* (``None`` = never planned on it).""" + bad = self.refused() + if bad is not None: + return bad + for obs in reversed(self.chunks): + if cid in obs.planned_ids: + return obs + return None + + def covered(self) -> set[str]: + return {cid for obs in self.chunks for cid in obs.planned_ids} + + def todo(self, target: Iterable[str]) -> list[str]: + """The cases of *target* this step still has to run on (target order). + + ``reuse``: the ones no chunk planned. Otherwise: all of them, unless the + latest chunk ran on exactly this case set. + """ + target = list(target) + if self.step.reuse: + done = self.covered() + return [cid for cid in target if cid not in done] + if self.chunks and set(self.chunks[-1].planned_ids) == set(target): + return [] + return target + + def valid_on(self, ids: Iterable[str]) -> bool: + """Some case of *ids* has an ``ok`` measurement the step's self-check did not refuse.""" + if self.refused() is not None: + return False + return any((obs := self.for_case(cid)) is not None and obs.status == OK for cid in ids) + + def statuses_on(self, ids: Iterable[str]) -> list[str]: + return sorted({obs.status for cid in ids if (obs := self.for_case(cid)) is not None}) + + def sec_per_case(self) -> "float | None": + """Wall seconds per planned case over the chunks that executed, for budget estimates.""" + rows = [(float(o.cost.get("wall_sec") or 0.0), len(o.planned_ids)) for o in self.chunks + if o.cost.get("calls") and o.planned_ids] + n = sum(k for _, k in rows) + return sum(s for s, _ in rows) / n if n else None + + +def pick(evidence: "dict[str, Any]", key: str, cid: str) -> "Observation | None": + """The observation for *cid* under *key*: a plain :class:`Observation` (one batch) or a + :class:`StepEvidence` (chunks).""" + value = evidence.get(key) + if isinstance(value, StepEvidence): + return value.for_case(cid) + return value diff --git a/evalrx/eval_agent/probing/ledger.py b/evalrx/eval_agent/probing/ledger.py index e8c2a81a..0aea7b87 100644 --- a/evalrx/eval_agent/probing/ledger.py +++ b/evalrx/eval_agent/probing/ledger.py @@ -2,15 +2,20 @@ Layout under the run's ``probing/`` directory:: - selection_trace.jsonl one line per decision event (planned / settled / reused / skipped) + selection_trace.jsonl one line per event (planned / settled / reused / skipped / decision ...) cost_ledger.jsonl one line per settled cost (the shared Stage-0 baseline first) observations/.json the full outcome of each terminal action attempt + observations/index.jsonl action id -> step identity (the action without its cases) and cases Resume rule: an action whose identity already has a terminal observation is read back, not re-run, and earns no new cost. An attempt that was planned but never settled (the process died mid-action) is recorded as uncertain; the next attempt gets a new number and its own cost line, so nothing is silently counted twice or not at all. + +The index lets a step whose per-case rows do not depend on the batch pick up +the chunks an earlier run measured on other case sets (a smaller sample), so +a larger sample only runs the cases no chunk covers. """ from __future__ import annotations @@ -66,14 +71,22 @@ def cost_events(self) -> list[dict[str, Any]]: return self._read(self.cost_path) # -- observations ---------------------------------------------------------- - def save(self, obs: Observation) -> Path: + def save(self, obs: Observation, step_id: "str | None" = None) -> Path: path = self.obs_dir / f"{obs.action_id}.json" tmp = path.with_suffix(".json.tmp") tmp.write_text(json.dumps(obs.to_dict(), ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") os.replace(tmp, path) + if step_id is not None: # after the file: an indexed chunk always exists + self._append(self.obs_dir / "index.jsonl", {"action_id": obs.action_id, "step_id": step_id, + "planned_ids": obs.planned_ids, "status": obs.status}) return path + def chunks_for(self, step_id: str) -> list[Observation]: + """Terminal observations of this step identity, in the order they were saved.""" + ids = [r["action_id"] for r in self._read(self.obs_dir / "index.jsonl") if r.get("step_id") == step_id] + return [obs for aid in dict.fromkeys(ids) if (obs := self.settled(aid)) is not None] + def settled(self, action_id: str) -> "Observation | None": path = self.obs_dir / f"{action_id}.json" if not path.is_file(): diff --git a/evalrx/eval_agent/probing/proposals.py b/evalrx/eval_agent/probing/proposals.py deleted file mode 100644 index bcc23d15..00000000 --- a/evalrx/eval_agent/probing/proposals.py +++ /dev/null @@ -1,115 +0,0 @@ -"""Next experiments the fixed plan did not run: proposed by rule, checked, never run. - -A run without internal state must still be able to name its next behavioural -experiment. Every route with FAIL cases on this sample gets the follow-ups of -the method table, behavioural ones first; each is built with the host's -extras and gated on the actual model and sample, so the report says which -can run here and why the others cannot. Nothing is executed or scored: -choosing among them is the adaptive controller's job (MVP-3), and only -configurations the tools already support are proposed. -""" - -from __future__ import annotations - -from collections import Counter -from dataclasses import dataclass -from typing import Any - -from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES -from evalrx.eval_agent.probing.actions import canonical -from evalrx.eval_agent.probing.executor import gate - -DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} - - -@dataclass(frozen=True) -class FollowUp: - """One candidate: the route it serves, the tool and configuration, the question it asks.""" - - route: str - analyzer: str - config: dict[str, Any] - question: str - task_kinds: tuple[str, ...] = () - caveat: str = "" - - -FOLLOW_UPS: tuple[FollowUp, ...] = ( - FollowUp("H", "answer_extraction_audit", {"reask": True}, - "does a re-ask with a stricter answer request recover the answer the output lost"), - FollowUp("H", "termination_audit", {"continue_non_clean": True}, - "continued past where it stopped, does the output reach an answer"), - FollowUp("N", "prompt_contrast", {"strategies": DESCRIBE_STRATEGIES}, - "asked to describe the media first, does the answer start to follow it", - caveat="the runtime's output cap must leave room for the description"), - FollowUp("N", "causal_trace", {"target": "gold"}, - "which layers and positions carry the media's effect on the gold margin"), - FollowUp("U", "self_consistency", {"n": 10}, - "with twice the samples, how often does the answer move"), - FollowUp("U", "logprob_entropy", {}, - "is the answer that moves a near tie in the answer-token probabilities"), - FollowUp("U", "format_sensitivity", {}, - "with the options rotated, does the answer follow content or position", - task_kinds=("multiple_choice_letter",)), - FollowUp("S", "prompt_contrast", {"strategies": DESCRIBE_STRATEGIES}, - "does a stable error survive when the model first states what it sees", - caveat="the runtime's output cap must leave room for the description"), - FollowUp("S", "gradcam", {"target": "gold"}, - "which image regions the gold margin depends on (no reference regions: " - "concentration only, not 'mislocalised')"), - FollowUp("S", "tuned_lens", {}, - "a fitted per-layer readout of the answer position: at what depth the wrong answer forms"), -) - -#: Not a tool call: extending the nested sample is an action of its own that -#: the controller cannot take yet. -EXPAND = {"analyzer": "(nested sample expansion)", "status": "not_implemented", - "reason": "expansion is not a controller action yet (MVP-2); rerun with a larger --triage-n-fail"} - - -def _route_cases(records: list[dict[str, Any]], route: str) -> list[str]: - return [r["case_id"] for r in records if r["label"] == "fail" and route in r["routes"]] - - -def propose(records: list[dict[str, Any]], model: Any, sample: Any, *, task_kind: "str | None", - extras: "dict[str, dict[str, Any]] | None" = None, - executed: "set[tuple[str, str]] | None" = None) -> dict[str, Any]: - """Follow-ups per route with FAIL cases, each with ``status``: - ``executable`` / ``unsupported`` / ``not_applicable`` / ``already_run`` / ``could_not_build``. - - *executed* holds ``(analyzer, canonical config)`` pairs this run already - executed (the plan's own steps). *extras* are the host's constructor extras - per analyzer, as for the plan. - """ - from evalrx.core.registry import registry - - extras = extras or {} - executed = executed or set() - out: list[dict[str, Any]] = [] - for route in ("H", "N", "U", "S"): - cases = _route_cases(records, route) - if not cases: - continue - for f in (x for x in FOLLOW_UPS if x.route == route): - config = {**f.config, **extras.get(f.analyzer, {})} - row: dict[str, Any] = {"route": route, "n_fail_cases": len(cases), "analyzer": f.analyzer, - "config": canonical(f.config), "question": f.question} - if f.caveat: - row["caveat"] = f.caveat - if f.task_kinds and task_kind not in f.task_kinds: - out.append({**row, "status": "not_applicable", "reason": f"for task kinds {list(f.task_kinds)}"}) - continue - if (f.analyzer, str(canonical(config))) in executed: - out.append({**row, "status": "already_run", "reason": "the plan ran this configuration"}) - continue - try: - analyzer = registry.analyzers.get(f.analyzer)(**config) - except Exception as exc: # noqa: BLE001 - a proposal that cannot be built says so - out.append({**row, "status": "could_not_build", "reason": f"{type(exc).__name__}: {exc}"}) - continue - why = gate(analyzer, model, sample) - out.append({**row, "status": "unsupported" if why else "executable", "reason": why or ""}) - out.append({"route": route, "n_fail_cases": len(cases), **EXPAND}) - untested = Counter(reason.split(":")[0] for r in records if r["routes"] == ["X"] for reason in r["x_reasons"]) - return {"candidates": out, "x_untested": dict(untested), - "_note": "proposed by rule from the routes on this sample, gated on this model; none was run"} diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py new file mode 100644 index 00000000..6d9d2422 --- /dev/null +++ b/evalrx/eval_agent/probing/rules.py @@ -0,0 +1,301 @@ +"""MVP-2 rules: what each route runs next, and when the sample is expanded. + +Fixed rules, no scores (scoring candidates against each other is MVP-3). They +write down the cold-start prior of the design's method table, so a different +choice is a new rule version rather than an unrecorded preference. + +**Layers.** Each route has ordered layers (the soft layer order). A layer is +one question; its candidates are the default representative, then its +fallbacks. A layer is *done* once a candidate, or a battery step that already +serves it, gave a valid observation (``ok`` and not refused by its own +self-check) on the route's FAIL cases. It is *exhausted* once every candidate +is gated off (capability, media, task kind), failed or refused. A failed or +refused candidate moves on to the next fallback of the same layer; a valid +negative moves on to the next layer. No rule keeps trying tools until one fires. + +**Rounds.** A route is active with at least ``min_route_fail`` FAIL cases. +Each round, every active route proposes one candidate. H goes first, because +output problems come before mechanisms. The other routes follow by number of +FAIL cases, with ties in the order H, N, U, S, X. A layer that was done on a +smaller sample is first extended to the route's new cases, before the route +moves on to its next layer. + +**Case sets.** A candidate runs on the route's FAIL cases plus as many PASS +cases of the same stratum, taken in the sampler's rank order. This is the +sample's own matching, and it nests the same way, so a grown route only adds +cases. + +**Expansion.** At the start of a round, the nested sample doubles (up to +``max_fail`` FAIL cases) while a gap holds that more cases can close. Two gaps +count: + +* a route whose FAIL-minus-PASS difference is positive but whose 95% interval + still includes zero; +* a stratum whose S cohort, or its stable PASS controls, is smaller than + ``min_cohort``. On POPE the S readings had the opposite sign at 16 cases. + +Expansion comes before the routes' candidates, because it revises the routes +those candidates are drawn from. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable + +from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES +from evalrx.eval_agent.probing.actions import PlanStep +from evalrx.eval_agent.probing.evidence import StepEvidence + +RULES_VERSION = "mvp2-rules-1" +ROUTE_ORDER = ("H", "N", "U", "S", "X") +DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} + +_NOISE_BY_POSITION = "the corruption noise is seeded by the case's position in the batch" +_FIT_ON_BATCH = "the translators are fit on the batch" + + +def _describe(route: str, question: str) -> PlanStep: + # one key for N3 and Sb: the routes share its observations (and its PASS controls) + return PlanStep("prompt_contrast", {"strategies": DESCRIBE_STRATEGIES}, route, question, + key="describe_first", calls_per_case={"generate": 2}, keep_artifacts=("outputs",), + caveat="the runtime's output cap must leave room for the description", + min_output_tokens=128) + + +@dataclass(frozen=True) +class Layer: + """One question of a route, its candidates in fallback order, and where the prior comes from. + + ``served_by`` names battery steps that already answer it. ``case_filter`` + narrows the route's FAIL cases to the ones the question is about. + """ + + rule_id: str + route: str + question: str + candidates: tuple[PlanStep, ...] + served_by: tuple[str, ...] = () + case_filter: "Callable[[dict[str, Any]], bool] | None" = None + filter_note: str = "" + source: str = "probing_design_mix.md method table (cold-start prior)" + + +LAYERS: tuple[Layer, ...] = ( + Layer("H1", "H", "does a re-ask with a stricter answer request recover the answer the output lost", ( + PlanStep("answer_extraction_audit", {"reask": True}, "H1", "re-ask the cases whose answer was not read", + key="extraction_reask", calls_per_case={"generate": 1}),)), + Layer("H2", "H", "continued past where it stopped, does the output reach an answer", ( + PlanStep("termination_audit", {"continue_non_clean": True}, "H2", "continue the outputs that did not end cleanly", + key="termination_continue", calls_per_case={"generate": 1}),)), + Layer("N1", "N", "does the media path carry a measurable effect on the gold answer", ( + PlanStep("causal_trace", {"target": "gold"}, "N1", "corrupt the media, restore one site at a time", + calls_per_case={"forward": 20}, reuse=False, reuse_note=_NOISE_BY_POSITION),), + served_by=("attention_knockout",)), + Layer("N2", "N", "does reading the media with sharper or flatter attention change the gold margin", ( + PlanStep("attention_temperature", {"target": "gold"}, "N2", "rescale the media attention temperature", + fidelity_check="edit", calls_per_case={"forward": 4}), + PlanStep("attention_sensitivity", {"target": "gold"}, "N2", "scale attention to the media down and up", + fidelity_check="edit", calls_per_case={"forward": 4}))), + Layer("N3", "N", "asked to describe the media first, does the answer start to follow it", ( + _describe("N3", "describe the media, then answer"),)), + Layer("U1", "U", "is the answer that moves close to a tie", ( + PlanStep("logprob_entropy", {}, "U1", "answer-token probabilities of the output", + calls_per_case={"logprobs": 1}, per_case=True), + PlanStep("self_consistency", {"n": 10}, "U1", "twice the samples: how often the answer moves", + key="self_consistency_n10", calls_per_case={"generate": 10}, per_case=True, + keep_artifacts=("samples",)))), + Layer("U2", "U", "with the options rotated, does the answer follow content or position", ( + PlanStep("format_sensitivity", {}, "U2", "rotate the options", calls_per_case={"generate": 3}, + task_kinds=("multiple_choice_letter",)),)), + Layer("Sb", "S", "does a stable error survive when the model first states what it sees", ( + _describe("Sb", "describe the media, then answer"),)), + Layer("S1", "S", "which image regions the gold margin depends on (no reference regions: " + "concentration only, not 'mislocalised')", ( + PlanStep("gradcam", {"target": "gold"}, "S1", "gradient x activation map of the gold margin", + calls_per_case={"backward": 1}), + PlanStep("generic_attention", {"target": "gold"}, "S1", "attention relevance of the gold margin", + fidelity_check="edit", calls_per_case={"backward": 1}))), + Layer("S2", "S", "is the case's own question word readable off the media tokens", (), served_by=("embed_lens",)), + Layer("S3", "S", "was the gold answer readable before the output", ( + PlanStep("tuned_lens", {}, "S3", "fitted per-layer readout of the answer position", + calls_per_case={"forward": 1}, reuse=False, reuse_note=_FIT_ON_BATCH), + PlanStep("layer_contrast", {}, "S3", "early-vs-late layer contrast at the answer position", + calls_per_case={"forward": 1})), + served_by=("patchscope",)), + Layer("X1", "X", "with the media removed instead of swapped, does the answer change " + "(a different intervention: it does not test N)", ( + PlanStep("modality_ablation", {"mode": "drop"}, "X1", "re-ask without the media", + key="media_drop", calls_per_case={"generate": 2}),), + case_filter=lambda r: r["N"]["state"] == "untested", + filter_note="X cases whose N check is missing (a case without media has N not applicable)"), +) + + +def candidate_steps(layers: "tuple[Layer, ...]" = LAYERS) -> list[PlanStep]: + return [c for layer in layers for c in layer.candidates] + + +# -- case sets ----------------------------------------------------------------------- + + +def route_fail_ids(records: list[dict[str, Any]], route: str, + case_filter: "Callable[[dict[str, Any]], bool] | None" = None) -> list[str]: + return [r["case_id"] for r in records if r["label"] == "fail" and route in r["routes"] + and (case_filter is None or case_filter(r))] + + +def matched_controls(records: list[dict[str, Any]], fail_ids: list[str], + rank: Callable[[str], Any]) -> tuple[list[str], dict[str, int]]: + """As many PASS cases per stratum as *fail_ids* has there, by sampler rank; and any shortfall.""" + by_id = {r["case_id"]: r for r in records} + need: dict[str, int] = {} + for cid in fail_ids: + need[by_id[cid]["stratum"]] = need.get(by_id[cid]["stratum"], 0) + 1 + controls, shortfall = [], {} + for stratum, k in sorted(need.items()): + pool = sorted((r["case_id"] for r in records if r["label"] == "pass" and r["stratum"] == stratum), key=rank) + controls += pool[:k] + if len(pool) < k: + shortfall[stratum] = k - len(pool) + return controls, shortfall + + +# -- routes ------------------------------------------------------------------------------ + + +def active_routes(records: list[dict[str, Any]], min_route_fail: int) -> list[dict[str, Any]]: + """Every route with FAIL cases, ``active`` when it has enough, in round order.""" + rows = [] + for route in ROUTE_ORDER: + n = len(route_fail_ids(records, route)) + if n: + rows.append({"route": route, "n_fail": n, "active": n >= min_route_fail}) + return sorted(rows, key=lambda r: (r["route"] != "H", -r["n_fail"], ROUTE_ORDER.index(r["route"]))) + + +@dataclass +class Proposal: + layer: Layer + step: PlanStep + kind: str # "open" (a new layer or fallback) | "extend" (a done layer, new cases) + fail_ids: list[str] + control_ids: list[str] + todo: list[str] + tried: list[dict[str, Any]] + before: list[dict[str, Any]] # the earlier layers' states + + @property + def target_ids(self) -> list[str]: + return [*self.fail_ids, *self.control_ids] + + +Gate = Callable[[PlanStep, list[str]], "tuple[str, str] | None"] + + +def layer_state(layer: Layer, evidence: dict[str, StepEvidence], fail_ids: list[str], target_ids: list[str], + gate: Gate, blocked: "dict[str, str] | None" = None) -> dict[str, Any]: + """``done`` / ``extend`` / ``open`` / ``exhausted`` for *layer* on these cases, with what was passed over.""" + blocked = blocked or {} + if not fail_ids: + return {"rule_id": layer.rule_id, "state": "no_cases"} + for name in layer.served_by: + ev = evidence.get(name) + if ev is not None and ev.valid_on(fail_ids): + return {"rule_id": layer.rule_id, "state": "done", "via": name, "battery": True} + tried: list[dict[str, Any]] = [] + for name in layer.served_by: + ev = evidence.get(name) + obs = next((o for cid in fail_ids if ev is not None and (o := ev.for_case(cid)) is not None), None) + tried.append({"key": name, "status": ",".join(ev.statuses_on(fail_ids)) if obs is not None else "not run", + "battery": True, **({"reason": obs.error} if obs is not None and obs.error else {})}) + for step in layer.candidates: + ev = evidence.get(step.name) + if ev is not None and ev.valid_on(fail_ids): + todo = ev.todo(target_ids) + if todo and step.name not in blocked: + return {"rule_id": layer.rule_id, "state": "extend", "via": step.name, "step": step, + "todo": todo, "tried": tried} + return {"rule_id": layer.rule_id, "state": "done", "via": step.name, "tried": tried, + **({"incomplete": blocked[step.name]} if todo else {})} + if ev is not None and any(cid in ev.covered() for cid in fail_ids): + tried.append({"key": step.name, "status": ",".join(ev.statuses_on(fail_ids))}) + continue + if step.name in blocked: + tried.append({"key": step.name, "status": "blocked", "reason": blocked[step.name]}) + continue + why = gate(step, target_ids) + if why is not None: + tried.append({"key": step.name, "status": why[0], "reason": why[1]}) + continue + return {"rule_id": layer.rule_id, "state": "open", "step": step, + "todo": ev.todo(target_ids) if ev is not None else list(target_ids), "tried": tried} + return {"rule_id": layer.rule_id, "state": "exhausted", "tried": tried} + + +def route_states(route: str, records: list[dict[str, Any]], evidence: dict[str, StepEvidence], gate: Gate, + rank: Callable[[str], Any], *, layers: "tuple[Layer, ...]" = LAYERS, + blocked: "dict[str, str] | None" = None) -> list[dict[str, Any]]: + """Every layer of *route*, in order, with its state on the route's current cases.""" + out = [] + for layer in (x for x in layers if x.route == route): + fail_ids = route_fail_ids(records, route, layer.case_filter) + controls, shortfall = matched_controls(records, fail_ids, rank) + state = layer_state(layer, evidence, fail_ids, [*fail_ids, *controls], gate, blocked) + out.append({**state, "question": layer.question, "n_fail": len(fail_ids), "n_controls": len(controls), + "control_shortfall": shortfall, "_fail_ids": fail_ids, "_control_ids": controls}) + return out + + +def next_for_route(route: str, records: list[dict[str, Any]], evidence: dict[str, StepEvidence], gate: Gate, + rank: Callable[[str], Any], *, layers: "tuple[Layer, ...]" = LAYERS, + blocked: "dict[str, str] | None" = None) -> "Proposal | None": + """The route's first layer that is open or needs extending, as a proposal; ``None`` when none is.""" + by_id = {x.rule_id: x for x in layers} + states = route_states(route, records, evidence, gate, rank, layers=layers, blocked=blocked) + for i, st in enumerate(states): + if st["state"] in ("open", "extend"): + # what this choice passed over: the exhausted layers before it, and this layer's own + tried = [{**t, "rule_id": s["rule_id"]} for s in [*states[:i], st] + if s is st or s["state"] == "exhausted" for t in s.get("tried", [])] + return Proposal(layer=by_id[st["rule_id"]], step=st["step"], kind=st["state"], + fail_ids=st["_fail_ids"], control_ids=st["_control_ids"], todo=st["todo"], + tried=tried, before=[public(s) for s in states[:i]]) + return None + + +def public(state: dict[str, Any]) -> dict[str, Any]: + """A layer state without its case lists and step object, for the trace and the report.""" + out = {k: v for k, v in state.items() if not k.startswith("_") and k != "step"} + if "todo" in out: + out["todo"] = len(out["todo"]) + if "step" in state: + out["key"] = state["step"].name + return out + + +# -- expansion ------------------------------------------------------------------------- + + +def expansion_gaps(summary: dict[str, Any], records: list[dict[str, Any]], *, min_cohort: int) -> list[dict[str, Any]]: + """The evidence gaps a larger nested sample could close (see the module docstring).""" + gaps = [] + for tag in ("H_label_free", "N", "U"): + row = summary.get(tag) or {} + ci = row.get("signal_ci95") + if row.get("routing_signal") and ci is not None and ci[0] <= 0.0: + gaps.append({"gap": "signal_uncertain", "route": tag, "routing_signal": row["routing_signal"], + "ci95": ci, "n_tested": [row["fail"]["n_tested"], row["pass"]["n_tested"]]}) + for stratum in sorted({r["stratum"] for r in records if r["label"] == "fail" and r["stable"]}): + n_s = sum(1 for r in records if r["label"] == "fail" and r["stable"] and r["stratum"] == stratum) + n_c = sum(1 for r in records if r["label"] == "pass" and r["stable"] and r["stratum"] == stratum) + if min(n_s, n_c) < min_cohort: + gaps.append({"gap": "s_cohort_small", "stratum": stratum, "n_S": n_s, "n_stable_pass": n_c, + "min_cohort": min_cohort}) + return gaps + + +def next_size(n_fail: int, max_fail: int, n_available: int) -> "int | None": + """The doubled FAIL count, capped; ``None`` when the sample cannot grow.""" + n = min(2 * n_fail, max_fail, n_available) + return n if n > n_fail else None diff --git a/evalrx/eval_agent/probing/sampler.py b/evalrx/eval_agent/probing/sampler.py index 973e30d3..7101958b 100644 --- a/evalrx/eval_agent/probing/sampler.py +++ b/evalrx/eval_agent/probing/sampler.py @@ -41,10 +41,14 @@ def single_stratum(case: Any) -> str: STRATA: dict[str, Callable[[Any], str]] = {"gold": gold_stratum, "none": single_stratum} -def _rank(seed: int, case_id: str) -> str: +def rank(seed: int, case_id: str) -> str: + """The case's fixed place in every draw with this seed (draws take rank prefixes).""" return hashlib.sha1(f"{seed}:{case_id}".encode("utf-8")).hexdigest() +_rank = rank + + @dataclass(frozen=True) class SampleDraw: """Which cases a draw took and why; ``case_ids`` keeps the batch order.""" diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index 2f93305c..19007513 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -36,12 +36,14 @@ from __future__ import annotations +import math from collections import Counter from typing import Any, Callable from evalrx.analyzers.perturbation.prompt_contrast import _norm_answer from evalrx.core.case import MEDIA_SLOTS from evalrx.eval_agent.probing.actions import OK, Observation +from evalrx.eval_agent.probing.evidence import StepEvidence, pick FIRED, CLEAR, UNTESTED, NOT_APPLICABLE = "fired", "clear", "untested", "not_applicable" @@ -65,6 +67,11 @@ AnswerFn = Callable[[Any, str], "str | None"] +#: The plan steps the H/N/U checks (and so the routes, S and X) are read from. +#: Every other step only adds descriptive readings to a case. +ROUTE_STEPS = frozenset({"answer_extraction_audit", "termination_audit", "modality_ablation", + "self_consistency", "prompt_reword"}) + def default_answer(case: Any, text: str) -> str: """Coarse answer key when the host gives none: yes/no, else a normalised prefix.""" @@ -316,13 +323,16 @@ def _s_patchscope(obs: "Observation | None", cid: str) -> dict[str, Any]: return out -def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assumed_finish: bool, +def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence]", *, + host_assumed_finish: bool, answer_contract: bool, n_needs_counterfactual: bool = False, answer_fn: "AnswerFn | None" = None) -> list[dict[str, Any]]: """One record per case: label, stratum, every H/N/U check, routes, knockout and S readings. *observations* are keyed by plan step (``prompt_reword`` and - ``prompt_threshold`` are the two ``prompt_contrast`` steps). + ``prompt_threshold`` are the two ``prompt_contrast`` steps): one + observation, or a :class:`StepEvidence` whose chunks each measured part of + the sample (each case is read from the chunk that measured it). *n_needs_counterfactual* (few-answer tasks: yes/no, letters): a swap only tests N when its donor is a counterfactual — the same question's gold on that @@ -341,7 +351,7 @@ def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assum cid = str(case.id) provenance = finish_reason_source(case, host_assumed_finish) h_fields = [ - _h_field(observations.get(a), a, f, link, kind, cid, provenance, answer_contract) + _h_field(pick(observations, a, cid), a, f, link, kind, cid, provenance, answer_contract) for a, f, link, kind in H_FIELDS ] free = [f for f in h_fields if f["label_link"] is None] @@ -360,8 +370,9 @@ def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assum "fields": h_fields, "disagreements": disagreements, } - n = _n_check(observations.get("modality_ablation"), case, n_needs_counterfactual) - u = _u_check(observations.get("self_consistency"), observations.get("prompt_reword"), case, answer) + n = _n_check(pick(observations, "modality_ablation", cid), case, n_needs_counterfactual) + u = _u_check(pick(observations, "self_consistency", cid), pick(observations, "prompt_reword", cid), + case, answer) label = getattr(getattr(case, "label", None), "value", None) checks = {"H": h["state"], "N": n["state"], "U": u["state"]} routes = [tag for tag, state in checks.items() if state == FIRED] @@ -386,11 +397,12 @@ def triage_cases(cases: Any, observations: dict[str, Observation], *, host_assum "H": h, "N": n, "U": u, - "knockout": _knockout(observations.get("attention_knockout"), cid), + "knockout": _knockout(pick(observations, "attention_knockout", cid), cid), "S_readings": { - "threshold": _s_threshold(observations.get("prompt_threshold"), case, answer), - "embed_lens": _measured_row(observations.get("embed_lens"), cid, "embed_lens", _EMBED_FIELDS), - "patchscope": _s_patchscope(observations.get("patchscope"), cid), + "threshold": _s_threshold(pick(observations, "prompt_threshold", cid), case, answer), + "embed_lens": _measured_row(pick(observations, "embed_lens", cid), cid, "embed_lens", + _EMBED_FIELDS), + "patchscope": _s_patchscope(pick(observations, "patchscope", cid), cid), }, }) return records @@ -483,9 +495,9 @@ def _threshold_table(records: list[dict[str, Any]]) -> "dict[str, Any] | None": def _s_readings(records: list[dict[str, Any]]) -> dict[str, Any]: """Embed-lens and Patchscope readings per cohort and stratum; descriptive only.""" out: dict[str, Any] = {} - for name, pick in _COHORTS.items(): - for stratum in sorted({r["stratum"] for r in records if pick(r)}): - group = [r for r in records if pick(r) and r["stratum"] == stratum] + for name, member in _COHORTS.items(): + for stratum in sorted({r["stratum"] for r in records if member(r)}): + group = [r for r in records if member(r) and r["stratum"] == stratum] el = [r["S_readings"]["embed_lens"] for r in group if r["S_readings"]["embed_lens"]["state"] == "measured"] ps = [r["S_readings"]["patchscope"] for r in group @@ -511,12 +523,32 @@ def _s_readings(records: list[dict[str, Any]]) -> dict[str, Any]: return out +def _wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]: + p, z2 = k / n, z * z + centre = (p + z2 / (2 * n)) / (1 + z2 / n) + half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n) + return max(0.0, centre - half), min(1.0, centre + half) + + +def difference_interval(k1: int, n1: int, k2: int, n2: int) -> "list[float] | None": + """95% interval of ``k1/n1 - k2/n2`` (Newcombe's hybrid score method), ``None`` if a side is empty.""" + if not n1 or not n2: + return None + p1, p2 = k1 / n1, k2 / n2 + (l1, u1), (l2, u2) = _wilson(k1, n1), _wilson(k2, n2) + d = p1 - p2 + return [round(d - math.sqrt((p1 - l1) ** 2 + (u2 - p2) ** 2), 4), + round(d + math.sqrt((u1 - p1) ** 2 + (p2 - l2) ** 2), 4)] + + def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: """Per-route FAIL/PASS rates on this sample, the S cohort and its descriptive readings. ``routing_signal = max(0, P(tag|FAIL) - P(tag|PASS))`` steers where the next actions go on THIS sample; it is not an explained share of failures - and says nothing about causes. H uses only label-free fields here. + and says nothing about causes. ``signal_ci95`` is the 95% interval of the + unclipped difference: how sure this sample is that the difference is not + zero, which the expansion rule reads. H uses only label-free fields here. """ tags = { "H_label_free": lambda r: r["H"]["state_label_free"], @@ -528,7 +560,9 @@ def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: fail, pas = _rate(records, "fail", state_of), _rate(records, "pass", state_of) signal = (round(max(0.0, fail["rate"] - pas["rate"]), 4) if fail["rate"] is not None and pas["rate"] is not None else None) - out[tag] = {"fail": fail, "pass": pas, "routing_signal": signal} + out[tag] = {"fail": fail, "pass": pas, "routing_signal": signal, + "signal_ci95": difference_interval(fail["n_fired"], fail["n_tested"], + pas["n_fired"], pas["n_tested"])} out["H_any_audit_only"] = { label: _rate(records, label, lambda r: r["H"]["state"]) for label in ("fail", "pass") } @@ -554,3 +588,79 @@ def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: ko["_note"] = "descriptive only: margin deltas of the gold first token, no test, no mechanism claim" out["attention_knockout"] = ko return out + + +# -- follow-up readings ------------------------------------------------------------ + + +def _numeric(row: dict[str, Any]) -> dict[str, float]: + out: dict[str, float] = {} + for key, value in row.items(): + if key == "sample_id" or key.startswith("_"): + continue + if isinstance(value, bool): + out[key] = float(value) + elif isinstance(value, (int, float)) and math.isfinite(float(value)): + out[key] = float(value) + return out + + +def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn) -> dict[str, float]: + """``prompt_contrast``: per strategy, whether the answer moved off the re-asked + question (by answer key) and whether that fixed or broke it (by the task's scorer).""" + cid = str(case.id) + outputs, scored = _outputs(obs), (obs.findings or {}).get("by_strategy") or {} + if cid not in (outputs.get("baseline") or {}): + return {} + base = answer_fn(case, outputs["baseline"][cid]) + before = (scored.get("baseline") or {}).get(cid) + out: dict[str, float] = {} + for strategy, texts in outputs.items(): + if strategy == "baseline" or cid not in texts: + continue + alt = answer_fn(case, texts[cid]) + if base and alt: + out[f"changed_{strategy}"] = float(alt != base) + after = (scored.get(strategy) or {}).get(cid) + if before is not None and after is not None: + out[f"fixed_{strategy}"] = float(before == 0.0 and after == 1.0) + out[f"broken_{strategy}"] = float(before == 1.0 and after == 0.0) + return out + + +def follow_up_values(evidence: StepEvidence, case: Any, answer_fn: "AnswerFn | None" = None) -> dict[str, Any]: + """One case's numeric readings from a follow-up step, or why there are none.""" + cid = str(case.id) + obs = evidence.for_case(cid) + if obs is None: + return {"state": UNTESTED, "reason": "not run on this case"} + if obs.status != OK: + return {"state": UNTESTED, "action_id": obs.action_id, "reason": f"{obs.status}: {obs.error or ''}".strip()} + values = _numeric(obs.per_case().get(cid) or {}) + if evidence.step.analyzer == "prompt_contrast": + values.update(_contrast_values(obs, case, answer_fn or default_answer)) + if not values: + return {"state": UNTESTED, "action_id": obs.action_id, "reason": obs.missing.get(cid, "no per_case row")} + return {"state": "measured", "action_id": obs.action_id, "values": values} + + +def follow_up_reading(evidence: StepEvidence, cases: Any, route_ids: "list[str]", control_ids: "list[str]", + answer_fn: "AnswerFn | None" = None) -> dict[str, Any]: + """Mean of every numeric per-case reading over the route's FAIL cases and their PASS controls. + + Descriptive, like the S readings: no test, and a field is listed even when + one cohort has no value for it. ``n_by_field`` counts the cases behind each + mean (an answer-change reading needs both answers readable). + """ + by_id = {str(c.id): c for c in cases} + rows = {cid: follow_up_values(evidence, by_id[cid], answer_fn) for cid in [*route_ids, *control_ids]} + out: dict[str, Any] = {} + for name, ids in (("route_fail", route_ids), ("controls", control_ids)): + measured = [rows[cid]["values"] for cid in ids if rows[cid]["state"] == "measured"] + fields = sorted({k for v in measured for k in v}) + out[name] = {"n": len(ids), "n_measured": len(measured), + "means": {f: _mean([v[f] for v in measured if f in v]) for f in fields}, + "n_by_field": {f: sum(1 for v in measured if f in v) for f in fields}, + "untested": dict(Counter(rows[cid]["reason"] for cid in ids + if rows[cid]["state"] != "measured"))} + return out diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index 929ac579..e286ca65 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -451,6 +451,11 @@ def vlm_cases(): return CaseBatch(out) +def _steps(report): + """The battery's executions on the first sample, by step key.""" + return {e["key"]: e for e in report["executions"] if e["kind"] == "battery"} + + def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): from tests.tiny_whitebox import TinyVLM @@ -462,8 +467,8 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) report = run_triage_mvp0(model, vlm_cases, **kw) - steps = {s["key"]: s for s in report["steps"]} - assert [s["status"] for s in report["steps"]] == [OK] * 9 + steps = _steps(report) + assert [s["status"] for s in report["executions"]] == [OK] * 9 # 2 FAIL: no route proposes assert steps["answer_extraction_audit"]["cost"]["calls"] == {} # Stage-0 outputs re-read assert steps["modality_ablation"]["cost"]["calls"] == {"generate": 8} # 4 cases x (base + swap) assert steps["attention_knockout"]["fidelity"]["status"] == "passed" @@ -473,8 +478,10 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): assert steps["prompt_threshold"]["cost"]["calls"] == {"generate": 8} assert steps["patchscope"]["fidelity"]["status"] == "passed" checks = report["checks"] - assert checks["only_planned_actions"] and checks["stage0_cost_separate"] - assert all(checks["case_sets_match_plan"].values()) and all(checks["configs_match_plan"].values()) + assert checks["only_rule_actions"] and checks["stage0_cost_separate"] + assert all(checks["battery_covers_sample"].values()) and all(checks["configs_match_plan"].values()) + assert all(checks["batch_dependent_read_from_current_sample"].values()) + assert report["stop"]["reason"] == "no_candidate" and report["decisions"] == [] sample = report["sample"] assert len(sample["fail_ids"]) == 2 and sample["strata"]["no"]["pass"] == 2 @@ -507,7 +514,7 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): # (only this invocation's Stage 0, which the caller did spend) n_forwards = model.n_forwards again = run_triage_mvp0(model, vlm_cases, **kw) - assert all(s["reused"] for s in again["steps"]) and model.n_forwards == n_forwards + assert all(s["reused"] for s in again["executions"]) and model.n_forwards == n_forwards costs2 = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] assert [c["kind"] for c in costs2[len(costs):]] == ["stage0"] and costs2[-1]["invocation"] == 2 events = [json.loads(line) for line in (out / "selection_trace.jsonl").read_text().splitlines()] @@ -515,12 +522,12 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): # a different model identity is a different action: nothing is reused other = run_triage_mvp0(model, vlm_cases, **{**kw, "model_identity": {**ident, "dtype": "fp32"}}) - assert not any(s["reused"] for s in other["steps"]) + assert not any(s["reused"] for s in other["executions"]) def _rerun(report): """Steps that executed again instead of being read back (not-applicable steps never run).""" - return [s["key"] for s in report["steps"] if s["status"] != "not_applicable" and not s["reused"]] + return [s["key"] for s in report["executions"] if s["status"] != "not_applicable" and not s["reused"]] def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch): @@ -535,7 +542,7 @@ def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch lambda a: real(a) + ("-edited" if a.name == "attention_knockout" else "")) second = run_triage_mvp0(model, vlm_cases, **kw) assert _rerun(second) == ["attention_knockout"] - assert second["steps"][3]["action_id"] != first["steps"][3]["action_id"] + assert _steps(second)["attention_knockout"]["action_id"] != _steps(first)["attention_knockout"]["action_id"] def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): @@ -545,7 +552,7 @@ def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): model = TinyVLM("qwen2_5_vl") kw = dict(out_dir=tmp_path / "p", model_identity={"spec": "tiny"}, n_fail=2, progress=None) first = run_triage_mvp0(model, vlm_cases, **kw) - ko_id = [s for s in first["steps"] if s["analyzer"] == "attention_knockout"][0]["action_id"] + ko_id = _steps(first)["attention_knockout"]["action_id"] ledger = Ledger(tmp_path / "p") (ledger.obs_dir / f"{ko_id}.json").unlink() # as if the process died before settling second = run_triage_mvp0(model, vlm_cases, **kw) @@ -559,7 +566,7 @@ def test_mvp0_black_box_gates_off_the_white_box_step(tmp_path, vlm_cases): model = _BlackBox() report = run_triage_mvp0(model, vlm_cases, out_dir=tmp_path / "bb", model_identity={"spec": "bb"}, n_fail=2, progress=None) - steps = {s["key"]: s for s in report["steps"]} + steps = _steps(report) assert steps["attention_knockout"]["status"] == UNSUPPORTED assert steps["attention_knockout"]["cost"]["calls"] == {} assert steps["modality_ablation"]["status"] == OK @@ -593,17 +600,17 @@ def forward(self, inputs, capture, spec=None): raise NotImplementedError -def test_api_run_meters_tokens_and_dollars_and_names_its_next_behavioural_experiments(tmp_path, vlm_cases): +def test_api_run_meters_tokens_and_dollars_and_runs_its_behavioural_follow_up(tmp_path, vlm_cases): from evalrx.models.backends.api.prices import usd model = _FakeAPI() report = run_triage_mvp0( model, vlm_cases, out_dir=tmp_path / "api", model_identity={"spec": "fake-api"}, n_fail=2, - task_kind="yes_no", n_needs_counterfactual=True, progress=None, + min_route_fail=1, task_kind="yes_no", n_needs_counterfactual=True, progress=None, analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, price_fn=lambda u: usd("gemini-3.1-flash-lite", u), stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}, "api_usage": {"requests": 8}, "usd": 0.001}) - steps = {s["key"]: s for s in report["steps"]} + steps = _steps(report) for key in ("attention_knockout", "embed_lens", "patchscope"): # no internals: gated, nothing spent assert steps[key]["status"] == UNSUPPORTED and steps[key]["cost"]["calls"] == {} swap = steps["modality_ablation"]["cost"] @@ -611,18 +618,30 @@ def test_api_run_meters_tokens_and_dollars_and_names_its_next_behavioural_experi assert swap["usd"] == usd("gemini-3.1-flash-lite", swap["api_usage"]) run = report["cost"]["actions_run"] assert run["api_usage"]["requests"] == model.counters["requests"] == sum(run["calls"].values()) - assert run["usd"] == round(sum(s["cost"].get("usd") or 0 for s in report["steps"] if s.get("cost")), 6) + assert run["usd"] == round(sum(s["cost"].get("usd") or 0 for s in report["executions"] if s.get("cost")), 6) assert report["cost"]["stage0"]["usd"] == 0.001 # sampling ran: the U sampling part is tested, not left untested as on greedy settings assert all(r["U"]["parts"][0]["state"] in ("fired", "clear") for r in report["cases"]) - # the FAIL cases keep "Yes" after a swap that should make it "no": N, whose next - # behavioural step can run here while the internal one cannot - n_next = {c["analyzer"]: c for c in report["next_candidates"]["candidates"] if c["route"] == "N"} - assert n_next["prompt_contrast"]["status"] == "executable" - assert n_next["causal_trace"]["status"] == "unsupported" and "hidden_states" in n_next["causal_trace"]["reason"] - assert n_next["(nested sample expansion)"]["status"] == "not_implemented" + # the FAIL cases keep "Yes" after a swap that should make it "no": N. Its internal + # layers are gated off at no cost, and the behavioural one runs on the two FAIL + # cases and their two matched PASS controls + (decision,) = report["decisions"] + assert (decision["route"], decision["rule_id"], decision["key"]) == ("N", "N3", "describe_first") + passed = {t["key"]: t for t in decision["passed_over"]} + assert passed["attention_knockout"]["battery"] and passed["attention_knockout"]["status"] == "unsupported" + assert passed["causal_trace"]["status"] == "unsupported" and "hidden_states" in passed["causal_trace"]["reason"] + assert passed["attention_temperature"]["status"] == passed["attention_sensitivity"]["status"] == "unsupported" + follow = report["executions"][-1] + assert follow["kind"] == "follow_up" and follow["n_cases"] == 4 and follow["cost"]["calls"] == {"generate": 8} + (fu,) = report["follow_ups"] + assert fu["reading"]["route_fail"]["n_measured"] == 2 and fu["reading"]["controls"]["n_measured"] == 2 + assert fu["reading"]["route_fail"]["means"]["changed_describe_first"] == 0.0 # "Yes" whatever the prompt + assert fu["reading"]["route_fail"]["n_by_field"]["changed_describe_first"] == 2 + assert report["stop"]["reason"] == "no_candidate" + layers = {st["rule_id"]: st["state"] for st in report["routes"][0]["layers"]} + assert layers == {"N1": "exhausted", "N2": "exhausted", "N3": "done"} md = (tmp_path / "api" / "triage_report.md").read_text() - assert "Next candidates" in md and "USD" in md + assert "## Decisions" in md and "Follow-ups" in md and "USD" in md assert "Not measured: unsupported (model lacks capabilities" in md # knockout, no table of Nones assert "Not measured: embed_lens unsupported" in md diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_probing_mvp2.py new file mode 100644 index 00000000..e27b6829 --- /dev/null +++ b/tests/test_eval_agent/test_probing_mvp2.py @@ -0,0 +1,407 @@ +"""MVP-2 triage: nested expansion with per-case reuse, and follow-ups chosen by fixed rules. + +* expanding 4 -> 8 FAIL cases gives every case the same record as drawing 8 at + once, for the same model calls: only the new cases run; +* the per-case rows of every ``reuse`` step do not depend on the batch; +* a rerun with a larger cap reads the earlier chunks back and extends the + follow-ups only to the new cases; +* a failed or refused candidate falls back within its layer, a valid one + advances to the next layer, and a refusal on any chunk refuses the step; +* the expansion rule fires on an uncertain routing signal or a small S + cohort, and stops at the cap. +""" + +from __future__ import annotations + +import pytest + +from evalrx.core.capability import Capability +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.core.model import Model +from evalrx.eval_agent.probing import BATTERY, LAYERS, run_triage +from evalrx.eval_agent.probing.actions import FAILED, OK, UNFAITHFUL, Observation +from evalrx.eval_agent.probing.evidence import StepEvidence +from evalrx.eval_agent.probing.rules import ( + active_routes, + candidate_steps, + expansion_gaps, + next_for_route, + next_size, +) +from evalrx.eval_agent.probing.triage import difference_interval + +OBJECTS = ("cat", "dog", "car", "cup") + + +def _pope_like(n_images: int = 24): + """POPE-like: each image is asked about one present (Yes) and one absent (No) object, and + every question recurs across images; the model answers wrong on 10 of the 48 cases.""" + cases, table = [], {} + for i in range(n_images): + img = f"img{i}" + for j, (obj, gold) in enumerate(((OBJECTS[i % 4], "Yes"), (OBJECTS[(i + 1) % 4], "No"))): + q = f"Is there a {obj} in the image?" + wrong = (7 * i + j) % 5 == 0 + ans = ("No" if gold == "Yes" else "Yes") if wrong else gold + table[(q, img)] = ans + cases.append(FailureCase(id=f"c{i}-{j}", inputs=Inputs(prompt=q, image=img), expected=gold, + observed=ans, label=Label.FAIL if wrong else Label.PASS, + metadata={"gold": gold, "finish_reason": "stop"})) + return CaseBatch(cases), table + + +class _Table(Model): + """A black box that answers from a table keyed by (question, image), whatever wraps the + question: deterministic, so its answers cannot depend on the batch.""" + + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text", "image"}) + + def __init__(self, table): + self.table, self.n_generate = table, 0 + + def generate(self, inputs, **kwargs): + self.n_generate += 1 + for (q, img), ans in self.table.items(): + if q in str(inputs.prompt) and img == inputs.image: + return ans + return "No" + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +def _yes_no(case, text): + t = str(text).strip().lower() + return "yes" if t.startswith("yes") else "no" if t.startswith("no") else "" + + +def _kw(out, **over): + kw = dict(out_dir=out, model_identity={"spec": "table"}, n_fail=4, seed=0, host_assumed_finish=True, + n_needs_counterfactual=True, task_kind="yes_no", answer_fn=_yes_no, min_cohort=100, + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, progress=None) + return {**kw, **over} + + +def _strip(x): + if isinstance(x, dict): + return {k: _strip(v) for k, v in x.items() if k != "action_id"} + if isinstance(x, list): + return [_strip(v) for v in x] + return x + + +def _generated(report, kinds=("battery", "expansion")): + return sum((e.get("cost") or {}).get("calls", {}).get("generate", 0) for e in report["executions"] + if e["kind"] in kinds and not e["reused"]) + + +def test_expansion_runs_only_new_cases_and_matches_drawing_the_larger_sample_at_once(tmp_path): + cases, table = _pope_like() + grown_model, direct_model = _Table(table), _Table(table) + grown = run_triage(grown_model, cases, **_kw(tmp_path / "grown", max_fail=8, max_actions=1)) + direct = run_triage(direct_model, cases, **_kw(tmp_path / "direct", n_fail=8, max_actions=0)) + + (expand,) = [d for d in grown["decisions"] if d["kind"] == "expand"] + assert (expand["from_fail"], expand["to_fail"]) == (4, 8) + assert {g["gap"] for g in expand["gaps"]} == {"s_cohort_small"} + assert grown["sample"]["case_ids"] == direct["sample"]["case_ids"] + n_new = expand["n_new_cases"] + for e in grown["executions"]: + if e["kind"] == "expansion" and e["status"] != "not_applicable": + assert next(s for s in BATTERY if s.name == e["key"]).reuse and e["n_cases"] == n_new + # the batch-dependent steps the routes do not read run once, on the settled sample + for key in ("embed_lens", "patchscope"): + (once,) = [e for e in grown["executions"] if e["key"] == key] + assert (once["revision"], once["n_cases"]) == (1, len(direct["sample"]["case_ids"])) + # every case reads the same as when the 8-FAIL sample is drawn at once, for the same calls + assert {r["case_id"]: _strip(r) for r in grown["cases"]} == {r["case_id"]: _strip(r) for r in direct["cases"]} + assert _generated(grown) == _generated(direct) == grown_model.n_generate == direct_model.n_generate + checks = grown["checks"] + assert all(checks["reused_chunks_disjoint"].values()) and all(checks["battery_covers_sample"].values()) + # the cap is reached with the gap still open: recorded, not retried; the next spend is refused + assert [d["kind"] for d in grown["decisions"]] == ["expand", "expand_not_possible"] + assert grown["expansion"]["state"] == "not_possible" and "cap of 8" in grown["expansion"]["reason"] + assert grown["stop"]["reason"] == "max_actions" and grown["stop"]["pending"] + assert [r["revision"] for r in grown["revisions"]] == [0, 1] + + +def test_rerun_reads_everything_back_and_a_larger_cap_extends_only_to_new_cases(tmp_path): + cases, table = _pope_like() + out = tmp_path / "p" + small_model = _Table(table) + small = run_triage(small_model, cases, **_kw(out, max_fail=4, min_route_fail=1)) + assert small["stop"]["reason"] == "no_candidate" and small["follow_ups"] + first = {(d["route"], d["key"]) for d in small["decisions"] if d["kind"] == "follow_up"} + assert ("N", "describe_first") in first or ("S", "describe_first") in first + + # same command: every action read back, the same decisions, no model call + again_model = _Table(table) + again = run_triage(again_model, cases, **_kw(out, max_fail=4, min_route_fail=1)) + assert again_model.n_generate == 0 and all(e["reused"] for e in again["executions"]) + assert [(d["kind"], d.get("key")) for d in again["decisions"]] == [(d["kind"], d.get("key")) + for d in small["decisions"]] + + # a larger cap: the battery and the follow-ups run on the cases the larger sample adds, only + big_model = _Table(table) + big = run_triage(big_model, cases, **_kw(out, max_fail=8, min_route_fail=1)) + assert big["revisions"][-1]["n_fail"] == 8 + fresh = [e for e in big["executions"] if e["kind"] == "follow_up" and not e["reused"]] + reread = [e for e in big["executions"] if e["kind"] == "follow_up" and e["reused"]] + assert reread, "the smaller run's follow-up chunks are read back" + new_ids = set(big["sample"]["case_ids"]) - set(small["sample"]["case_ids"]) + for fu in big["follow_ups"]: + assert fu["not_run_on"] in (0, None) + calls = sum(e["cost"]["calls"].get("generate", 0) for e in fresh if e.get("cost")) + assert calls == big_model.n_generate - _generated(big) + assert all(e["n_cases"] <= len(new_ids) for e in fresh if e["key"] == "describe_first") + assert all(big["checks"]["reused_chunks_disjoint"].values()) + + +def test_describe_first_is_not_applicable_under_a_short_output_cap(tmp_path): + cases, table = _pope_like() + ident = {"spec": "table", "generation": {"max_new_tokens": 16}} + report = run_triage(_Table(table), cases, **_kw(tmp_path / "cap", max_fail=4, min_route_fail=1, + model_identity=ident)) + assert not [d for d in report["decisions"] if d["kind"] == "follow_up"] + passed = [t for row in report["routes"] for st in row["layers"] for t in st.get("tried") or [] + if t["key"] == "describe_first"] + assert passed and all(t["status"] == "not_applicable" and "output cap of 16" in t["reason"] for t in passed) + + +def test_max_actions_zero_runs_only_the_battery(tmp_path): + cases, table = _pope_like() + report = run_triage(_Table(table), cases, **_kw(tmp_path / "z", max_fail=8, max_actions=0)) + assert report["decisions"] == [] and report["stop"] == {"reason": "max_actions", "max_actions": 0, + "pending": "expansion"} + assert {e["kind"] for e in report["executions"]} == {"battery"} + + +# -- rules --------------------------------------------------------------------------- + + +def _obs(step_key, ids, status=OK, rows=True): + return Observation(action_id=f"{step_key}-{status}-{ids[0]}", analyzer=step_key, attempt=1, status=status, + params={}, planned_ids=list(ids), + measured_ids=list(ids) if status == OK else [], + findings={"per_case": [{"sample_id": i, "v": 1.0} for i in ids]} if status == OK and rows + else None) + + +def _records(n_fail_route=None): + """Three N FAILs, two S FAILs (stratum yes), one H FAIL, and PASS controls in both strata.""" + rows = [] + for i, route in enumerate(n_fail_route or ["N", "N", "N", "S", "S", "H"]): + rows.append({"case_id": f"f{i}", "label": "fail", "stratum": "yes" if i % 2 else "no", + "routes": [route], "stable": route == "S", "N": {"state": "clear"}}) + for i in range(8): + rows.append({"case_id": f"p{i}", "label": "pass", "stratum": "yes" if i % 2 else "no", + "routes": [], "stable": True, "N": {"state": "clear"}}) + return rows + + +def _step(key): + by = {s.name: s for s in [*BATTERY, *candidate_steps(LAYERS)]} + return by[key] + + +def _no_gate(step, ids): + return None + + +def test_routes_go_h_first_then_by_failures_and_layers_fall_back_within_and_advance_between(): + records = _records() + order = [r["route"] for r in active_routes(records, min_route_fail=1)] + assert order == ["H", "N", "S"] + assert [r["route"] for r in active_routes(records, min_route_fail=3) + if r["active"]] == ["N"] + + n_ids = ["f0", "f1", "f2"] + ev = {"attention_knockout": StepEvidence(_step("attention_knockout"), [_obs("attention_knockout", n_ids)])} + # N1 is served by the battery's knockout; N2's representative is next + p = next_for_route("N", records, ev, _no_gate, str) + assert (p.layer.rule_id, p.step.name, p.kind) == ("N2", "attention_temperature", "open") + assert sorted(p.fail_ids) == n_ids and len(p.control_ids) == 3 # matched per stratum + + # a refused representative moves to its fallback in the SAME layer + target = [*p.fail_ids, *p.control_ids] + ev["attention_temperature"] = StepEvidence(_step("attention_temperature"), + [_obs("attention_temperature", target, status=UNFAITHFUL)]) + p = next_for_route("N", records, ev, _no_gate, str) + assert (p.layer.rule_id, p.step.name) == ("N2", "attention_sensitivity") + assert p.tried == [{"key": "attention_temperature", "status": "unfaithful", "rule_id": "N2"}] + + # a valid observation (whatever it shows) completes the layer: on to N3 + ev["attention_sensitivity"] = StepEvidence(_step("attention_sensitivity"), [_obs("attention_sensitivity", target)]) + p = next_for_route("N", records, ev, _no_gate, str) + assert (p.layer.rule_id, p.step.name) == ("N3", "describe_first") + + # when the knockout failed, N1's own fallback comes first; gated-off candidates are passed over + ev["attention_knockout"] = StepEvidence(_step("attention_knockout"), + [_obs("attention_knockout", n_ids, status=FAILED)]) + + def gate(step, ids): + return ("unsupported", "model lacks capabilities ['hidden_states']") if step.analyzer == "causal_trace" else None + + p = next_for_route("N", records, ev, gate, str) + assert (p.layer.rule_id, p.step.name) == ("N3", "describe_first") + assert [(t["rule_id"], t["key"], t["status"]) for t in p.tried] == [ + ("N1", "attention_knockout", "failed"), ("N1", "causal_trace", "unsupported")] + + +def test_a_layer_done_on_fewer_cases_is_extended_to_the_routes_new_cases_first(): + records = _records() + s_ids = ["f3", "f4"] + ev = {"describe_first": StepEvidence(_step("describe_first"), [_obs("describe_first", ["f3", "p1"])])} + p = next_for_route("S", records, ev, _no_gate, str) + assert (p.layer.rule_id, p.kind) == ("Sb", "extend") + assert sorted(p.todo) == sorted(set([*s_ids, *p.control_ids]) - {"f3", "p1"}) + assert sorted(p.fail_ids) == s_ids + + +def test_a_refusal_on_any_chunk_refuses_the_step_on_every_case(): + step = _step("attention_knockout") + ev = StepEvidence(step, [_obs("ko", ["a", "b"]), _obs("ko", ["c"], status=UNFAITHFUL)]) + assert ev.for_case("a").status == UNFAITHFUL and not ev.valid_on(["a", "b"]) + plain = StepEvidence(_step("self_consistency"), [_obs("sc", ["a", "b"]), _obs("sc", ["c"], status=FAILED)]) + assert plain.for_case("a").status == OK and plain.for_case("c").status == FAILED + assert plain.todo(["a", "b", "c", "d"]) == ["d"] + batchy = StepEvidence(_step("embed_lens"), [_obs("el", ["a", "b"])]) + assert batchy.todo(["a", "b"]) == [] and batchy.todo(["a", "b", "c"]) == ["a", "b", "c"] + + +def test_expansion_gaps_and_sizes(): + lo, hi = difference_interval(3, 8, 0, 8) + assert lo < 0 < hi # 3/8 vs 0/8: not sure the difference is not zero + assert difference_interval(13, 32, 1, 32)[0] > 0 + assert difference_interval(1, 0, 0, 4) is None + + def summary(k_fail, k_pass, n): + rate = {"fail": {"n_fired": k_fail, "n_tested": n}, "pass": {"n_fired": k_pass, "n_tested": n}} + d = (k_fail - k_pass) / n + return {"U": {**rate, "routing_signal": max(0.0, d), "signal_ci95": difference_interval(k_fail, n, k_pass, n)}, + "N": {**rate, "routing_signal": 0.0, "signal_ci95": None}, + "H_label_free": {**rate, "routing_signal": None, "signal_ci95": None}} + + records = _records() + assert [g["route"] for g in expansion_gaps(summary(3, 0, 8), records, min_cohort=1) + if g["gap"] == "signal_uncertain"] == ["U"] + assert not expansion_gaps(summary(13, 1, 32), records, min_cohort=1) + cohort = expansion_gaps(summary(13, 1, 32), records, min_cohort=8) + assert cohort == [{"gap": "s_cohort_small", "stratum": "yes", "n_S": 1, "n_stable_pass": 4, "min_cohort": 8}, + {"gap": "s_cohort_small", "stratum": "no", "n_S": 1, "n_stable_pass": 4, "min_cohort": 8}][::-1] + assert next_size(8, 32, 100) == 16 and next_size(16, 32, 20) == 20 and next_size(32, 32, 100) is None + + +def test_budget_estimates_come_from_the_same_steps_earlier_seconds(tmp_path): + from evalrx.eval_agent.probing.controller import _Run + from evalrx.eval_agent.probing.ledger import Ledger + + cases, table = _pope_like() + ledger = Ledger(tmp_path / "b") + run = _Run(_Table(table), cases, ledger, context={}, extras={}, task_kind="yes_no", budget_sec=10.0, + price_fn=None, run_logger=None, say=lambda _m: None) + step = _step("self_consistency") + obs = _obs("sc", ["c0-0", "c1-0"]) + obs.cost = {"wall_sec": 4.0, "calls": {"generate": 10}} + run.evidence[step.name] = StepEvidence(step, [obs]) + ledger.cost({"kind": "action", "wall_sec": 4.0}) + assert run.estimate_sec(step, 4) == 8.0 + assert "exceeds the 6.0s left" in run.over_budget(8.0) + assert run.over_budget(5.0) is None + ledger.cost({"kind": "action", "wall_sec": 7.0}) + assert "spent" in run.over_budget(None) + + +# -- the reuse declarations hold -------------------------------------------------------- + +#: Steps declared ``reuse`` whose rows these tests show do not depend on the batch. +#: ``per_case`` steps run once per case by construction. +_CHECKED = {"answer_extraction_audit", "termination_audit", "modality_ablation", "prompt_contrast", + "attention_knockout", "attention_temperature", "attention_sensitivity", "gradcam", + "generic_attention", "layer_contrast", "format_sensitivity"} + + +def test_every_reuse_step_is_covered_by_a_decomposability_check(): + steps = [*BATTERY, *candidate_steps(LAYERS)] + assert {s.analyzer for s in steps if s.reuse and not s.per_case} <= _CHECKED + for s in steps: + if not s.reuse: + assert s.reuse_note, s.name + + +def _rows(result): + from evalrx.eval_agent.probing.actions import canonical + + findings = canonical(result.findings or {}) + rows = {str(r["sample_id"]): r for r in findings.get("per_case") or []} + outputs = ((result.artifacts or {}).get("outputs") or {}) if hasattr(result, "artifacts") else {} + return rows, canonical(outputs) + + +def _split_equals_whole(analyzer, model, batch, cut=3): + whole_rows, whole_out = _rows(analyzer.run(model, batch)) + a_rows, a_out = _rows(analyzer.run(model, CaseBatch(list(batch)[:cut]))) + b_rows, b_out = _rows(analyzer.run(model, CaseBatch(list(batch)[cut:]))) + merged_out = {s: {**a_out.get(s, {}), **b_out.get(s, {})} for s in set(a_out) | set(b_out)} + return whole_rows == {**a_rows, **b_rows} and whole_out == merged_out, whole_rows + + +@pytest.fixture() +def vlm_cases(): + pytest.importorskip("torch") + pytest.importorskip("transformers") + from tests.tiny_whitebox import image + + layout = [("cat", "Yes"), ("dog", "No"), ("cat", "No"), ("dog", "Yes"), + ("cat", "Yes"), ("dog", "No"), ("cat", "No"), ("dog", "Yes")] + imgs = [image(i) for i in range(4)] + out = [] + for i, (obj, gold) in enumerate(layout): + fail = i in (1, 5) + out.append(FailureCase( + id=f"pope-{i}", inputs=Inputs(prompt=f"Is there a {obj} in the image?", image=imgs[i // 2]), + expected=gold, observed="Yes" if fail or gold == "Yes" else "No", + label=Label.FAIL if fail else Label.PASS, metadata={"gold": gold, "finish_reason": "stop"})) + return CaseBatch(out) + + +@pytest.mark.parametrize("name, config", [ + ("attention_knockout", {"target": "gold"}), + ("attention_temperature", {"target": "gold"}), + ("attention_sensitivity", {"target": "gold"}), + ("gradcam", {"target": "gold"}), + ("generic_attention", {"target": "gold"}), + ("layer_contrast", {}), +]) +def test_white_box_reuse_steps_give_the_same_rows_whatever_shares_the_batch(vlm_cases, name, config): + from evalrx.core.registry import registry + from tests.tiny_whitebox import TinyVLM + + model = TinyVLM("qwen2_5_vl") + same, rows = _split_equals_whole(registry.analyzers.get(name)(**config), model, vlm_cases) + assert rows and same + + +def test_behavioural_reuse_steps_give_the_same_rows_whatever_shares_the_batch(): + from evalrx.core.registry import registry + + cases, table = _pope_like(6) + model = _Table(table) + for name, config in [("answer_extraction_audit", {"reask": False}), ("answer_extraction_audit", {"reask": True}), + ("termination_audit", {"continue_non_clean": True}), + ("modality_ablation", {"mode": "swap", "donor_rule": "counterfactual", "donor_pool": cases}), + ("modality_ablation", {"mode": "drop"}), + ("prompt_contrast", {"strategies": {"baseline": "{prompt}", "x": "Q: {prompt}"}})]: + same, rows = _split_equals_whole(registry.analyzers.get(name)(**config), model, cases, cut=5) + assert rows and same, (name, config) + + mc = CaseBatch([FailureCase(id=f"m{i}", inputs=Inputs(prompt=f"Which {i}?\nA. cat\nB. dog\nC. cup"), + expected="A", observed="A", label=Label.PASS) for i in range(5)]) + + class _Letters(_Table): + def generate(self, inputs, **kwargs): + return "B" if "B. cat" in str(inputs.prompt) else "A" + + same, rows = _split_equals_whole(registry.analyzers.get("format_sensitivity")(), _Letters({}), mc, cut=2) + assert rows and same From 0de2a87b4f8327ec87ea0cb6b7cbfc13809d5bf1 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:42:38 -0700 Subject: [PATCH 04/26] triage MVP-3a: scored scheduler; prompt_contrast per-call generation Scored scheduler (--triage-scheduler scored, probing/scoring.py): one decision at a time over every feasible candidate (each active route's open or stale layer, the expansion, the deferred battery steps), ranked by U = q*[D + T + C - R]+ / (c + eps). D is 0 until competing explanations with predictions exist; T rewards extending a reuse step to new cases (1) or an expansion that may close a recorded gap (0.5); C is the coverage gap over layer x gold-stratum units the action removes; R filters existing observations; q is smoothed success over distinct observations; c is the step's own cost per case, else measured per-call rates (USD when every action is priced, else wall seconds). Every 10th decision explores with a seed; nothing above the 0.01 gain floor stops the run. No batch-dependent candidate is taken while an expansion can still follow. Each decision records every candidate's components; the report is triage_report.scored.*, and probing/compare.py compares two reports on first-execution evidence cost, controller time and coverage. Adoption of earlier chunks is limited to chunks inside the target. --triage-budget-usd caps USD on priced models. On Qwen3.5-0.8B POPE the scored run reaches the rules' follow-ups, readings and call counts exactly, with twice the decisions: with D = 0 it only reorders. prompt_contrast takes gen_kwargs for every re-ask; describe-first asks for max_new_tokens=256 where the backend honours per-call settings and is gated on the host's cap where it does not. Its follow-up readings add extra_words_* / complied_*, and the report warns when most route cases did not describe first (Qwen3.5-0.8B 0/17, gemini-3.1-flash-lite 15/15). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 47 +++ docs/agentic_benchmark.md | 4 +- .../analyzers/perturbation/prompt_contrast.py | 12 +- evalrx/benchmark/run.py | 5 + evalrx/benchmark/runner.py | 7 +- evalrx/eval_agent/probing/compare.py | 59 +++ evalrx/eval_agent/probing/controller.py | 383 +++++++++++++++--- evalrx/eval_agent/probing/ledger.py | 6 +- evalrx/eval_agent/probing/rules.py | 36 +- evalrx/eval_agent/probing/scoring.py | 236 +++++++++++ evalrx/eval_agent/probing/triage.py | 22 +- tests/test_analyzers/test_prompt_contrast.py | 19 + tests/test_eval_agent/test_probing_mvp0.py | 3 +- tests/test_eval_agent/test_probing_mvp2.py | 35 +- tests/test_eval_agent/test_probing_mvp3.py | 132 ++++++ 15 files changed, 918 insertions(+), 88 deletions(-) create mode 100644 evalrx/eval_agent/probing/compare.py create mode 100644 evalrx/eval_agent/probing/scoring.py create mode 100644 tests/test_eval_agent/test_probing_mvp3.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 60668894..e44b6385 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,53 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — triage scored scheduler (MVP-3, first part) + +`--triage-scheduler scored` replaces the rules' rounds with one decision at a +time: every feasible candidate (each active route's open or stale layer, the +expansion, the deferred battery steps) gets +`U = q·[D + T + C − R]₊ / (c + ε)` (`probing/scoring.py`, version +`mvp3-score-1`) and the highest wins, ties going to the soft order; taking a +later layer first is recorded as a soft-order exception. D is 0 until +competing explanations with predictions exist; T is 1 for extending a +`reuse` step to a route's new cases or a contradiction, 0.5 for an expansion +that may close a recorded gap; C is the coverage gap over `layer × gold +stratum` units the action removes; R filters an observation that already +exists; q is `(successes+1)/(attempts+2)` over the analyzer's distinct +observations (unsupported is not an attempt); c is the step's own cost per +case, else measured per-call rates, on the primary axis (USD when every +action is priced, else wall seconds). Every 10th decision explores with a +seed; no candidate above the gain floor (0.01) stops the run. While an +expansion can still follow, no batch-dependent candidate is taken (its reading +would be superseded; its layer waits rather than falling back). On +Qwen3.5-0.8B POPE it reaches the rules' follow-ups, readings and call counts +exactly, with twice the decisions (each expansion makes it extend what it ran +on the smaller sample): with D = 0 it only reorders. Decisions read +only the scheduler's own evidence and price candidates as if fresh, so a +shared ledger saves compute without changing choices; the report +(`triage_report.scored.*`) lists every candidate's components per decision. +Both schedulers' reports now carry `cost.evidence` (the first-execution cost +of every observation read), `cost.controller_sec` and `coverage`; +`probing/compare.py` compares two reports. `--triage-budget-usd` caps USD the +way `--triage-budget-sec` caps seconds. Adoption of earlier chunks is limited +to chunks inside the target, so no case enters the evidence without a +decision that asked for it. + +### Added — `prompt_contrast(gen_kwargs=...)`; describe-first gets its own output room + +`prompt_contrast` takes per-call generation settings for every re-ask +(baseline included); without them it behaves as before (Qwen3.5-0.8B: every +reworded and threshold answer identical to the earlier run). The triage's +describe-first candidates ask for `max_new_tokens=256`, so they run under +POPE's 16-token cap where the backend honours per-call settings; on a +backend that drops them (OpenAI-compatible endpoint) the step runs without +them and is gated on the host's cap. Follow-up readings of a strategy that +asks for text before the answer add `extra_words_*` and `complied_*` (at +least 5 more words than the re-asked question), and the report warns when +most route cases did not comply: Qwen3.5-0.8B answers "No" straight away +(0/17 complied), so its unchanged answers do not test the question; +gemini-3.1-flash-lite describes first (15/15, about 21 extra words). + ### Added — triage expansion and rule-chosen follow-ups (MVP-2) `--m1-policy triage_active` (policy `mvp2-0`) keeps the nine-step battery and diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index a658864a..1371cf5c 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -33,7 +33,9 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Steps whose per-case rows do not depend on the batch (the audits, the swap with donors from the whole partition, the knockout, re-sampling, the wrappers) run on the new cases alone and keep the old rows. `embed_lens` and `patchscope` infer the question words from the batch, but no route reads them, so they wait until the sample stops growing and run once on the whole of it. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). -**Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls: descriptive, no test, no mechanism named. +**Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. + +**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — each active route's open or stale layer, the expansion, and the batch-dependent battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for extending a step to a route's new cases or resolving a contradiction and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist; q is the analyzer's smoothed success rate in this run; c is the estimated cost on the primary axis (USD when every action is priced, else seconds). Every 10th decision explores with a seed, and the run stops when no candidate's gain reaches 0.01. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. diff --git a/evalrx/analyzers/perturbation/prompt_contrast.py b/evalrx/analyzers/perturbation/prompt_contrast.py index f0340485..d8156c63 100755 --- a/evalrx/analyzers/perturbation/prompt_contrast.py +++ b/evalrx/analyzers/perturbation/prompt_contrast.py @@ -128,6 +128,11 @@ class PromptContrastAnalyzer(Analyzer): to a word-boundary rubric scorer over ``case.expected`` (dict ``all_of/any_of/none_of`` or plain string). max_cases: Cap on cases (cost = ``len(strategies)`` generations each); 0 (the default) = every case. + gen_kwargs: per-call generation settings for every re-ask, baseline + included (e.g. a larger ``max_new_tokens`` for a strategy that + asks for a description before the answer); ``None`` (the + default) = the model's own settings. A backend that drops + per-call settings (an OpenAI-compatible endpoint) ignores them. """ name = "prompt_contrast" @@ -163,11 +168,13 @@ def __init__( # so a small cap leaves too few discordant pairs for M4 to clear the # e-value bar. 128 covers typical mined fail counts plus controls. max_cases: int = 0, + gen_kwargs: "dict[str, Any] | None" = None, ) -> None: strategies = dict(strategies) if strategies else dict(_DEFAULT_STRATEGIES) if "baseline" not in strategies: strategies = {"baseline": "{prompt}", **strategies} - super().__init__(strategies=strategies, score_fn=score_fn, max_cases=max_cases) + super().__init__(strategies=strategies, score_fn=score_fn, max_cases=max_cases, + gen_kwargs=dict(gen_kwargs) if gen_kwargs else None) def _run(self, model: "Model", cases: "CaseBatch") -> Result: score = self.score_fn or _default_score @@ -182,6 +189,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: # mixes both, which the McNemar (flips) and the no-free-lunch check # (breaks of correct answers) each need. selected = cases.stratified_head(self.max_cases) + gen_kwargs = dict(self.gen_kwargs or {}) for case in selected: prompt = str(getattr(case.inputs, "prompt", "")) for strat, template in self.strategies.items(): @@ -192,7 +200,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: # any modality set that includes text prompts) — a fresh # Inputs(image=...) silently dropped .audio, so the re-ask # would have answered without hearing the clip. - out = str(model.generate(dataclasses.replace(case.inputs, prompt=rewritten))) + out = str(model.generate(dataclasses.replace(case.inputs, prompt=rewritten), **gen_kwargs)) verdict = score(case, out) answers[strat][case.id] = out[:200] outputs[strat][case.id] = out diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index b281a199..cb367733 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -158,6 +158,11 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "(doubling from --triage-n-fail; a value at or below it disables expansion)") p.add_argument("--triage-max-actions", type=int, default=12, help="triage_active: decisions after the battery (expansions + route follow-ups)") + p.add_argument("--triage-scheduler", choices=["rules", "scored"], default="rules", + help="triage_active: rules = MVP-2 fixed rounds over the routes' layers; scored = MVP-3 " + "value per cost, U = q*[D+T+C-R]+/(c+eps) (report: triage_report.scored.*)") + p.add_argument("--triage-budget-usd", type=float, default=0.0, + help="triage_active: USD cap on executed actions on priced API models (0 = none)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index a5571757..58085907 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -422,6 +422,8 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "n_cases": baseline["n"], **{k: baseline[k] for k in ("api_usage", "usd") if k in baseline}}, price_fn=_price_fn(spec), + per_call_generation=sampling is not None, + scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "confirm_visible_to_controller": False}, @@ -434,10 +436,11 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "m1_policy": "triage_active", "triage": report["summary"], "triage_steps": [{k: s.get(k) for k in ("kind", "key", "analyzer", "status", "reused", "n_cases")} for s in report["executions"]], - "triage_stop": report["stop"], + "triage_stop": report["stop"], "triage_scheduler": report["scheduler"], } (run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n", encoding="utf-8") - print(f"Done (triage). {run_dir / 'probing' / 'triage_report.md'}") + name = "triage_report" if args.triage_scheduler == "rules" else f"triage_report.{args.triage_scheduler}" + print(f"Done (triage). {run_dir / 'probing' / (name + '.md')}") return 0 diff --git a/evalrx/eval_agent/probing/compare.py b/evalrx/eval_agent/probing/compare.py new file mode 100644 index 00000000..f48abae5 --- /dev/null +++ b/evalrx/eval_agent/probing/compare.py @@ -0,0 +1,59 @@ +"""Two schedulers' runs side by side: what each chose, in what order, at what evidence cost. + +Both runs may share one ledger, so a scheduler that runs second reads most +observations back. Cost is therefore compared on the evidence each report +was built from, at the cost the observation had when it was first executed +(``cost.evidence``), not on what the second invocation happened to spend. +""" + +from __future__ import annotations + +from typing import Any + + +def _followed(report: dict[str, Any]) -> list[tuple[str, str, str]]: + return [(d.get("route") or "-", d.get("rule_id") or "-", d.get("key") or d["kind"]) + for d in report["decisions"] if d["kind"] in ("expand", "follow_up", "extend", "battery")] + + +def compare(baseline: dict[str, Any], other: dict[str, Any]) -> dict[str, Any]: + """Selection and cost differences of *other* against the *baseline* run (both triage reports).""" + a, b = _followed(baseline), _followed(other) + def open_units(r: dict[str, Any]) -> list[dict[str, Any]]: # units some tool could still close here + return [u for u in (r.get("coverage") or {}).values() if u.get("layer_state") != "exhausted"] + + gap = {name: sum(u["gap"] for u in open_units(r)) for name, r in (("baseline", baseline), ("other", other))} + units = {name: len(open_units(r)) for name, r in (("baseline", baseline), ("other", other))} + return { + "schedulers": [baseline.get("scheduler", "rules"), other.get("scheduler", "rules")], + "same_sample": baseline["sample"]["case_ids"] == other["sample"]["case_ids"], + "actions": {"baseline": a, "other": b}, + "only_baseline": [x for x in a if x not in b], + "only_other": [x for x in b if x not in a], + "same_order": a == b, + "evidence_cost": {"baseline": (baseline.get("cost") or {}).get("evidence"), + "other": (other.get("cost") or {}).get("evidence")}, + "controller_sec": {"baseline": (baseline.get("cost") or {}).get("controller_sec"), + "other": (other.get("cost") or {}).get("controller_sec")}, + "coverage_gap": gap, "coverage_units": units, + "stop": {"baseline": baseline["stop"], "other": other["stop"]}, + } + + +def markdown(diff: dict[str, Any]) -> str: + a_name, b_name = diff["schedulers"] + lines = [f"# Scheduler comparison: {a_name} vs {b_name}", "", + f"Same final sample: {diff['same_sample']}. Same actions in the same order: {diff['same_order']}.", "", + f"| | {a_name} | {b_name} |", "|---|---|---|"] + rows = max(len(diff["actions"]["baseline"]), len(diff["actions"]["other"])) + for i in range(rows): + cells = [":".join(x[i]) if i < len(x) else "" for x in (diff["actions"]["baseline"], diff["actions"]["other"])] + lines.append(f"| {i} | {cells[0]} | {cells[1]} |") + ev = diff["evidence_cost"] + lines += ["", f"Evidence cost (first execution of every observation read): {a_name} {ev['baseline']}; " + f"{b_name} {ev['other']}.", + f"Controller time outside the actions: {diff['controller_sec']}.", + f"Coverage gap left on units some tool can close here (sum): {diff['coverage_gap']} of " + f"{diff['coverage_units']} units.", + f"Stop: {diff['stop']}.", ""] + return "\n".join(lines) diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 663dd57c..43689f66 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -53,6 +53,7 @@ import inspect import json import os +import time from collections import Counter from functools import partial from pathlib import Path @@ -65,8 +66,10 @@ from evalrx.eval_agent.probing.ledger import Ledger from evalrx.eval_agent.probing.rules import ( LAYERS, + ROUTE_ORDER, RULES_VERSION, Layer, + Proposal, active_routes, candidate_steps, expansion_gaps, @@ -77,12 +80,27 @@ route_states, ) from evalrx.eval_agent.probing.sampler import matched_sample, rank +from evalrx.eval_agent.probing.scoring import ( + SCORING_VERSION, + Scored, + Weights, + availability, + axis_of, + choose, + coverage_gain, + coverage_units, + estimate_cost, + method_rates, + public_units, + value, +) from evalrx.eval_agent.probing.triage import ROUTE_STEPS, follow_up_reading, summarize, triage_cases if TYPE_CHECKING: from evalrx.core.case import CaseBatch POLICY_VERSION = "mvp2-0" +SCHEDULERS = ("rules", "scored") #: Neutral wrappers around the question, kept verbatim (with its output #: contract): the meaning cannot change, only the surface. A wrapper whose @@ -175,8 +193,10 @@ class _Run: def __init__(self, model: Any, explore: "CaseBatch", ledger: Ledger, *, context: dict[str, Any], extras: dict[str, dict[str, Any]], task_kind: "str | None", budget_sec: float, - price_fn: Any, run_logger: Any, say: Callable[[str], None]) -> None: + price_fn: Any, run_logger: Any, say: Callable[[str], None], + per_call_generation: bool = True, budget_usd: float = 0.0) -> None: self.model, self.ledger, self.context, self.extras = model, ledger, context, extras + self.per_call_generation, self.budget_usd = per_call_generation, budget_usd self.task_kind, self.budget_sec, self.price_fn, self.run_logger, self.say = ( task_kind, budget_sec, price_fn, run_logger, say) self.by_id = {str(c.id): c for c in explore} @@ -191,7 +211,17 @@ def batch(self, ids: "list[str]") -> "CaseBatch": return CaseBatch([self.by_id[i] for i in sorted(set(ids), key=self.order.__getitem__)]) def config(self, step: PlanStep) -> dict[str, Any]: - return {**step.config, **self.extras.get(step.analyzer, {})} + """The constructor arguments the step actually runs with: on a backend that drops + per-call generation settings it gets none, so its identity says what ran.""" + config = {**step.config, **self.extras.get(step.analyzer, {})} + if not self.per_call_generation: + config.pop("gen_kwargs", None) + return config + + def output_cap(self, step: PlanStep) -> "int | None": + """The output cap *step* runs under: its own per-call setting, else the host's.""" + asked = (self.config(step).get("gen_kwargs") or {}).get("max_new_tokens") + return int(asked) if asked is not None else output_cap(self.context.get("model") or {}) def build(self, step: PlanStep) -> Any: from evalrx.core.registry import registry @@ -202,7 +232,7 @@ def gate(self, step: PlanStep, ids: "list[str]") -> "tuple[str, str] | None": """Why *step* cannot run on *ids* here — ``(status, reason)`` — before anything is spent.""" if step.task_kinds and self.task_kind not in step.task_kinds: return "not_applicable", f"for task kinds {list(step.task_kinds)}; this task is {self.task_kind!r}" - cap = output_cap(self.context.get("model") or {}) + cap = self.output_cap(step) if step.min_output_tokens and cap is not None and cap < step.min_output_tokens: return "not_applicable", (f"the output cap of {cap} tokens is below the {step.min_output_tokens} " f"this step needs ({step.caveat or 'text before the answer'})") @@ -218,14 +248,27 @@ def estimate_sec(self, step: PlanStep, n_cases: int) -> "float | None": per_case = ev.sec_per_case() if ev is not None else None return round(per_case * n_cases, 1) if per_case is not None else None - def over_budget(self, estimate: "float | None") -> "str | None": - if self.budget_sec <= 0: - return None - spent = self.ledger.spent_wall_sec() - if spent >= self.budget_sec: - return f"wall-clock budget {self.budget_sec}s spent" - if estimate is not None and spent + estimate > self.budget_sec: - return f"estimated {estimate}s exceeds the {round(self.budget_sec - spent, 1)}s left" + def estimate_usd(self, step: PlanStep, n_cases: int) -> "float | None": + ev = self.evidence.get(step.name) + rows = [(float(o.cost.get("usd") or 0.0), len(o.planned_ids)) for o in (ev.chunks if ev else []) + if o.cost.get("usd") is not None and o.planned_ids] + n = sum(k for _, k in rows) + return round(sum(v for v, _ in rows) / n * n_cases, 6) if n else None + + def over_budget(self, estimate: "float | None", estimate_usd: "float | None" = None) -> "str | None": + """Why an action with these estimates may not start (``None`` = it may).""" + if self.budget_sec > 0: + spent = self.ledger.spent("wall_sec") + if spent >= self.budget_sec: + return f"wall-clock budget {self.budget_sec}s spent" + if estimate is not None and spent + estimate > self.budget_sec: + return f"estimated {estimate}s exceeds the {round(self.budget_sec - spent, 1)}s left" + if self.budget_usd > 0: + spent = self.ledger.spent("usd") + if spent >= self.budget_usd: + return f"USD budget {self.budget_usd} spent" + if estimate_usd is not None and spent + estimate_usd > self.budget_usd: + return f"estimated USD {estimate_usd} exceeds the {round(self.budget_usd - spent, 6)} left" return None def _identity(self, step: PlanStep) -> tuple[Any, str, dict[str, Any], str]: @@ -261,13 +304,15 @@ def _log(self, record: dict[str, Any]) -> None: def _adopt(self, ev: StepEvidence, step_id: str, target: "list[str]", base: dict[str, Any]) -> "dict[str, Any] | None": """Take up chunks of the same step identity measured before (by this run or an earlier - one) on cases of *target* that no chunk covers yet; the last such execution record.""" + one) inside *target*, on cases no chunk covers yet; the last such execution record.""" record = None known = {o.action_id for o in ev.chunks} wanted = set(target) for obs in self.ledger.chunks_for(step_id): ids = set(obs.planned_ids) - if obs.action_id in known or not ids & wanted or ids & ev.covered(): + # only chunks inside the target: one that also covers other cases would bring + # evidence on them that no decision of this run asked for + if obs.action_id in known or not ids or not ids <= wanted or ids & ev.covered(): continue ev.add(obs) row = {**base, "n_cases": len(ids & wanted), "action_id": obs.action_id, "step_id": step_id} @@ -335,7 +380,7 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: return record estimate = self.estimate_sec(step, len(cases)) - why = None if budget_checked else self.over_budget(estimate) + why = None if budget_checked else self.over_budget(estimate, self.estimate_usd(step, len(cases))) if why is not None: self.ledger.trace({**base, "event": "skipped", "status": SKIPPED, "reason": why}) self.blocked[step.name] = why @@ -401,6 +446,13 @@ def run_triage( budget_sec: float = 0.0, stage0_cost: "dict[str, Any] | None" = None, partition: "dict[str, Any] | None" = None, + per_call_generation: bool = True, + scheduler: str = "rules", + weights: "Weights | None" = None, + explore_every: int = 10, + min_gain: float = 0.01, + min_cover: int = 8, + budget_usd: float = 0.0, run_logger: Any = None, progress: "Callable[[str], None] | None" = print, ) -> dict[str, Any]: @@ -440,8 +492,25 @@ def run_triage( left is skipped. stage0_cost: the shared baseline cost, logged once and kept separate. partition: how EXPLORE/CONFIRM were split (recorded, not used). + per_call_generation: the backend honours per-call generation settings (an + OpenAI-compatible endpoint drops them): when it does + not, steps run without their ``gen_kwargs`` and are gated + on the host's output cap. + scheduler: ``"rules"`` (MVP-2: rounds over the routes' soft layer order) + or ``"scored"`` (MVP-3: the candidate with the highest + U = q·[D+T+C−R]₊/(c+ε), see :mod:`.scoring`). Both share + the ledger; the scored report is ``triage_report.scored``. + weights, explore_every, min_gain, min_cover: the scored scheduler's weights, + exploration period (every k-th decision), value floor + and per-unit coverage target. + budget_usd: USD cap on executed actions (0 = none), checked like + ``budget_sec`` with the step's earlier USD per case. run_logger: optional RunLoggerV2 for per-call model logs. """ + if scheduler not in SCHEDULERS: + raise ValueError(f"scheduler must be one of {SCHEDULERS}; got {scheduler!r}") + weights = weights or Weights() + started = time.monotonic() say = progress or (lambda _msg: None) out = Path(out_dir) ledger = Ledger(out) @@ -452,7 +521,7 @@ def run_triage( n_available = sum(1 for c in explore if getattr(getattr(c, "label", None), "value", None) == "fail") run = _Run(model, explore, ledger, context={"policy": POLICY_VERSION, "model": model_identity}, extras=extras, task_kind=task_kind, budget_sec=budget_sec, price_fn=price_fn, - run_logger=run_logger, say=say) + run_logger=run_logger, say=say, per_call_generation=per_call_generation, budget_usd=budget_usd) rank_of = partial(rank, seed) triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn) @@ -497,12 +566,180 @@ def settle() -> None: def decide(record: dict[str, Any]) -> None: record = {"event": "decision", "n": len(decisions), "round": round_no, "revision": revision, - "rules_version": RULES_VERSION, **record} + "scheduler": scheduler, "rules_version": RULES_VERSION, **record} ledger.trace(record) decisions.append(record) - def n_actions() -> int: # decisions that spend: expansions and follow-ups - return sum(1 for d in decisions if d["kind"] in ("expand", "follow_up")) + def n_actions() -> int: # decisions that spend: expansions, follow-ups, scheduled battery steps + return sum(1 for d in decisions if d["kind"] in ("expand", "follow_up", "extend", "battery")) + + def expansion_plan() -> "tuple[Any, Any, list[str], float | None] | None": + """The next nested sample, its new cases and the battery's estimated seconds; ``None`` at the cap.""" + size = next_size(len(draw.fail_ids), max_fail, n_available) + if size is None: + return None + bigger, bigger_draw = matched_sample(explore, size, seed=seed, stratum=stratum) + if not (set(draw.fail_ids) <= set(bigger_draw.fail_ids) and set(draw.pass_ids) <= set(bigger_draw.pass_ids)): + raise RuntimeError("nested sampler returned a draw that does not contain the previous one") + new_ids = [cid for cid in bigger_draw.case_ids if cid not in set(draw.case_ids)] + estimates = [run.estimate_sec(s, len(new_ids) if s.reuse else len(bigger_draw.case_ids)) + for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] + estimate = round(sum(e for e in estimates if e is not None), 1) if any( + e is not None for e in estimates) else None + return bigger, bigger_draw, new_ids, estimate + + def not_possible(gaps: list[dict[str, Any]]) -> dict[str, Any]: + return {"state": "not_possible", "gaps": gaps, + "reason": (f"the sample has the cap of {max_fail} FAIL cases" if len(draw.fail_ids) >= max_fail + else f"EXPLORE has no FAIL case beyond the {n_available} drawn")} + + def do_expand(plan: Any, gaps: list[dict[str, Any]], extra: dict[str, Any]) -> None: + nonlocal sample, draw, revision + bigger, bigger_draw, new_ids, estimate = plan + decide({"kind": "expand", "rule_id": "E1", "from_fail": len(draw.fail_ids), + "to_fail": len(bigger_draw.fail_ids), "n_new_cases": len(new_ids), "gaps": gaps, + "estimate_sec": estimate, **extra}) + say(f"[triage] expand {len(draw.fail_ids)} -> {len(bigger_draw.fail_ids)} FAIL " + f"({len(new_ids)} new cases; gaps: {[g['gap'] for g in gaps]})") + sample, draw = bigger, bigger_draw + draws.append(draw) + revision += 1 + manifest() + ledger.trace({"event": "revision", "revision": revision, "n_fail": len(draw.fail_ids), + "n_pass": len(draw.pass_ids), "n_new_cases": len(new_ids), "scheduler": scheduler}) + for step in immediate: + run.run_step(step, list(draw.case_ids), kind="expansion", revision=revision, rule_id="E1", + budget_checked=True) + + by_rule = {x.rule_id: x for x in layers} + + def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] + ) -> tuple[list[Scored], list[dict[str, Any]], str]: + """Every feasible candidate with its value, what the budget filtered out, and the cost axis.""" + nonlocal expansion_note + sample_ids = list(draw.case_ids) + # A batch-dependent step's reading is superseded by any later expansion, and no + # route reads it: while an expansion can still follow, running it is wasted. Its + # layer waits for it (a battery step) rather than falling back to another tool. + growing = bool(gaps) and expansion_note is None and \ + next_size(len(draw.fail_ids), max_fail, n_available) is not None + pending = {s.name: (s, sample_ids) for s in deferred + if s.name not in run.evidence or run.evidence[s.name].todo(sample_ids)} + rows = [r for r in active_routes(records, min_route_fail) if r["active"]] + # Decisions read only this scheduler's own evidence and price every candidate as if + # it ran fresh: chunks in the ledger (an earlier invocation, the other scheduler) + # save compute when the chosen step runs, never change what is chosen. + states = {r["route"]: route_states(r["route"], records, run.evidence, run.gate, rank_of, layers=layers, + blocked=run.blocked, pending=pending) for r in rows} + units = coverage_units(states, records, run.evidence, layers, min_cover=min_cover) + axis = axis_of(run.evidence) + rates, wall_rates = method_rates(run.evidence, axis), method_rates(run.evidence, "wall_sec") + by_id = {r["case_id"]: r for r in records} + pool: list[Scored] = [] + filtered: list[dict[str, Any]] = [] + for route, sts in states.items(): + for li, st in enumerate(sts): + if st["state"] not in ("open", "extend"): + continue + layer, step = by_rule[st["rule_id"]], st["step"] + if growing and not step.reuse: + filtered.append({"key": step.name, "route": route, "rule_id": layer.rule_id, + "reason": "batch-dependent: a pending expansion would supersede it"}) + continue + target = st["target"] if st.get("battery") else [*st["_fail_ids"], *st["_control_ids"]] + ev = run.evidence.get(step.name) + todo = ev.todo(target) if ev is not None else list(target) + if not todo: # the same observation exists: R = 1, not a candidate + continue + fail_new = set(todo) & set(st["_fail_ids"]) + C, touched = coverage_gain(layer.rule_id, fail_new, units) + T, gap_ids = 0.0, [] + if st["state"] == "extend" and step.reuse: + T, gap_ids = 1.0, [f"stale:{layer.rule_id}:{step.name}"] + elif layer.route == "H" and any(by_id[c]["H"]["disagreements"] for c in fail_new): + T, gap_ids = 1.0, [f"contradiction:{layer.rule_id}"] + kind = "battery" if st.get("battery") else ("extend" if st["state"] == "extend" else "follow_up") + cand = Scored(kind=kind, key=step.name, route=route, rule_id=layer.rule_id, + order=(ROUTE_ORDER.index(route), li), n_new_cases=len(todo), T=T, C=C, + q=availability(step.analyzer, run.evidence), + cost=estimate_cost(step, len(todo), run.evidence, axis, rates), + gaps=gap_ids, units=touched, + payload=Proposal(layer=layer, step=step, kind=st["state"], fail_ids=st["_fail_ids"], + control_ids=st["_control_ids"], todo=todo, tried=st.get("tried", []), + before=[], target_override=st.get("target"))) + why = run.over_budget(estimate_cost(step, len(todo), run.evidence, "wall_sec", wall_rates), + run.estimate_usd(step, len(todo))) + if why is not None: + filtered.append({"key": step.name, "route": route, "rule_id": layer.rule_id, "reason": why}) + continue + pool.append(value(cand, weights, axis)) + if gaps and expansion_note is None: + plan = expansion_plan() + if plan is None: + expansion_note = not_possible(gaps) + decide({"kind": "expand_not_possible", "rule_id": "E1", **expansion_note}) + else: + steps = [s for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] + qs = [availability(s.analyzer, run.evidence) for s in steps + if any(o.status != "unsupported" for o in run.evidence[s.name].chunks)] + costs = [estimate_cost(s, len(plan[2]), run.evidence, axis, rates) for s in steps] + cand = Scored(kind="expand", key="expand", rule_id="E1", order=(-1, 0), n_new_cases=len(plan[2]), + T=0.5, q=sum(qs) / len(qs) if qs else 0.5, + cost=sum(c for c in costs if c is not None) if any(c is not None for c in costs) else None, + gaps=[f"{g['gap']}:{g.get('route') or g.get('stratum')}" for g in gaps], payload=plan) + why = run.over_budget(plan[3]) + if why is not None: + filtered.append({"key": "expand", "rule_id": "E1", "reason": why}) + else: + pool.append(value(cand, weights, axis)) + return pool, filtered, axis + + if scheduler == "scored": + while stop is None: + records = triage(sample, run.evidence) + summary = summarize(records) + gaps = expansion_gaps(summary, records, min_cohort=min_cohort) + if not revisions or revisions[-1]["revision"] != revision: + revisions.append(_revision_row(revision, draw, summary, records, gaps)) + pool, filtered, axis = scored_pool(records, gaps) + pick, why = choose(pool, decision_no=n_actions(), seed=seed, explore_every=explore_every, + min_gain=min_gain) + if pick is None: + stop = {"reason": "no_candidate" if why == "none" else "below_threshold", + "detail": ("no feasible candidate" if why == "none" else + f"no candidate reaches the gain floor {min_gain}"), + "best_gain": max((c.gain for c in pool), default=None), "filtered": filtered} + break + if n_actions() >= max_actions: + stop = {"reason": "max_actions", "max_actions": max_actions, + "pending": f"{pick.route}:{pick.rule_id}:{pick.key}"} + break + ranked = sorted(pool, key=lambda c: (-c.U, c.order)) + skipped = [c.rule_id for c in pool if pick.route and c.route == pick.route and c.order < pick.order] + extra = {"choice": why, "scoring_version": SCORING_VERSION, "axis": axis, + "U": round(pick.U, 6), "gain": round(pick.gain, 6), + "candidates": [c.row() for c in ranked], "filtered": filtered, + **({"soft_order_exception": f"{pick.rule_id} taken before open layer(s) {skipped} of route " + f"{pick.route}: higher value"} if skipped else {})} + if pick.kind == "expand": + do_expand(pick.payload, gaps, extra) + round_no += 1 + continue + proposal = pick.payload + decide({"kind": pick.kind, "rule_id": pick.rule_id, "route": pick.route, "key": pick.key, + "analyzer": proposal.step.analyzer, "question": proposal.layer.question, + "n_route_fail": len(proposal.fail_ids), "n_new_cases": pick.n_new_cases, **extra}) + record = run.run_step(proposal.step, proposal.target_ids, + kind="battery" if pick.kind == "battery" else "follow_up", revision=revision, + rule_id=pick.rule_id, route=pick.route) + if record is None: + run.blocked.setdefault(proposal.step.name, "nothing left to run") + elif record["status"] == SKIPPED: + stop = {"reason": "budget", "detail": record.get("reason")} + break + if pick.kind != "battery" and (pick.route, pick.rule_id, pick.key) not in followed: + followed.append((pick.route, pick.rule_id, pick.key)) + round_no += 1 while stop is None: records = triage(sample, run.evidence) @@ -510,45 +747,22 @@ def n_actions() -> int: # decisions that spend: expansions and follow-ups gaps = expansion_gaps(summary, records, min_cohort=min_cohort) if not revisions or revisions[-1]["revision"] != revision: revisions.append(_revision_row(revision, draw, summary, records, gaps)) - size = next_size(len(draw.fail_ids), max_fail, n_available) - if gaps and size is not None and expansion_note is None: - if n_actions() >= max_actions: - stop = {"reason": "max_actions", "max_actions": max_actions, "pending": "expansion"} - break - bigger, bigger_draw = matched_sample(explore, size, seed=seed, stratum=stratum) - if not (set(draw.fail_ids) <= set(bigger_draw.fail_ids) and set(draw.pass_ids) <= set(bigger_draw.pass_ids)): - raise RuntimeError("nested sampler returned a draw that does not contain the previous one") - new_ids = [cid for cid in bigger_draw.case_ids if cid not in set(draw.case_ids)] - estimates = [run.estimate_sec(s, len(new_ids) if s.reuse else len(bigger_draw.case_ids)) - for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] - estimate = round(sum(e for e in estimates if e is not None), 1) if any( - e is not None for e in estimates) else None - why = run.over_budget(estimate) - if why is not None: - expansion_note = {"state": "skipped", "reason": why, "gaps": gaps} - decide({"kind": "expand_skipped", "rule_id": "E1", "reason": why, "gaps": gaps, - "estimate_sec": estimate}) - continue - decide({"kind": "expand", "rule_id": "E1", "from_fail": len(draw.fail_ids), "to_fail": len(bigger_draw.fail_ids), - "n_new_cases": len(new_ids), "gaps": gaps, "estimate_sec": estimate, - "rationale": "an evidence gap a larger nested sample can close; expansion precedes the " - "routes' candidates because it revises the routes"}) - say(f"[triage] expand {len(draw.fail_ids)} -> {len(bigger_draw.fail_ids)} FAIL " - f"({len(new_ids)} new cases; gaps: {[g['gap'] for g in gaps]})") - sample, draw = bigger, bigger_draw - draws.append(draw) - revision += 1 - manifest() - ledger.trace({"event": "revision", "revision": revision, "n_fail": len(draw.fail_ids), - "n_pass": len(draw.pass_ids), "n_new_cases": len(new_ids)}) - for step in immediate: - run.run_step(step, list(draw.case_ids), kind="expansion", revision=revision, rule_id="E1", - budget_checked=True) - continue if gaps and expansion_note is None: - expansion_note = {"state": "not_possible", "gaps": gaps, - "reason": (f"the sample has the cap of {max_fail} FAIL cases" if len(draw.fail_ids) >= max_fail - else f"EXPLORE has no FAIL case beyond the {n_available} drawn")} + plan = expansion_plan() + if plan is not None: + if n_actions() >= max_actions: + stop = {"reason": "max_actions", "max_actions": max_actions, "pending": "expansion"} + break + why = run.over_budget(plan[3]) + if why is not None: + expansion_note = {"state": "skipped", "reason": why, "gaps": gaps} + decide({"kind": "expand_skipped", "rule_id": "E1", "reason": why, "gaps": gaps, + "estimate_sec": plan[3]}) + continue + do_expand(plan, gaps, {"rationale": "an evidence gap a larger nested sample can close; expansion " + "precedes the routes' candidates because it revises the routes"}) + continue + expansion_note = not_possible(gaps) decide({"kind": "expand_not_possible", "rule_id": "E1", **expansion_note}) settle() # the sample is final: the deferred battery steps run once, before any follow-up @@ -597,12 +811,21 @@ def n_actions() -> int: # decisions that spend: expansions and follow-ups settle() # a stop before the sample settled (max_actions with an expansion pending) records = triage(sample, run.evidence) summary = summarize(records) - ledger.trace({"event": "stop", "round": round_no, "revision": revision, **stop}) + ledger.trace({"event": "stop", "round": round_no, "revision": revision, "scheduler": scheduler, **stop}) say(f"[triage] stop: {stop['reason']} after {n_actions()} actions") final_gaps = expansion_gaps(summary, records, min_cohort=min_cohort) n_expansions = sum(1 for d in decisions if d["kind"] == "expand") + final_states = {row["route"]: route_states(row["route"], records, run.evidence, run.gate, rank_of, layers=layers, + blocked=run.blocked) + for row in active_routes(records, min_route_fail) if row["active"]} + coverage = public_units(coverage_units(final_states, records, run.evidence, layers, min_cover=min_cover)) + executed_wall = sum(float((e.get("cost") or {}).get("wall_sec") or 0.0) for e in run.executions + if not e.get("reused")) report = { "policy": POLICY_VERSION, + "scheduler": scheduler, + **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_every": explore_every, + "min_gain": min_gain, "min_cover": min_cover} if scheduler == "scored" else {}), "rules_version": RULES_VERSION, "model": model_identity, "sample": draw.to_dict(), @@ -610,7 +833,7 @@ def n_actions() -> int: # decisions that spend: expansions and follow-ups "n_needs_counterfactual": n_needs_counterfactual, "budget_sec": budget_sec, "task_kind": task_kind, "answer_fn": canonical(answer_fn), "n_fail": n_fail, "max_fail": max_fail, "max_actions": max_actions, "min_route_fail": min_route_fail, - "min_cohort": min_cohort}, + "min_cohort": min_cohort, "per_call_generation": per_call_generation}, "executions": run.executions, "battery": _battery_state(battery, run, draw), "revisions": revisions, @@ -619,15 +842,18 @@ def n_actions() -> int: # decisions that spend: expansions and follow-ups else "pending"})}, "decisions": decisions, "stop": stop, - "cost": _cost_summary(run.executions, stage0_cost), + "cost": {**_cost_summary(run.executions, stage0_cost), "evidence": _evidence_cost(run), + "controller_sec": round(time.monotonic() - started - executed_wall, 3)}, + "coverage": coverage, "summary": summary, "follow_ups": _follow_ups(followed, records, run, sample, rank_of, layers, answer_fn), "routes": _route_report(records, run, rank_of, layers, min_route_fail), "checks": _acceptance(battery, layers, run, draw, ledger), "cases": records, } - _write_json(out / "triage_report.json", report) - (out / "triage_report.md").write_text(_markdown(report), encoding="utf-8") + name = "triage_report" if scheduler == "rules" else f"triage_report.{scheduler}" + _write_json(out / f"{name}.json", report) + (out / f"{name}.md").write_text(_markdown(report), encoding="utf-8") return report @@ -649,6 +875,28 @@ def _revision_row(revision: int, draw: Any, summary: dict[str, Any], records: li } +def _evidence_cost(run: _Run) -> dict[str, Any]: + """What the evidence this report reads cost when each observation was first executed + (a read-back counts at its original cost, once): comparable across schedulers that + share a ledger.""" + seen: dict[str, dict[str, Any]] = {} + for ev in run.evidence.values(): + for obs in ev.chunks: + seen.setdefault(obs.action_id, obs.cost or {}) + costs = list(seen.values()) + calls: dict[str, int] = {} + for c in costs: + for k, v in (c.get("calls") or {}).items(): + calls[k] = calls.get(k, 0) + int(v) + priced = [c for c in costs if c.get("api_usage") is not None] + out: dict[str, Any] = {"n_observations": len(costs), "calls": calls, + "wall_sec": round(sum(float(c.get("wall_sec") or 0.0) for c in costs), 3)} + if priced: + usd = [c.get("usd") for c in priced] + out["usd"] = round(sum(usd), 6) if all(v is not None for v in usd) else None + return out + + def _battery_state(battery: "tuple[PlanStep, ...]", run: _Run, draw: Any) -> list[dict[str, Any]]: """Per battery step: which observations the current sample is read from.""" out = [] @@ -748,7 +996,9 @@ def _acceptance(battery: "tuple[PlanStep, ...]", layers: "tuple[Layer, ...]", ru read = {o.action_id for cid in draw.case_ids if (o := ev.for_case(cid)) is not None} if key in {s.name for s in battery}: one_batch[key] = len(read) == 1 and set(ev.chunks[-1].planned_ids) == set(draw.case_ids) - configs[key] = all(o.params.get(k) == canonical(v) for o in ev.chunks for k, v in ev.step.config.items()) + planned = run.config(ev.step) + configs[key] = all(o.params.get(k) == canonical(planned[k]) for o in ev.chunks + for k in ev.step.config if k in planned) costs = ledger.cost_events() observations = [o for ev in run.evidence.values() for o in ev.chunks] return { @@ -914,6 +1164,11 @@ def _markdown(report: dict[str, Any]) -> str: lines += ["", "| reading | route FAIL mean (n) | PASS control mean (n) |", "|---|---:|---:|"] lines += [f"| {f} | {fail['means'].get(f)} ({fail['n_by_field'].get(f, 0)}) " f"| {ctrl['means'].get(f)} ({ctrl['n_by_field'].get(f, 0)}) |" for f in fields] + low = [f for f in fail["means"] if f.startswith("complied_") and (fail["means"][f] or 0.0) < 0.5] + if low: + lines += ["", f"Warning: on most route cases the model did not add the text {low[0][9:]} asks for " + f"(mean {low[0]} {fail['means'][low[0]]}): an unchanged answer there does not answer " + "the question."] untested = {**fail["untested"], **{f"(controls) {k}": v for k, v in ctrl["untested"].items()}} if untested: lines += ["", f"Untested: {untested}."] @@ -929,7 +1184,7 @@ def _markdown(report: dict[str, Any]) -> str: lines.append(f"| {row['route']} | {row['n_fail']} | {row['active']} | {st['rule_id']} | {st['state']} " f"| {st.get('via') or st.get('key') or '-'} | {passed or '-'} |") lines += ["", "## Checks", ""] - for name, value in report["checks"].items(): - lines.append(f"- `{name}`: {value}") + for name, check in report["checks"].items(): + lines.append(f"- `{name}`: {check}") lines.append("") return "\n".join(lines) diff --git a/evalrx/eval_agent/probing/ledger.py b/evalrx/eval_agent/probing/ledger.py index 0aea7b87..96a6a18f 100644 --- a/evalrx/eval_agent/probing/ledger.py +++ b/evalrx/eval_agent/probing/ledger.py @@ -99,4 +99,8 @@ def attempts(self, action_id: str) -> int: if e.get("event") == "planned" and e.get("action_id") == action_id) def spent_wall_sec(self) -> float: - return sum(float(e.get("wall_sec") or 0.0) for e in self.cost_events() if e.get("kind") == "action") + return self.spent("wall_sec") + + def spent(self, axis: str) -> float: + """Executed actions' spend on *axis* (``wall_sec`` or ``usd``), over every invocation.""" + return sum(float(e.get(axis) or 0.0) for e in self.cost_events() if e.get("kind") == "action") diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index 6d9d2422..c05d566c 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -55,9 +55,15 @@ _FIT_ON_BATCH = "the translators are fit on the batch" +#: Room for a description before the answer, asked per call (the task's own cap +#: is sized for the answer alone: 16 tokens on POPE). +DESCRIBE_OUTPUT_TOKENS = 256 + + def _describe(route: str, question: str) -> PlanStep: # one key for N3 and Sb: the routes share its observations (and its PASS controls) - return PlanStep("prompt_contrast", {"strategies": DESCRIBE_STRATEGIES}, route, question, + return PlanStep("prompt_contrast", {"strategies": DESCRIBE_STRATEGIES, + "gen_kwargs": {"max_new_tokens": DESCRIBE_OUTPUT_TOKENS}}, route, question, key="describe_first", calls_per_case={"generate": 2}, keep_artifacts=("outputs",), caveat="the runtime's output cap must leave room for the description", min_output_tokens=128) @@ -185,20 +191,35 @@ class Proposal: tried: list[dict[str, Any]] before: list[dict[str, Any]] # the earlier layers' states + target_override: "list[str] | None" = None # a battery step runs on the whole sample + @property def target_ids(self) -> list[str]: - return [*self.fail_ids, *self.control_ids] + return list(self.target_override) if self.target_override is not None else [*self.fail_ids, *self.control_ids] Gate = Callable[[PlanStep, list[str]], "tuple[str, str] | None"] def layer_state(layer: Layer, evidence: dict[str, StepEvidence], fail_ids: list[str], target_ids: list[str], - gate: Gate, blocked: "dict[str, str] | None" = None) -> dict[str, Any]: - """``done`` / ``extend`` / ``open`` / ``exhausted`` for *layer* on these cases, with what was passed over.""" + gate: Gate, blocked: "dict[str, str] | None" = None, + pending: "dict[str, tuple[PlanStep, list[str]]] | None" = None) -> dict[str, Any]: + """``done`` / ``extend`` / ``open`` / ``exhausted`` for *layer* on these cases, with what was passed over. + + *pending* names battery steps that serve a layer but have not run on the + current sample yet (with that sample): the layer is open on them first, + unless the model cannot run them (the battery records that when it settles). + """ blocked = blocked or {} if not fail_ids: return {"rule_id": layer.rule_id, "state": "no_cases"} + for name in layer.served_by: + if name in (pending or {}) and gate(pending[name][0], pending[name][1]) is None: + step, sample_ids = pending[name] + ev = evidence.get(name) + return {"rule_id": layer.rule_id, "state": "open", "step": step, "battery": True, + "stale": bool(ev is not None and ev.chunks), "target": list(sample_ids), + "todo": ev.todo(sample_ids) if ev is not None else list(sample_ids), "tried": []} for name in layer.served_by: ev = evidence.get(name) if ev is not None and ev.valid_on(fail_ids): @@ -235,13 +256,14 @@ def layer_state(layer: Layer, evidence: dict[str, StepEvidence], fail_ids: list[ def route_states(route: str, records: list[dict[str, Any]], evidence: dict[str, StepEvidence], gate: Gate, rank: Callable[[str], Any], *, layers: "tuple[Layer, ...]" = LAYERS, - blocked: "dict[str, str] | None" = None) -> list[dict[str, Any]]: + blocked: "dict[str, str] | None" = None, + pending: "dict[str, tuple[PlanStep, list[str]]] | None" = None) -> list[dict[str, Any]]: """Every layer of *route*, in order, with its state on the route's current cases.""" out = [] for layer in (x for x in layers if x.route == route): fail_ids = route_fail_ids(records, route, layer.case_filter) controls, shortfall = matched_controls(records, fail_ids, rank) - state = layer_state(layer, evidence, fail_ids, [*fail_ids, *controls], gate, blocked) + state = layer_state(layer, evidence, fail_ids, [*fail_ids, *controls], gate, blocked, pending) out.append({**state, "question": layer.question, "n_fail": len(fail_ids), "n_controls": len(controls), "control_shortfall": shortfall, "_fail_ids": fail_ids, "_control_ids": controls}) return out @@ -266,7 +288,7 @@ def next_for_route(route: str, records: list[dict[str, Any]], evidence: dict[str def public(state: dict[str, Any]) -> dict[str, Any]: """A layer state without its case lists and step object, for the trace and the report.""" - out = {k: v for k, v in state.items() if not k.startswith("_") and k != "step"} + out = {k: v for k, v in state.items() if not k.startswith("_") and k not in ("step", "target")} if "todo" in out: out["todo"] = len(out["todo"]) if "step" in state: diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/probing/scoring.py new file mode 100644 index 00000000..aa197ea2 --- /dev/null +++ b/evalrx/eval_agent/probing/scoring.py @@ -0,0 +1,236 @@ +"""MVP-3: the value of a candidate action and the scored scheduler's choice. + + U(a | E) = q(a) · [w_D·D(a) + w_T·T(a) + w_C·C(a) − w_R·R(a)]₊ / (c(a) + ε) + +All gains are in [0, 1], ``c`` is on the run's primary budget axis (wall +seconds, or USD when every executed action has a price), and ``ε`` is that +axis' metering floor. The definitions are the design's first executable ones, +written down so a run can show why each action won: + +* **D** (prediction disagreement) needs competing explanations with predictions + per tool; none are proposed yet, so ``D = 0`` and actions earn budget through + T and C (as the design allows with zero or one explanation). +* **T** (evidence gap): 1 completes a recorded gap — a layer done on a smaller + sample whose step only has to run on the route's new cases (a ``reuse`` + step), or a contradiction between two readings of the same check; 0.5 is an + expansion that may close a recorded uncertainty (an uncertain routing + signal, a small S cohort); 0 otherwise. A batch-dependent step that went + stale re-runs on the whole sample: its value is the coverage it restores (C), + not a gap of its own. Every T names the gap ids it serves. +* **C** (coverage): units are ``layer × gold stratum`` for every route with FAIL + cases there. A unit's gap is 1 untested, 0.5 measured on fewer than + ``min(min_cover, route FAIL cases in the stratum)`` cases, else 0. ``C(a)`` is + the gap the action is expected to remove, over the number of units. +* **R** (redundancy): an observation that already exists is filtered out (R = 1); + another tool for a layer that is already answered gets 0.5 (same purpose, + same kind of evidence); otherwise 0. +* **q** (execution availability): ``(successes + 1) / (attempts + 2)`` over the + distinct observations of the analyzer in this run's evidence (a read-back + counts once, so a resumed run decides the same way); ``ok`` and not refused + by its own check is a success, and ``unsupported`` (a gate result, filtered + before scoring) is not an attempt. +* **c** (marginal cost): the step's own earlier cost per case, else the per-call + rate of each method it calls (measured on this run), times the new cases. + ``backward`` has no measured rate until a gradient tool runs; it is priced at + three forwards (a prior, stated here). + +Candidates are each route's open or stale layers (the layer's next candidate in +its fallback order, as in the rules), the expansion, and the batch-dependent +battery steps not yet run on the current sample. No batch-dependent candidate +(battery step or follow-up) is taken while an expansion can still follow: any +expansion supersedes its reading, and no route reads it (the rules' deferral, +for the same reason); its layer waits instead of falling back. Unlike the rules, the +scored scheduler may take a later layer first, and says so when it does. Every +``explore_every``-th decision picks, with a seed, among the feasible candidates +other than the top one. A gain below ``min_gain`` is not worth an action: when +no candidate reaches it, the run stops. +""" + +from __future__ import annotations + +import random +from dataclasses import dataclass, field +from typing import Any + +from evalrx.eval_agent.probing.actions import OK, UNSUPPORTED, PlanStep +from evalrx.eval_agent.probing.evidence import StepEvidence + +SCORING_VERSION = "mvp3-score-1" +BACKWARD_FORWARDS = 3.0 + + +@dataclass(frozen=True) +class Weights: + d: float = 1.0 + t: float = 1.0 + c: float = 1.0 + r: float = 1.0 + + +@dataclass +class Scored: + """One candidate with its value components.""" + + kind: str # "follow_up" | "extend" | "battery" | "expand" + key: str # step key, or "expand" + route: "str | None" = None + rule_id: "str | None" = None + order: tuple[int, int] = (99, 99) # soft order: (route, layer); ties go to the earlier + n_new_cases: int = 0 + D: float = 0.0 + T: float = 0.0 + C: float = 0.0 + R: float = 0.0 + q: float = 0.5 + cost: "float | None" = None + gain: float = 0.0 + U: float = 0.0 + gaps: list[str] = field(default_factory=list) + units: list[str] = field(default_factory=list) + note: str = "" + payload: Any = None # the proposal / expansion plan; not serialised + + def row(self) -> dict[str, Any]: + return {k: (round(v, 6) if isinstance(v, float) else v) for k, v in self.__dict__.items() + if k not in ("payload", "order")} + + +# -- q and c --------------------------------------------------------------------------- + + +def availability(analyzer: str, evidence: dict[str, StepEvidence]) -> float: + """``(successes + 1) / (attempts + 2)`` over the analyzer's distinct observations.""" + seen: dict[str, bool] = {} + for ev in evidence.values(): + if ev.step.analyzer != analyzer: + continue + for obs in ev.chunks: + if obs.status == UNSUPPORTED: # a gate result, filtered before scoring: not an attempt + continue + refused = (obs.fidelity or {}).get("status") == "failed" + seen[obs.action_id] = obs.status == OK and not refused + return (sum(seen.values()) + 1) / (len(seen) + 2) + + +def axis_of(evidence: dict[str, StepEvidence]) -> str: + """``usd`` when every executed observation carries a price, else ``wall_sec``.""" + costs = [o.cost for ev in evidence.values() for o in ev.chunks if (o.cost or {}).get("calls")] + if costs and all(c.get("usd") is not None for c in costs): + return "usd" + return "wall_sec" + + +EPSILON = {"wall_sec": 1.0, "usd": 1e-4} + + +def _amount(cost: dict[str, Any], axis: str) -> float: + return float(cost.get(axis) or 0.0) + + +def method_rates(evidence: dict[str, StepEvidence], axis: str) -> dict[str, float]: + """Cost per call by method, from observations that called one method only.""" + spent: dict[str, float] = {} + calls: dict[str, int] = {} + seen = set() + for ev in evidence.values(): + for obs in ev.chunks: + used = {k: int(v) for k, v in (obs.cost.get("calls") or {}).items() if v} + if obs.action_id in seen or len(used) != 1: + continue + seen.add(obs.action_id) + (method, n), = used.items() + spent[method] = spent.get(method, 0.0) + _amount(obs.cost, axis) + calls[method] = calls.get(method, 0) + n + rates = {m: spent[m] / calls[m] for m in calls if calls[m]} + if "backward" not in rates and "forward" in rates: + rates["backward"] = BACKWARD_FORWARDS * rates["forward"] + if "logprobs" not in rates and "generate" in rates: + rates["logprobs"] = rates["generate"] + return rates + + +def estimate_cost(step: PlanStep, n_cases: int, evidence: dict[str, StepEvidence], axis: str, + rates: dict[str, float]) -> "float | None": + """Marginal cost of running *step* on *n_cases* new cases (``None`` = no basis yet).""" + ev = evidence.get(step.name) + rows = [(_amount(o.cost, axis), len(o.planned_ids)) for o in (ev.chunks if ev else []) + if (o.cost or {}).get("calls") and o.planned_ids] + if rows and sum(k for _, k in rows): + return sum(s for s, _ in rows) / sum(k for _, k in rows) * n_cases + if step.calls_per_case and all(m in rates for m in step.calls_per_case): + return sum(rates[m] * k for m, k in step.calls_per_case.items()) * n_cases + return None + + +# -- C: coverage units ------------------------------------------------------------------- + + +def coverage_units(states_by_route: dict[str, list[dict[str, Any]]], records: list[dict[str, Any]], + evidence: dict[str, StepEvidence], layers: Any, *, min_cover: int) -> dict[str, dict[str, Any]]: + """``{unit id: {layer, stratum, need, measured, gap, layer_state}}`` for every layer of every route + with FAIL cases. A unit of an ``exhausted`` layer keeps its gap: no tool can close it on this model.""" + by_rule = {x.rule_id: x for x in layers} + stratum_of = {r["case_id"]: r["stratum"] for r in records} + units: dict[str, dict[str, Any]] = {} + for route, states in states_by_route.items(): + for st in states: + layer = by_rule[st["rule_id"]] + keys = [*layer.served_by, *(c.name for c in layer.candidates)] + for stratum in sorted({stratum_of[c] for c in st["_fail_ids"]}): + ids = [c for c in st["_fail_ids"] if stratum_of[c] == stratum] + measured = sum(1 for cid in ids if any( + (ev := evidence.get(k)) is not None and ev.refused() is None + and (o := ev.for_case(cid)) is not None and o.status == OK for k in keys)) + need = min(min_cover, len(ids)) + gap = 1.0 if measured == 0 else 0.5 if measured < need else 0.0 + units[f"{layer.rule_id}:{stratum}"] = {"rule_id": layer.rule_id, "stratum": stratum, "need": need, + "measured": measured, "gap": gap, + "layer_state": st["state"], "_ids": ids} + return units + + +def coverage_gain(rule_id: str, new_ids: set[str], units: dict[str, dict[str, Any]]) -> tuple[float, list[str]]: + """Gap removed if the action measures *new_ids*, over all units; and the units it touches.""" + if not units: + return 0.0, [] + removed, touched = 0.0, [] + for uid, u in units.items(): + if u["rule_id"] != rule_id: + continue + added = sum(1 for cid in u["_ids"] if cid in new_ids) + if not added: + continue + after = u["measured"] + added + gap_after = 1.0 if after == 0 else 0.5 if after < u["need"] else 0.0 + if u["gap"] > gap_after: + removed += u["gap"] - gap_after + touched.append(uid) + return removed / len(units), touched + + +def public_units(units: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: + return {uid: {k: v for k, v in u.items() if not k.startswith("_")} for uid, u in units.items()} + + +# -- choosing ------------------------------------------------------------------------------ + + +def value(s: Scored, weights: Weights, axis: str) -> Scored: + s.gain = s.q * max(0.0, weights.d * s.D + weights.t * s.T + weights.c * s.C - weights.r * s.R) + s.U = s.gain / ((s.cost if s.cost is not None else 0.0) + EPSILON[axis]) + return s + + +def choose(candidates: list[Scored], *, decision_no: int, seed: int, explore_every: int, + min_gain: float) -> "tuple[Scored | None, str]": + """The candidate to run, and why: ``best`` / ``explore`` / ``below_threshold`` / ``none``.""" + if not candidates: + return None, "none" + ranked = sorted(candidates, key=lambda s: (-s.U, s.order)) + if explore_every and (decision_no + 1) % explore_every == 0 and len(ranked) > 1: + rng = random.Random(f"{seed}:{decision_no}") + return rng.choice(ranked[1:]), "explore" + best = ranked[0] + if best.gain < min_gain: + return None, "below_threshold" + return best, "best" diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index 19007513..1da6f6a0 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -605,9 +605,20 @@ def _numeric(row: dict[str, Any]) -> dict[str, float]: return out -def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn) -> dict[str, float]: +#: Words a strategy that asks for text before the answer must add over the re-asked +#: question before its answer counts as given after that text. +COMPLIANCE_WORDS = 5 + + +def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn, + asks_for_text: bool = False) -> dict[str, float]: """``prompt_contrast``: per strategy, whether the answer moved off the re-asked - question (by answer key) and whether that fixed or broke it (by the task's scorer).""" + question (by answer key) and whether that fixed or broke it (by the task's scorer). + + With *asks_for_text* (a strategy asking for a description before the answer) + also how many words it added and whether that reached ``COMPLIANCE_WORDS``: + an unchanged answer from a model that never described is not a stable error + surviving description.""" cid = str(case.id) outputs, scored = _outputs(obs), (obs.findings or {}).get("by_strategy") or {} if cid not in (outputs.get("baseline") or {}): @@ -621,6 +632,10 @@ def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn) -> dict[s alt = answer_fn(case, texts[cid]) if base and alt: out[f"changed_{strategy}"] = float(alt != base) + if asks_for_text: + extra = len(str(texts[cid]).split()) - len(str(outputs["baseline"][cid]).split()) + out[f"extra_words_{strategy}"] = float(extra) + out[f"complied_{strategy}"] = float(extra >= COMPLIANCE_WORDS) after = (scored.get(strategy) or {}).get(cid) if before is not None and after is not None: out[f"fixed_{strategy}"] = float(before == 0.0 and after == 1.0) @@ -638,7 +653,8 @@ def follow_up_values(evidence: StepEvidence, case: Any, answer_fn: "AnswerFn | N return {"state": UNTESTED, "action_id": obs.action_id, "reason": f"{obs.status}: {obs.error or ''}".strip()} values = _numeric(obs.per_case().get(cid) or {}) if evidence.step.analyzer == "prompt_contrast": - values.update(_contrast_values(obs, case, answer_fn or default_answer)) + values.update(_contrast_values(obs, case, answer_fn or default_answer, + asks_for_text=evidence.step.min_output_tokens > 0)) if not values: return {"state": UNTESTED, "action_id": obs.action_id, "reason": obs.missing.get(cid, "no per_case row")} return {"state": "measured", "action_id": obs.action_id, "values": values} diff --git a/tests/test_analyzers/test_prompt_contrast.py b/tests/test_analyzers/test_prompt_contrast.py index 250ea2ce..6c63dc12 100755 --- a/tests/test_analyzers/test_prompt_contrast.py +++ b/tests/test_analyzers/test_prompt_contrast.py @@ -189,3 +189,22 @@ def test_prompt_sensitivity_is_a_clean_stats_signal(): # Enters the tested family; not isolated as a label leak. assert "prompt_contrast.prompt_sensitivity" in inp.per_case assert "prompt_contrast.prompt_sensitivity" not in inp.sanity + + +def test_gen_kwargs_reach_every_re_ask_and_the_identity(): + seen = [] + + class _Recording(InterventionModel): + def generate(self, inputs, **kwargs): + seen.append(kwargs) + return super().generate(inputs, **kwargs) + + cases = CaseBatch([FailureCase(id="c", inputs=Inputs(prompt="Is there a cat?"), expected="yes", + observed="No.", label=Label.FAIL)]) + strategies = {"baseline": "{prompt}", "describe_first": "Describe the image, then answer. {prompt}"} + PromptContrastAnalyzer(strategies=strategies, gen_kwargs={"max_new_tokens": 256}).run(_Recording(), cases) + assert seen == [{"max_new_tokens": 256}] * 2 # baseline included: the same cap for both + seen.clear() + plain = PromptContrastAnalyzer(strategies=strategies) + plain.run(_Recording(), cases) + assert seen == [{}, {}] and plain.get_params()["gen_kwargs"] is None diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index e286ca65..1e49799a 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -637,11 +637,12 @@ def test_api_run_meters_tokens_and_dollars_and_runs_its_behavioural_follow_up(tm assert fu["reading"]["route_fail"]["n_measured"] == 2 and fu["reading"]["controls"]["n_measured"] == 2 assert fu["reading"]["route_fail"]["means"]["changed_describe_first"] == 0.0 # "Yes" whatever the prompt assert fu["reading"]["route_fail"]["n_by_field"]["changed_describe_first"] == 2 + assert fu["reading"]["route_fail"]["means"]["complied_describe_first"] == 0.0 # it never described assert report["stop"]["reason"] == "no_candidate" layers = {st["rule_id"]: st["state"] for st in report["routes"][0]["layers"]} assert layers == {"N1": "exhausted", "N2": "exhausted", "N3": "done"} md = (tmp_path / "api" / "triage_report.md").read_text() - assert "## Decisions" in md and "Follow-ups" in md and "USD" in md + assert "## Decisions" in md and "Follow-ups" in md and "USD" in md and "did not add the text" in md assert "Not measured: unsupported (model lacks capabilities" in md # knockout, no table of Nones assert "Not measured: embed_lens unsupported" in md diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_probing_mvp2.py index e27b6829..fa2f4a98 100644 --- a/tests/test_eval_agent/test_probing_mvp2.py +++ b/tests/test_eval_agent/test_probing_mvp2.py @@ -158,15 +158,36 @@ def test_rerun_reads_everything_back_and_a_larger_cap_extends_only_to_new_cases( assert all(big["checks"]["reused_chunks_disjoint"].values()) -def test_describe_first_is_not_applicable_under_a_short_output_cap(tmp_path): +def test_describe_first_asks_for_its_own_output_room_where_the_backend_honours_it(tmp_path): cases, table = _pope_like() ident = {"spec": "table", "generation": {"max_new_tokens": 16}} - report = run_triage(_Table(table), cases, **_kw(tmp_path / "cap", max_fail=4, min_route_fail=1, - model_identity=ident)) - assert not [d for d in report["decisions"] if d["kind"] == "follow_up"] - passed = [t for row in report["routes"] for st in row["layers"] for t in st.get("tried") or [] - if t["key"] == "describe_first"] - assert passed and all(t["status"] == "not_applicable" and "output cap of 16" in t["reason"] for t in passed) + + class _Recording(_Table): + def generate(self, inputs, **kwargs): + self.kwargs = [*getattr(self, "kwargs", []), kwargs] + return super().generate(inputs, **kwargs) + + # per-call settings honoured: the describe step asks for 256 tokens and runs + model = _Recording(table) + report = run_triage(model, cases, **_kw(tmp_path / "room", max_fail=4, min_route_fail=1, model_identity=ident)) + keys = [d["key"] for d in report["decisions"] if d["kind"] == "follow_up"] + assert "describe_first" in keys and {"max_new_tokens": 256} in model.kwargs + assert all(report["checks"]["configs_match_plan"].values()) + + # dropped per call (an OpenAI-compatible endpoint): the step runs without its + # gen_kwargs, so the host's 16-token cap applies and leaves no room + from evalrx.eval_agent.probing.controller import _Run + from evalrx.eval_agent.probing.ledger import Ledger + + step, ids = _step("describe_first"), [str(c.id) for c in cases][:4] + for per_call, expected in ((True, None), (False, "not_applicable")): + run = _Run(_Table(table), cases, Ledger(tmp_path / f"g{per_call}"), context={"model": ident}, extras={}, + task_kind="yes_no", budget_sec=0.0, price_fn=None, run_logger=None, say=lambda _m: None, + per_call_generation=per_call) + why = run.gate(step, ids) + assert (why[0] if why else None) == expected + assert ("gen_kwargs" in run.config(step)) is per_call + assert "output cap of 16" in why[1] def test_max_actions_zero_runs_only_the_battery(tmp_path): diff --git a/tests/test_eval_agent/test_probing_mvp3.py b/tests/test_eval_agent/test_probing_mvp3.py new file mode 100644 index 00000000..d4a55573 --- /dev/null +++ b/tests/test_eval_agent/test_probing_mvp3.py @@ -0,0 +1,132 @@ +"""MVP-3 scored scheduler: U(a) = q·[D + T + C − R]₊ / (c + ε), against the rules. + +* q counts distinct observations (a read-back once), a refusal as a failure; +* c comes from the step's own cost per case, else measured per-call rates; +* C is the coverage gap an action removes, T the recorded gap it completes; +* the best U wins, ties go to the soft order, every k-th decision explores + with a seed, and a run stops when no gain reaches the threshold; +* a scored run is deterministic on resume and comparable with the rules run + that shares its ledger. +""" + +from __future__ import annotations + +import json + +from evalrx.eval_agent.probing import BATTERY, LAYERS, run_triage +from evalrx.eval_agent.probing.actions import OK, UNFAITHFUL, Observation +from evalrx.eval_agent.probing.compare import compare +from evalrx.eval_agent.probing.evidence import StepEvidence +from evalrx.eval_agent.probing.rules import candidate_steps +from evalrx.eval_agent.probing.scoring import ( + Scored, + availability, + choose, + coverage_gain, + estimate_cost, + method_rates, +) +from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table + + +def _step(key): + return {s.name: s for s in [*BATTERY, *candidate_steps(LAYERS)]}[key] + + +def _obs(aid, ids, status=OK, cost=None, fidelity=None): + return Observation(action_id=aid, analyzer="x", attempt=1, status=status, params={}, planned_ids=list(ids), + measured_ids=list(ids), findings={"per_case": []} if status == OK else None, + fidelity=fidelity or {"status": "not_applicable"}, cost=cost or {}) + + +def test_availability_counts_each_observation_once_and_a_refusal_as_a_failure(): + ko = _step("attention_knockout") + ok = _obs("a", ["c1"]) + ev = {"attention_knockout": StepEvidence(ko, [ok, ok, _obs("b", ["c2"], status=UNFAITHFUL)])} + assert availability("attention_knockout", ev) == (1 + 1) / (2 + 2) + assert availability("gradcam", ev) == 0.5 # never tried + + +def test_costs_come_from_the_steps_own_history_else_measured_rates(): + sc = _step("self_consistency") + ev = {"self_consistency": StepEvidence(sc, [_obs("s", ["a", "b"], cost={"wall_sec": 10.0, "calls": {"generate": 10}})]), + "attention_knockout": StepEvidence(_step("attention_knockout"), + [_obs("k", ["a"], cost={"wall_sec": 4.0, "calls": {"forward": 8}})])} + rates = method_rates(ev, "wall_sec") + assert rates == {"generate": 1.0, "forward": 0.5, "backward": 1.5, "logprobs": 1.0} + assert estimate_cost(sc, 3, ev, "wall_sec", rates) == 15.0 # 5 s per case, its own + assert estimate_cost(_step("gradcam"), 2, ev, "wall_sec", rates) == 3.0 # 1 backward per case + assert estimate_cost(_step("causal_trace"), 2, {}, "wall_sec", {}) is None + + +def test_coverage_gain_is_the_gap_removed_over_all_units(): + units = {"S1:yes": {"rule_id": "S1", "stratum": "yes", "need": 2, "measured": 0, "gap": 1.0, "_ids": ["a", "b"]}, + "S1:no": {"rule_id": "S1", "stratum": "no", "need": 2, "measured": 1, "gap": 0.5, "_ids": ["c", "d"]}, + "U1:yes": {"rule_id": "U1", "stratum": "yes", "need": 1, "measured": 0, "gap": 1.0, "_ids": ["e"]}, + "N2:no": {"rule_id": "N2", "stratum": "no", "need": 1, "measured": 1, "gap": 0.0, "_ids": ["f"]}} + gain, touched = coverage_gain("S1", {"a", "d"}, units) + assert gain == (0.5 + 0.5) / 4 and touched == ["S1:yes", "S1:no"] # one of two: 1 -> 0.5; 1 of 2 done -> 0 + assert coverage_gain("N2", {"f"}, units) == (0.0, []) + + +def test_choose_takes_the_best_value_breaks_ties_by_soft_order_explores_and_stops_below_threshold(): + def s(key, U, gain, order): + return Scored(kind="follow_up", key=key, U=U, gain=gain, order=order) + + pool = [s("late", 0.5, 0.2, (1, 2)), s("early", 0.5, 0.2, (1, 0)), s("cheap", 0.1, 0.3, (0, 0))] + best, why = choose(pool, decision_no=0, seed=0, explore_every=10, min_gain=0.01) + assert (best.key, why) == ("early", "best") + picked, why = choose(pool, decision_no=9, seed=0, explore_every=10, min_gain=0.01) + assert why == "explore" and picked.key != "early" + assert choose(pool, decision_no=9, seed=0, explore_every=10, min_gain=0.01)[0].key == picked.key # seeded + assert choose([s("x", 0.0, 0.0, (0, 0))], decision_no=0, seed=0, explore_every=10, min_gain=0.01) == ( + None, "below_threshold") + assert choose([], decision_no=0, seed=0, explore_every=10, min_gain=0.01) == (None, "none") + + +def test_scored_run_is_traceable_deterministic_on_resume_and_comparable_with_the_rules(tmp_path): + cases, table = _pope_like() + out = tmp_path / "p" + rules = run_triage(_Table(table), cases, **_kw(out, max_fail=8, min_route_fail=1)) + model = _Table(table) + scored = run_triage(model, cases, **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored")) + assert scored["scheduler"] == "scored" and (out / "triage_report.scored.json").is_file() + assert (out / "triage_report.json").is_file() # the rules report is not overwritten + for d in scored["decisions"]: + if d["kind"] in ("expand", "follow_up", "extend", "battery"): + top = d["candidates"][0] + assert {"U", "gain", "T", "C", "R", "q", "cost"} <= set(top) and d["choice"] in ("best", "explore") + # the battery is complete on the final sample whatever the order of choices + assert all(scored["checks"]["battery_covers_sample"].values()) + assert scored["cost"]["evidence"]["n_observations"] > 0 + again = run_triage(_Table(table), cases, **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored")) + assert [(d["kind"], d.get("key")) for d in again["decisions"]] == [(d["kind"], d.get("key")) + for d in scored["decisions"]] + diff = compare(rules, scored) + assert diff["same_sample"] and diff["schedulers"] == ["rules", "scored"] + json.dumps(diff) + + +def test_scored_runs_a_batch_dependent_step_once_after_the_last_expansion(tmp_path): + from evalrx.eval_agent.probing.actions import PlanStep + from evalrx.eval_agent.probing.rules import Layer + + cases, table = _pope_like() + batchy = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "q": "Q: {prompt}"}}, "Z", + "a reading inferred from the whole batch", key="batchy", reuse=False, + reuse_note="test: pretends to depend on the batch") + fallback = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "f": "F: {prompt}"}}, "Z1", + "a batch-dependent fallback", key="batchy_fallback", reuse=False, reuse_note="test") + layers = (*LAYERS, Layer("Z1", "S", "a batch-dependent S reading", (fallback,), served_by=("batchy",))) + report = run_triage(_Table(table), cases, **_kw(tmp_path / "z", max_fail=8, min_route_fail=1, + scheduler="scored", battery=(*BATTERY, batchy), layers=layers)) + runs = [e for e in report["executions"] if e["key"] == "batchy"] + last = report["revisions"][-1]["revision"] + assert [(e["revision"], e["n_cases"]) for e in runs] == [(last, len(report["sample"]["case_ids"]))] + assert last == 1 # it waited for the expansion, though cheap + (chosen,) = [d for d in report["decisions"] if d.get("key") == "batchy"] + assert chosen["kind"] == "battery" and chosen["revision"] == last # a scored choice once the sample settled + # its layer waited for it: the batch-dependent fallback never ran + assert not [e for e in report["executions"] if e["key"] == "batchy_fallback"] + held = [f for d in report["decisions"] for f in d.get("filtered") or [] if f["key"] in ("batchy", "batchy_fallback")] + assert held and all(f["key"] == "batchy" and "supersede" in f["reason"] for f in held) From 5ef0d0f6c366a16e339cb9952115c4717bc7686b Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 18 Oct 2026 10:57:01 -0700 Subject: [PATCH 05/26] add judge for routing explanation --- CHANGELOG.md | 37 ++ docs/agentic_benchmark.md | 4 +- evalrx/benchmark/run.py | 10 +- evalrx/benchmark/runner.py | 40 +- evalrx/eval_agent/probing/compare.py | 51 ++- evalrx/eval_agent/probing/controller.py | 397 ++++++++++++++-- evalrx/eval_agent/probing/explanations.py | 483 ++++++++++++++++++++ evalrx/eval_agent/probing/scoring.py | 12 +- tests/test_analysis/test_run_cli.py | 25 + tests/test_eval_agent/test_probing_mvp2.py | 16 +- tests/test_eval_agent/test_probing_mvp3b.py | 274 +++++++++++ 11 files changed, 1290 insertions(+), 59 deletions(-) create mode 100644 evalrx/eval_agent/probing/explanations.py create mode 100644 tests/test_eval_agent/test_probing_mvp3b.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e44b6385..dd13bbac 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,43 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — triage competing explanations: D for the scored scheduler (MVP-3, second part) + +`--triage-explanations judge` (with `--triage-scheduler scored`) has the +chain's judge propose, per active route, up to three competing local +explanations of the route's FAIL cases, each predicting `up` / `down` / +`same` / `unknown` for the readings of every tool still to run there (FAIL mean +minus PASS control mean against a band fixed per reading in +`probing/explanations.py`, version `mvp3-explain-1`). The judge is asked once +the sample has settled and again, at most three asks, when the evidence has +decided a prediction and a route with tools left has fewer than two live +explanations. Code checks each prediction on the 95% interval of the difference +(hit inside the predicted region, miss outside, else undetermined); a miss +contradicts the explanation. A candidate's D is the share of pairs of its +route's live explanations whose predictions for it conflict (scoring version +`mvp3-score-2`). The judge sees route summaries and readings only, never a +case or CONFIRM; each call's prompt, reply and cost is stored under +`probing/explanations/`, so a resumed run reads it back. The report is +`triage_report.scored_d.*`; every report now carries `outcomes` (each card +reading's FAIL-vs-control difference per route), and `compare.py` counts the +pairs of the explaining run's explanations each run's evidence tells apart. +Only each open layer's current candidate is offered for prediction. On +Qwen3.5-0.8B POPE (claude-opus-5 judge, two asks, 169 s) D reorders the +follow-ups but changes neither the set that runs nor the pairs of explanations +the final evidence tells apart (4/7 for every scheduler); under a tight budget +the judge's time costs coverage. The re-ask after the first S explanations were +all contradicted proposed one that patchscope then confirmed out of sample +(gold readable at no depth: peak probability FAIL - control -0.85). D does not +yet discount predictions the route's case count cannot decide. + +### Changed — triage budgets charge the evidence read + +`--triage-budget-sec` / `--triage-budget-usd` are checked against the evidence +the run reads, each observation at its first execution's cost, plus judge +calls (`cost.charged` in the report), not against everything the ledger has +recorded across invocations: a resumed run or a second scheduler on the same +ledger now decides as the first run did. + ### Added — triage scored scheduler (MVP-3, first part) `--triage-scheduler scored` replaces the rules' rounds with one decision at a diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 1371cf5c..bde025f9 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -29,7 +29,7 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend --m1-policy triage_active --run-tag triage0 ``` -After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called, M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the wall-clock budget is spent or once its estimate (the same step's earlier seconds per case) exceeds what is left. +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once its estimate (the same step's earlier seconds per case) exceeds what is left. The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. **Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Steps whose per-case rows do not depend on the batch (the audits, the swap with donors from the whole partition, the knockout, re-sampling, the wrappers) run on the new cases alone and keep the old rows. `embed_lens` and `patchscope` infer the question words from the batch, but no route reads them, so they wait until the sample stops growing and run once on the whole of it. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). @@ -37,6 +37,8 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — each active route's open or stale layer, the expansion, and the batch-dependent battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for extending a step to a route's new cases or resolving a contradiction and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist; q is the analyzer's smoothed success rate in this run; c is the estimated cost on the primary axis (USD when every action is priced, else seconds). Every 10th decision explores with a seed, and the run stops when no candidate's gain reaches 0.01. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. +**Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D is the share of pairs of its route's live explanations whose predictions for it conflict (a pair with `unknown` counts only in the denominator). The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Only each open layer's current candidate is offered for prediction. On Qwen3.5-0.8B POPE D reorders the follow-ups but changes neither what runs nor which pairs the final evidence tells apart, and the judge's two asks (169 s) cost about a sixth of the evidence time; D does not yet discount predictions the route's case count cannot decide. + The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Any readable answer that differs fires U. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the gold answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index cb367733..db5467f8 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -162,11 +162,17 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP help="triage_active: rules = MVP-2 fixed rounds over the routes' layers; scored = MVP-3 " "value per cost, U = q*[D+T+C-R]+/(c+eps) (report: triage_report.scored.*)") p.add_argument("--triage-budget-usd", type=float, default=0.0, - help="triage_active: USD cap on executed actions on priced API models (0 = none)") + help="triage_active: USD cap on priced API models (0 = none), charged like " + "--triage-budget-sec") + p.add_argument("--triage-explanations", choices=["none", "judge"], default="none", + help="triage_active with --triage-scheduler scored: judge = the --judge-provider/" + "--judge-model judge proposes competing explanations with predictions once per " + "sample revision, giving D (none = D stays 0, no judge is built)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, - help="triage_active: wall-clock cap on executed actions (0 = none); a running " + help="triage_active: wall-clock cap (0 = none) on the evidence the run reads, each " + "observation at its first execution's cost, plus judge calls; a running " "action is not interrupted, later ones are skipped") p.add_argument("--analyzer-max-cases", type=int, default=0, help="cap per analyzer (0 = every case)") p.add_argument("--m2-codegen", action=argparse.BooleanOptionalAction, default=None, diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 58085907..53c2760c 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -13,6 +13,7 @@ from __future__ import annotations +import argparse import json import time from dataclasses import replace @@ -380,14 +381,35 @@ def _price_fn(spec): return lambda usage: usd(model_id, usage) +def _triage_explainer(args, spec): + """The chain's judge as the scored triage's explainer (``--triage-explanations judge``). + + Triage runs no coding stage, so the judge is built without the coder checks + the Gemini judge otherwise needs. The judge must not be the model under test.""" + from evalrx.eval_agent.probing.explanations import Explainer + from evalrx.models.backends.api.prices import usd + + if args.triage_scheduler != "scored": + raise SystemExit("--triage-explanations judge needs --triage-scheduler scored") + judge_args = argparse.Namespace(**{**vars(args), "allow_codegen": False, "explore": False, "m2_codegen": False, + "skip_m5": True, "coder_provider": None}) + judge, _, name, _ = build_judge(judge_args) # the coder slot carries the judge's resolved model name + name = name or args.judge_model + if name and name in {spec.key, spec.hf_repo}: + raise SystemExit(f"the triage judge ({name}) is the model under test; pick another --judge-model") + identity = {"provider": args.judge_provider, "model": name, "effort": args.judge_effort} + return Explainer(judge, identity=identity, price_fn=(lambda u: usd(name, u)) if name else None) + + def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, cases, ctx, run_dir: Path, baseline: dict) -> int: """``--m1-policy triage_active``: the triage battery, rule-chosen expansions and follow-ups on EXPLORE, then stop. Same Stage 0 and the same EXPLORE/CONFIRM split as the diagnosis loop; the - controller sees EXPLORE only, calls no judge, and runs no M2-M5. Outputs - go to ``/probing/``. + controller sees EXPLORE only and runs no M2-M5; it calls the judge only with + ``--triage-explanations judge`` (scored scheduler: explanations for D, from + route summaries, never a case). Outputs go to ``/probing/``. """ from evalrx.eval_agent.probing import explore_confirm_split, run_triage @@ -401,7 +423,12 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: if not gen_kwargs: # API backends carry the sampling (and the output cap) in the runtime, not per call identity["runtime_generation"] = generation_settings(task, args) - ctx.config.update(m1_policy="triage_active", judge_provider=None, judge_model=None) # none was built + explainer = _triage_explainer(args, spec) if args.triage_explanations == "judge" else None + if explainer is None: + ctx.config.update(m1_policy="triage_active", judge_provider=None, judge_model=None) # none was built + else: + ctx.config.update(m1_policy="triage_active", judge_provider=explainer.identity["provider"], + judge_model=explainer.identity["model"], triage_explanations="judge") extras: dict = {"modality_ablation": {"score_fn": T.score_case}, "prompt_contrast": {"score_fn": T.score_case}} sampling = _sampling_kwargs(resolved, args) @@ -423,7 +450,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: **{k: baseline[k] for k in ("api_usage", "usd") if k in baseline}}, price_fn=_price_fn(spec), per_call_generation=sampling is not None, - scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), + scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "confirm_visible_to_controller": False}, @@ -437,9 +464,12 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "triage_steps": [{k: s.get(k) for k in ("kind", "key", "analyzer", "status", "reused", "n_cases")} for s in report["executions"]], "triage_stop": report["stop"], "triage_scheduler": report["scheduler"], + "triage_explanations": args.triage_explanations, } (run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n", encoding="utf-8") - name = "triage_report" if args.triage_scheduler == "rules" else f"triage_report.{args.triage_scheduler}" + from evalrx.eval_agent.probing.controller import report_name + + name = report_name(args.triage_scheduler, explainer is not None) print(f"Done (triage). {run_dir / 'probing' / (name + '.md')}") return 0 diff --git a/evalrx/eval_agent/probing/compare.py b/evalrx/eval_agent/probing/compare.py index f48abae5..a3363382 100644 --- a/evalrx/eval_agent/probing/compare.py +++ b/evalrx/eval_agent/probing/compare.py @@ -8,8 +8,41 @@ from __future__ import annotations +from itertools import combinations from typing import Any +from evalrx.eval_agent.probing.explanations import CARDS, verdict + + +def discrimination(explained: dict[str, Any], report: dict[str, Any]) -> dict[str, Any]: + """How many pairs of *explained*'s last explanations (per route) with conflicting predictions + *report*'s evidence tells apart: one of the pair misses on a reading they conflict on. + + Applies one run's explanations to another run's final ``outcomes``, so two + schedulers are compared on the same explanations whichever of them asked.""" + sets = [s for s in (explained.get("explanations") or {}).get("sets") or [] if s["hypotheses"]] + if not sets: + return {"revision": None, "n_conflicting_pairs": 0, "n_resolved": 0, "pairs": []} + last, outcomes = sets[-1], report.get("outcomes") or {} + bands = {(key, m.field): m.band for key, ms in CARDS.items() for m in ms} + pairs = [] + for a, b in combinations(last["hypotheses"], 2): + if a["route"] != b["route"]: + continue + on = [(step, f) for step in sorted(set(a["predictions"]) & set(b["predictions"])) + for f in sorted(set(a["predictions"][step]) & set(b["predictions"][step])) + if a["predictions"][step][f] != b["predictions"][step][f]] + if not on: + continue + resolved = [f"{step}.{f}" for step, f in on + if any(verdict(h["predictions"][step][f], + ((outcomes.get(a["route"]) or {}).get(step) or {}).get(f, {}).get("ci95"), + bands[(step, f)]) == "miss" for h in (a, b))] + pairs.append({"route": a["route"], "pair": [a["id"], b["id"]], "on": [f"{s}.{f}" for s, f in on], + "resolved_on": resolved}) + return {"revision": last["revision"], "n_conflicting_pairs": len(pairs), + "n_resolved": sum(1 for x in pairs if x["resolved_on"]), "pairs": pairs} + def _followed(report: dict[str, Any]) -> list[tuple[str, str, str]]: return [(d.get("route") or "-", d.get("rule_id") or "-", d.get("key") or d["kind"]) @@ -24,7 +57,7 @@ def open_units(r: dict[str, Any]) -> list[dict[str, Any]]: # units some tool co gap = {name: sum(u["gap"] for u in open_units(r)) for name, r in (("baseline", baseline), ("other", other))} units = {name: len(open_units(r)) for name, r in (("baseline", baseline), ("other", other))} - return { + out = { "schedulers": [baseline.get("scheduler", "rules"), other.get("scheduler", "rules")], "same_sample": baseline["sample"]["case_ids"] == other["sample"]["case_ids"], "actions": {"baseline": a, "other": b}, @@ -33,11 +66,19 @@ def open_units(r: dict[str, Any]) -> list[dict[str, Any]]: # units some tool co "same_order": a == b, "evidence_cost": {"baseline": (baseline.get("cost") or {}).get("evidence"), "other": (other.get("cost") or {}).get("evidence")}, + "charged": {"baseline": (baseline.get("cost") or {}).get("charged"), + "other": (other.get("cost") or {}).get("charged")}, + "judge": {"baseline": (baseline.get("cost") or {}).get("judge"), + "other": (other.get("cost") or {}).get("judge")}, "controller_sec": {"baseline": (baseline.get("cost") or {}).get("controller_sec"), "other": (other.get("cost") or {}).get("controller_sec")}, "coverage_gap": gap, "coverage_units": units, "stop": {"baseline": baseline["stop"], "other": other["stop"]}, } + source = next((r for r in (other, baseline) if r.get("explanations")), None) + if source is not None: # both runs' evidence, on the same explanations + out["discrimination"] = {"baseline": discrimination(source, baseline), "other": discrimination(source, other)} + return out def markdown(diff: dict[str, Any]) -> str: @@ -52,8 +93,14 @@ def markdown(diff: dict[str, Any]) -> str: ev = diff["evidence_cost"] lines += ["", f"Evidence cost (first execution of every observation read): {a_name} {ev['baseline']}; " f"{b_name} {ev['other']}.", - f"Controller time outside the actions: {diff['controller_sec']}.", + f"Charged against the budget (evidence plus judge calls): {diff['charged']}; judge: {diff['judge']}.", + f"Controller time outside the actions and the judge: {diff['controller_sec']}.", f"Coverage gap left on units some tool can close here (sum): {diff['coverage_gap']} of " f"{diff['coverage_units']} units.", f"Stop: {diff['stop']}.", ""] + if "discrimination" in diff: + d = diff["discrimination"] + lines += [f"Pairs of competing explanations (the explaining run's last set) each run's evidence tells " + f"apart: {a_name} {d['baseline']['n_resolved']}/{d['baseline']['n_conflicting_pairs']}, " + f"{b_name} {d['other']['n_resolved']}/{d['other']['n_conflicting_pairs']}.", ""] return "\n".join(lines) diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 43689f66..4cb04d33 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -40,11 +40,15 @@ * ``max_actions`` decisions (expansions + follow-ups) have been made; or * the wall-clock budget is spent, or an action's estimate exceeds what is left. -No judge is called, no hypothesis is named, and CONFIRM never enters. Outputs -land in ``out_dir``:: +The rules scheduler calls no judge and names no hypothesis. The scored +scheduler (MVP-3) may take an explainer: the judge then proposes competing +explanations once the sample has settled, and their predictions give each +candidate its D (:mod:`.explanations`); no explanation is a finding. CONFIRM +never enters. Outputs land in ``out_dir``:: - split_manifest.json triage_report.json triage_report.md + split_manifest.json triage_report[.scored].json triage_report[.scored].md selection_trace.jsonl cost_ledger.jsonl observations/.json + explanations/.json (with an explainer: each judge call's prompt, reply and cost) """ from __future__ import annotations @@ -53,6 +57,7 @@ import inspect import json import os +import random import time from collections import Counter from functools import partial @@ -63,6 +68,17 @@ from evalrx.eval_agent.probing.actions import OK, SKIPPED, PlanStep, ProbeAction, canonical from evalrx.eval_agent.probing.evidence import StepEvidence from evalrx.eval_agent.probing.executor import execute, gate +from evalrx.eval_agent.probing.explanations import ( + CARDS, + EXPLAIN_VERSION, + Explainer, + ExplanationSet, + Hypothesis, + Metric, + check, + disagreement, + outcome, +) from evalrx.eval_agent.probing.ledger import Ledger from evalrx.eval_agent.probing.rules import ( LAYERS, @@ -73,6 +89,7 @@ active_routes, candidate_steps, expansion_gaps, + matched_controls, next_for_route, next_size, public, @@ -94,7 +111,13 @@ public_units, value, ) -from evalrx.eval_agent.probing.triage import ROUTE_STEPS, follow_up_reading, summarize, triage_cases +from evalrx.eval_agent.probing.triage import ( + ROUTE_STEPS, + follow_up_reading, + follow_up_values, + summarize, + triage_cases, +) if TYPE_CHECKING: from evalrx.core.case import CaseBatch @@ -117,6 +140,15 @@ _BATCH_WORDS = ("the question words (and recurring media words) are inferred from the batch's prompts " "and images") +#: What a FAIL case on each route has shown, as the judge is told. +ROUTE_MEANING = { + "H": "the output lost the answer: an extraction, truncation or format check fired", + "N": "the answer did not change when the media was swapped for media on which the correct answer differs", + "U": "the answer moved under re-sampling at the host's settings or under a neutral rewording", + "S": "a stable error: the output, media-swap and stability checks all ran and none fired", + "X": "a required check could not run on the case", +} + BATTERY: tuple[PlanStep, ...] = ( PlanStep("answer_extraction_audit", {"reask": False}, "H", "re-read Stage-0 outputs for grading and extraction problems"), @@ -204,6 +236,7 @@ def __init__(self, model: Any, explore: "CaseBatch", ledger: Ledger, *, context: self.evidence: dict[str, StepEvidence] = {} self.executions: list[dict[str, Any]] = [] self.blocked: dict[str, str] = {} + self.judge_cost: dict[str, float] = {} def batch(self, ids: "list[str]") -> "CaseBatch": from evalrx.core.case import CaseBatch @@ -255,16 +288,26 @@ def estimate_usd(self, step: PlanStep, n_cases: int) -> "float | None": n = sum(k for _, k in rows) return round(sum(v for v, _ in rows) / n * n_cases, 6) if n else None + def charged(self, axis: str) -> float: + """What this run's evidence cost when each observation was first executed (a read-back + at its original cost, once), plus its judge calls: the same for a resumed run and for + a second scheduler on a shared ledger as for the run that executed it.""" + seen: dict[str, float] = {} + for ev in self.evidence.values(): + for obs in ev.chunks: + seen.setdefault(obs.action_id, float((obs.cost or {}).get(axis) or 0.0)) + return sum(seen.values()) + float(self.judge_cost.get(axis) or 0.0) + def over_budget(self, estimate: "float | None", estimate_usd: "float | None" = None) -> "str | None": """Why an action with these estimates may not start (``None`` = it may).""" if self.budget_sec > 0: - spent = self.ledger.spent("wall_sec") + spent = self.charged("wall_sec") if spent >= self.budget_sec: return f"wall-clock budget {self.budget_sec}s spent" if estimate is not None and spent + estimate > self.budget_sec: return f"estimated {estimate}s exceeds the {round(self.budget_sec - spent, 1)}s left" if self.budget_usd > 0: - spent = self.ledger.spent("usd") + spent = self.charged("usd") if spent >= self.budget_usd: return f"USD budget {self.budget_usd} spent" if estimate_usd is not None and spent + estimate_usd > self.budget_usd: @@ -292,6 +335,9 @@ def adopt_for(self, step: PlanStep, target: "list[str]", *, kind: str, revision: except Exception: # noqa: BLE001 - run_step records the construction failure return False ev = self.evidence.setdefault(step.name, StepEvidence(step)) + todo = ev.todo(target) + if not todo or self.over_budget(self.estimate_sec(step, len(todo)), self.estimate_usd(step, len(todo))): + return False # what a fresh run could not afford is not read back either: run_step records it n = len(ev.chunks) self._adopt(ev, step_id, target, {"kind": kind, "revision": revision, "key": step.name, "analyzer": step.analyzer, "rule_id": rule_id, "route": route}) @@ -354,6 +400,21 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: record = {**base, "status": "failed", "reused": False, "error": str(exc)} self._log(record) return record + todo = ev.todo(target) + if not todo: + return None + # Checked as if the cases ran fresh, before anything is read back: the budget is + # charged with the evidence read, so a resumed run (or a second scheduler on the + # same ledger) must skip what the run that executed it could not afford. + estimate = self.estimate_sec(step, len(todo)) + why = None if budget_checked else self.over_budget(estimate, self.estimate_usd(step, len(todo))) + if why is not None: + self.ledger.trace({**base, "event": "skipped", "status": SKIPPED, "reason": why, "n_cases": len(todo)}) + self.blocked[step.name] = why + record = {**base, "status": SKIPPED, "reused": False, "reason": why, "n_cases": len(todo)} + self._log(record) + self.say(f"[triage] {step.name}: skipped ({why})") + return record record = self._adopt(ev, step_id, target, base) if step.reuse else None todo = ev.todo(target) @@ -380,15 +441,6 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: return record estimate = self.estimate_sec(step, len(cases)) - why = None if budget_checked else self.over_budget(estimate, self.estimate_usd(step, len(cases))) - if why is not None: - self.ledger.trace({**base, "event": "skipped", "status": SKIPPED, "reason": why}) - self.blocked[step.name] = why - record = {**base, "status": SKIPPED, "reused": False, "reason": why} - self._log(record) - self.say(f"[triage] {step.name}: skipped ({why})") - return record - prior = self.ledger.attempts(action_id) attempt = prior + 1 self.ledger.trace({ @@ -453,6 +505,7 @@ def run_triage( min_gain: float = 0.01, min_cover: int = 8, budget_usd: float = 0.0, + explainer: "Explainer | None" = None, run_logger: Any = None, progress: "Callable[[str], None] | None" = print, ) -> dict[str, Any]: @@ -486,9 +539,12 @@ def run_triage( analyzer_kwargs: per-analyzer constructor extras the host supplies (e.g. the task's ``score_fn``, the sampling settings). price_fn: ``api_usage -> USD`` (``None`` = no price on record). - budget_sec: wall-clock cap on executed actions (0 = none). A running - action is not interrupted; one whose estimate (from the - same step's earlier seconds per case) exceeds what is + budget_sec: wall-clock cap (0 = none) on the evidence the run reads, + each observation at the cost of its first execution (so a + resumed run, or a second scheduler on the same ledger, is + charged what the evidence cost), plus its judge calls. A + running action is not interrupted; one whose estimate (from + the same step's earlier seconds per case) exceeds what is left is skipped. stage0_cost: the shared baseline cost, logged once and kept separate. partition: how EXPLORE/CONFIRM were split (recorded, not used). @@ -503,12 +559,19 @@ def run_triage( weights, explore_every, min_gain, min_cover: the scored scheduler's weights, exploration period (every k-th decision), value floor and per-unit coverage target. - budget_usd: USD cap on executed actions (0 = none), checked like - ``budget_sec`` with the step's earlier USD per case. + budget_usd: USD cap (0 = none), charged like ``budget_sec`` and checked + with the step's earlier USD per case. + explainer: the scored scheduler's source of competing explanations + (:mod:`.explanations`): asked once the sample has settled and + again when the evidence has thinned a route's live explanations + (at most ``explainer.max_asks`` times); its predictions give + each candidate its D. ``None`` = D stays 0. run_logger: optional RunLoggerV2 for per-call model logs. """ if scheduler not in SCHEDULERS: raise ValueError(f"scheduler must be one of {SCHEDULERS}; got {scheduler!r}") + if explainer is not None and scheduler != "scored": + raise ValueError("explanations give D to the scored scheduler; the rules scheduler does not read them") weights = weights or Weights() started = time.monotonic() say = progress or (lambda _msg: None) @@ -612,15 +675,39 @@ def do_expand(plan: Any, gaps: list[dict[str, Any]], extra: dict[str, Any]) -> N budget_checked=True) by_rule = {x.rule_id: x for x in layers} - - def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] - ) -> tuple[list[Scored], list[dict[str, Any]], str]: - """Every feasible candidate with its value, what the budget filtered out, and the cost axis.""" - nonlocal expansion_note + step_layers: dict[tuple[str, str], Layer] = {} + for x in layers: + for name in (*x.served_by, *(c.name for c in x.candidates)): + step_layers.setdefault((x.route, name), x) + + def outcomes_for(records: list[dict[str, Any]]) -> Callable[[str, str, Metric], dict[str, Any]]: + """``(route, step key, reading) -> outcome``: the reading's FAIL-minus-control difference + on the route's current FAIL cases (the layer's filter applied) and their PASS controls.""" + groups: dict[Any, tuple[list[str], list[str]]] = {} + values: dict[tuple[str, str], dict[str, Any]] = {} + + def get(route: str, key: str, metric: Metric) -> dict[str, Any]: + ev = run.evidence.get(key) + if ev is None or not ev.chunks: + return {"n": [0, 0], "observed": "not_measured"} + layer = step_layers.get((route, key)) + flt = layer.case_filter if layer is not None else None + if (route, flt) not in groups: + fail_ids = route_fail_ids(records, route, flt) + groups[(route, flt)] = (fail_ids, matched_controls(records, fail_ids, rank_of)[0]) + fail_ids, controls = groups[(route, flt)] + for cid in (*fail_ids, *controls): + if (key, cid) not in values: + values[(key, cid)] = follow_up_values(ev, run.by_id[cid], answer_fn) + return outcome({cid: values[(key, cid)] for cid in (*fail_ids, *controls)}, fail_ids, controls, metric) + + return get + + def route_view(records: list[dict[str, Any]], gaps: list[dict[str, Any]] + ) -> tuple[dict[str, list[dict[str, Any]]], bool]: + """Every active route's layer states (pending battery steps first), and whether an + expansion can still follow.""" sample_ids = list(draw.case_ids) - # A batch-dependent step's reading is superseded by any later expansion, and no - # route reads it: while an expansion can still follow, running it is wasted. Its - # layer waits for it (a battery step) rather than falling back to another tool. growing = bool(gaps) and expansion_note is None and \ next_size(len(draw.fail_ids), max_fail, n_available) is not None pending = {s.name: (s, sample_ids) for s in deferred @@ -629,8 +716,131 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] # Decisions read only this scheduler's own evidence and price every candidate as if # it ran fresh: chunks in the ledger (an earlier invocation, the other scheduler) # save compute when the chosen step runs, never change what is chosen. - states = {r["route"]: route_states(r["route"], records, run.evidence, run.gate, rank_of, layers=layers, - blocked=run.blocked, pending=pending) for r in rows} + return {r["route"]: route_states(r["route"], records, run.evidence, run.gate, rank_of, layers=layers, + blocked=run.blocked, pending=pending) for r in rows}, growing + + explanation_sets: list[ExplanationSet] = [] + + def explanation_request(records: list[dict[str, Any]], states: dict[str, list[dict[str, Any]]], + outcome_of: Callable[[str, str, Metric], dict[str, Any]] + ) -> tuple[dict[str, Any], dict[str, dict[str, list[str]]]]: + """What the judge sees, and per route the steps (with their readings) it may predict: + each open layer's current candidate, in a seeded order. A fallback only becomes a + candidate when its layer's first choice fails; predictions on it would mostly go + unchecked (a later ask covers it once it is the candidate).""" + offered: dict[str, dict[str, list[str]]] = {} + routes: dict[str, Any] = {} + for route, sts in states.items(): + to_run: list[dict[str, Any]] = [] + for st in sts: + if st["state"] not in ("open", "extend"): + continue + layer, step = by_rule[st["rule_id"]], st["step"] + if step.name in CARDS and all(c["step"] != step.name for c in to_run): + to_run.append({"step": step.name, "tool": step.analyzer, "layer": layer.rule_id, + "question": layer.question, "what": step.purpose, + **({"caveat": step.caveat} if step.caveat else {}), + "readings": [m.card() for m in CARDS[step.name]]}) + if not to_run: + continue + random.Random(f"{seed}:{revision}:{route}").shuffle(to_run) + offered[route] = {c["step"]: [r["field"] for r in c["readings"]] for c in to_run} + measured: dict[str, Any] = {} + for key in sorted(CARDS): + rows = {m.field: {k: v for k, v in o.items() if k != "observed" or v != "not_measured"} + for m in CARDS[key] if (o := outcome_of(route, key, m))["n"] != [0, 0]} + if rows: + measured[key] = rows + fail_ids = route_fail_ids(records, route) + by_id = {r["case_id"]: r for r in records} + routes[route] = {"meaning": ROUTE_MEANING.get(route, ""), "n_fail": len(fail_ids), + "fail_by_gold": dict(sorted(Counter(by_id[c]["stratum"] for c in fail_ids).items())), + "measured": measured, "to_run": to_run} + previous = [] + if explanation_sets and explanation_sets[-1].hypotheses: + prev = explanation_sets[-1] + for hid, row in check(prev.hypotheses, outcome_of).items(): + h = next(x for x in prev.hypotheses if x.id == hid) + previous.append({"id": hid, "route": h.route, "claim": h.claim, "state": row["state"], + "verdicts": [{"step": p["step"], "reading": p["reading"], "predicted": p["predicted"], + "observed": p["outcome"].get("observed"), "verdict": p["verdict"]} + for p in row["predictions"]]}) + context = { + "task": {"kind": task_kind, "controls_matched_on": stratum}, + "model_under_test": {k: model_identity.get(k) for k in ("spec", "backend")}, + "sample": {"revision": revision, "n_fail": len(draw.fail_ids), "n_pass": len(draw.pass_ids)}, + "checks": {"meaning": "FAIL vs PASS cases on which each route's check fired (fired/tested), " + "with the 95% interval of the difference", + **(revisions[-1]["signals"] if revisions else {})}, + "measured_meaning": "per reading: FAIL mean, control mean, n [FAIL, control], diff = FAIL - " + "control, its 95% interval, and the direction the whole interval lies in", + "routes": routes, "previous": previous, + } + return context, offered + + def n_asked() -> int: + return sum(1 for es in explanation_sets if es.source != "not_asked") + + def ask_reason(states: dict[str, list[dict[str, Any]]], growing: bool, verdicts: dict[str, Any], + current: "ExplanationSet | None") -> "str | None": + """Why the judge is asked now (``None`` = it is not). + + Explanations are about the routes, and an expansion revises the routes: the + judge is first asked once no expansion can follow (the sample has settled, + or the next one is over budget). It is asked again when the evidence has + decided a prediction since the last ask and a route with tools left has + fewer than two live explanations.""" + if growing: + plan = expansion_plan() + if plan is not None and run.over_budget(plan[3]) is None: + return None + with_cards = sorted(route for route, sts in states.items() + if any(st["state"] in ("open", "extend") and st["step"].name in CARDS for st in sts)) + if not with_cards or run.over_budget(None) is not None: + return None + if current is None: + return "the sample has settled: no expansion can follow" + new = _decided(verdicts) - current.decided_at_ask + thin = [route for route in with_cards if sum(1 for h in current.hypotheses if h.route == route + and verdicts[h.id]["state"] == "live") < 2] + if not new or not thin: + return None + return (f"the evidence decided {len(new)} prediction(s) since the last ask, and route(s) {thin} " + f"with tools left have fewer than two live explanations") + + def explain(records: list[dict[str, Any]], states: dict[str, list[dict[str, Any]]], + outcome_of: Callable[[str, str, Metric], dict[str, Any]], reason: str) -> ExplanationSet: + context, offered = explanation_request(records, states, outcome_of) + if not offered: + es = ExplanationSet(revision, "", offered=offered, source="not_asked", + error="no active route has a tool with readings to predict") + else: + assert explainer is not None + es = explainer.propose(out, revision, context, offered) + es.seen = {route: sorted(r["measured"]) for route, r in context["routes"].items()} + for axis in ("wall_sec", "usd"): + if es.cost.get(axis) is not None: + run.judge_cost[axis] = run.judge_cost.get(axis, 0.0) + float(es.cost[axis]) + if es.source in ("judge", "failed"): + ledger.cost({"kind": "judge", "key": es.key, "revision": revision, "source": es.source, + **es.cost}) + es.reason = reason + ledger.trace({"event": "explanations", "revision": revision, "key": es.key, "source": es.source, + "reason": reason, "error": es.error, "by_route": dict(Counter(h.route for h in es.hypotheses)), + "dropped": es.dropped, "cost": es.cost}) + say(f"[triage] explanations (revision {revision}): {es.source}, " + f"{dict(Counter(h.route for h in es.hypotheses)) or 'none'}" + (f" ({es.error})" if es.error else "")) + explanation_sets.append(es) + return es + + def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], + states: dict[str, list[dict[str, Any]]], growing: bool, live: list[Hypothesis] + ) -> tuple[list[Scored], list[dict[str, Any]], str]: + """Every feasible candidate with its value, what the budget filtered out, and the cost axis.""" + nonlocal expansion_note + # A batch-dependent step's reading is superseded by any later expansion, and no + # route reads it: while an expansion can still follow, running it is wasted. Its + # layer waits for it (a battery step) rather than falling back to another tool. units = coverage_units(states, records, run.evidence, layers, min_cover=min_cover) axis = axis_of(run.evidence) rates, wall_rates = method_rates(run.evidence, axis), method_rates(run.evidence, "wall_sec") @@ -659,8 +869,10 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] elif layer.route == "H" and any(by_id[c]["H"]["disagreements"] for c in fail_new): T, gap_ids = 1.0, [f"contradiction:{layer.rule_id}"] kind = "battery" if st.get("battery") else ("extend" if st["state"] == "extend" else "follow_up") + D, d_detail = disagreement(route, step.name, live) if live else (0.0, {}) cand = Scored(kind=kind, key=step.name, route=route, rule_id=layer.rule_id, - order=(ROUTE_ORDER.index(route), li), n_new_cases=len(todo), T=T, C=C, + order=(ROUTE_ORDER.index(route), li), n_new_cases=len(todo), D=D, T=T, C=C, + d_detail=d_detail, q=availability(step.analyzer, run.evidence), cost=estimate_cost(step, len(todo), run.evidence, axis, rates), gaps=gap_ids, units=touched, @@ -695,19 +907,33 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] return pool, filtered, axis if scheduler == "scored": + current: "ExplanationSet | None" = None while stop is None: records = triage(sample, run.evidence) summary = summarize(records) gaps = expansion_gaps(summary, records, min_cohort=min_cohort) if not revisions or revisions[-1]["revision"] != revision: revisions.append(_revision_row(revision, draw, summary, records, gaps)) - pool, filtered, axis = scored_pool(records, gaps) + states, growing = route_view(records, gaps) + outcome_of = outcomes_for(records) + # explanations a prediction already missed on leave the live set: D is recomputed + # from the evidence at every decision, without asking the judge again + verdicts = check(current.hypotheses, outcome_of) if current is not None else {} + if explainer is not None and n_asked() < explainer.max_asks: + reason = ask_reason(states, growing, verdicts, current) + if reason is not None: + current = explain(records, states, outcome_of, reason) + verdicts = check(current.hypotheses, outcome_of) + current.decided_at_ask = _decided(verdicts) + live = [h for h in (current.hypotheses if current is not None else []) if verdicts[h.id]["state"] == "live"] + pool, filtered, axis = scored_pool(records, gaps, states, growing, live) pick, why = choose(pool, decision_no=n_actions(), seed=seed, explore_every=explore_every, min_gain=min_gain) if pick is None: - stop = {"reason": "no_candidate" if why == "none" else "below_threshold", - "detail": ("no feasible candidate" if why == "none" else - f"no candidate reaches the gain floor {min_gain}"), + over = [f for f in filtered if not f["reason"].startswith("batch-dependent")] + stop = {"reason": "below_threshold" if why != "none" else "budget" if over else "no_candidate", + "detail": (f"no candidate reaches the gain floor {min_gain}" if why != "none" else + "every remaining candidate is over budget" if over else "no feasible candidate"), "best_gain": max((c.gain for c in pool), default=None), "filtered": filtered} break if n_actions() >= max_actions: @@ -719,6 +945,9 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] extra = {"choice": why, "scoring_version": SCORING_VERSION, "axis": axis, "U": round(pick.U, 6), "gain": round(pick.gain, 6), "candidates": [c.row() for c in ranked], "filtered": filtered, + **({"explanations": {"key": current.key, "revision": current.revision, + "states": {hid: v["state"] for hid, v in verdicts.items()}}} + if current is not None else {}), **({"soft_order_exception": f"{pick.rule_id} taken before open layer(s) {skipped} of route " f"{pick.route}: higher value"} if skipped else {})} if pick.kind == "expand": @@ -819,8 +1048,14 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] blocked=run.blocked) for row in active_routes(records, min_route_fail) if row["active"]} coverage = public_units(coverage_units(final_states, records, run.evidence, layers, min_cover=min_cover)) + final_outcome = outcomes_for(records) + outcomes = {route: {key: {m.field: final_outcome(route, key, m) for m in CARDS[key]} + for key in sorted(CARDS) if run.evidence.get(key) is not None and run.evidence[key].chunks} + for route in final_states} executed_wall = sum(float((e.get("cost") or {}).get("wall_sec") or 0.0) for e in run.executions if not e.get("reused")) + asked = [es for es in explanation_sets if es.source in ("judge", "failed")] + judge_wall = sum(float(es.cost.get("wall_sec") or 0.0) for es in asked) report = { "policy": POLICY_VERSION, "scheduler": scheduler, @@ -843,20 +1078,36 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]] "decisions": decisions, "stop": stop, "cost": {**_cost_summary(run.executions, stage0_cost), "evidence": _evidence_cost(run), - "controller_sec": round(time.monotonic() - started - executed_wall, 3)}, + "judge": _judge_cost(explanation_sets), + "charged": {"wall_sec": round(run.charged("wall_sec"), 3), + **({"usd": round(run.charged("usd"), 6)} if budget_usd > 0 else {}), + "_note": "evidence at its first execution's cost plus judge calls: what the " + "budgets are checked against"}, + "controller_sec": round(time.monotonic() - started - executed_wall - judge_wall, 3)}, "coverage": coverage, + "outcomes": outcomes, + **({"explanations": _explanations_report(explanation_sets, explainer, final_outcome)} + if explainer is not None else {}), "summary": summary, "follow_ups": _follow_ups(followed, records, run, sample, rank_of, layers, answer_fn), "routes": _route_report(records, run, rank_of, layers, min_route_fail), "checks": _acceptance(battery, layers, run, draw, ledger), "cases": records, } - name = "triage_report" if scheduler == "rules" else f"triage_report.{scheduler}" + name = report_name(scheduler, explainer is not None) _write_json(out / f"{name}.json", report) (out / f"{name}.md").write_text(_markdown(report), encoding="utf-8") return report +def report_name(scheduler: str, explained: bool = False) -> str: + """``triage_report`` (rules), ``triage_report.scored``, or ``triage_report.scored_d`` (with D): + the arms of a comparison can share one probing directory and its ledger.""" + if scheduler == "rules": + return "triage_report" + return f"triage_report.{scheduler}" + ("_d" if explained else "") + + #: The MVP-0 entry point, now the same controller (no expansion unless ``max_fail`` is given). run_triage_mvp0 = run_triage @@ -897,6 +1148,46 @@ def _evidence_cost(run: _Run) -> dict[str, Any]: return out +def _decided(verdicts: dict[str, Any]) -> set[tuple[str, str, str]]: + """The predictions the evidence has decided (hit or miss), as (explanation, step, reading).""" + return {(hid, p["step"], p["reading"]) for hid, row in verdicts.items() for p in row["predictions"] + if p["verdict"] in ("hit", "miss")} + + +def _judge_cost(sets: list[ExplanationSet]) -> dict[str, Any]: + """Judge calls this invocation made, and the replies it read back (spent by the run that asked).""" + asked = [es for es in sets if es.source in ("judge", "failed")] + usd = [es.cost.get("usd") for es in asked if "api_usage" in es.cost] + return {"n_calls": len(asked), "n_failed": sum(1 for es in asked if es.source == "failed"), + "n_read_back": sum(1 for es in sets if es.source == "read_back"), + "wall_sec": round(sum(float(es.cost.get("wall_sec") or 0.0) for es in asked), 3), + **({"usd": round(sum(usd), 6) if all(v is not None for v in usd) else None} if usd else {})} + + +def _explanations_report(sets: list[ExplanationSet], explainer: Any, + outcome_of: Callable[[str, str, Metric], dict[str, Any]]) -> dict[str, Any]: + """Every explanation set with each prediction checked on the final evidence, and the tally.""" + rows, tally = [], Counter() + for es in sets: + final = check(es.hypotheses, outcome_of) + for hid, h in final.items(): + route = hid.split(".", 1)[0] + tally[h["state"]] += 1 + for p in h["predictions"]: + p["seen_when_predicted"] = p["step"] in es.seen.get(route, []) + tally[f"prediction_{p['verdict']}"] += 1 + if not p["seen_when_predicted"]: + tally[f"unseen_prediction_{p['verdict']}"] += 1 + rows.append({**es.to_dict(), "final": final}) + return {"version": EXPLAIN_VERSION, "judge": explainer.identity, "max_per_route": explainer.max_per_route, + "max_asks": explainer.max_asks, + "sets": rows, "tally": dict(sorted(tally.items())), + "_note": ("predictions are checked by code on the final evidence: hit = the 95% interval of FAIL - " + "control lies in the predicted region, miss = outside it; an explanation with a miss is " + "contradicted. A prediction on a step whose readings the judge already saw in part " + "(seen_when_predicted) is not out of sample; unseen_* counts the others")} + + def _battery_state(battery: "tuple[PlanStep, ...]", run: _Run, draw: Any) -> list[dict[str, Any]]: """Per battery step: which observations the current sample is read from.""" out = [] @@ -919,8 +1210,6 @@ def _follow_ups(followed: list[tuple[str, str, str]], records: list[dict[str, An rank_of: Callable[[str], Any], layers: "tuple[Layer, ...]", answer_fn: Any) -> list[dict[str, Any]]: """Descriptive readings of every follow-up that ran, on the route's current cases.""" - from evalrx.eval_agent.probing.rules import matched_controls - by_rule = {x.rule_id: x for x in layers} out = [] for route, rule_id, key in followed: @@ -1175,6 +1464,32 @@ def _markdown(report: dict[str, Any]) -> str: lines.append("") lines.append("_Means over the route's FAIL cases and their stratum-matched PASS controls; descriptive, " "no test, no mechanism named._") + expl = report.get("explanations") + if expl: + judge, judge_cost = expl["judge"], (report.get("cost") or {}).get("judge") or {} + lines += ["", "## Competing explanations (D)", "", + f"Judge `{judge.get('provider')}` / `{judge.get('model')}`: {judge_cost.get('n_calls', 0)} call(s) " + f"({judge_cost.get('n_failed', 0)} failed), {judge_cost.get('wall_sec', 0)} s" + + (f", USD {judge_cost['usd']}" if judge_cost.get("usd") is not None else "") + + f"; {judge_cost.get('n_read_back', 0)} read back. Tally on the final evidence: {expl['tally']}."] + for i, es in enumerate(expl["sets"]): + lines += ["", f"### Ask {i + 1} (revision {es['revision']}): {es['source']}" + + (f" ({es['error']})" if es.get("error") else ""), "", f"Asked because {es['reason']}.", ""] + if not es["hypotheses"]: + lines.append("No explanation." + (f" Dropped: {es['dropped']}." if es["dropped"] else "")) + continue + lines += ["| explanation | claim | state | predictions: predicted -> observed (verdict) |", + "|---|---|---|---|"] + for h in es["hypotheses"]: + final = es["final"][h["id"]] + preds = "; ".join(f"{p['step']}.{p['reading']}: {p['predicted']} -> " + f"{p['outcome'].get('observed')} ({p['verdict']}" + + (", seen" if p.get("seen_when_predicted") else "") + ")" + for p in final["predictions"]) or "none explicit" + lines.append(f"| {h['id']} | {h['claim']} | {final['state']} | {preds} |") + if es["dropped"]: + lines += ["", f"Dropped from the reply: {es['dropped']}."] + lines += ["", f"_{expl['_note']}._"] if report["routes"]: lines += ["", "## Route layers when the run stopped", "", "| route | FAIL | active | layer | state | via / next | passed over |", "|---|---:|---|---|---|---|---|"] @@ -1184,7 +1499,7 @@ def _markdown(report: dict[str, Any]) -> str: lines.append(f"| {row['route']} | {row['n_fail']} | {row['active']} | {st['rule_id']} | {st['state']} " f"| {st.get('via') or st.get('key') or '-'} | {passed or '-'} |") lines += ["", "## Checks", ""] - for name, check in report["checks"].items(): - lines.append(f"- `{name}`: {check}") + for name, held in report["checks"].items(): + lines.append(f"- `{name}`: {held}") lines.append("") return "\n".join(lines) diff --git a/evalrx/eval_agent/probing/explanations.py b/evalrx/eval_agent/probing/explanations.py new file mode 100644 index 00000000..c1377b69 --- /dev/null +++ b/evalrx/eval_agent/probing/explanations.py @@ -0,0 +1,483 @@ +"""MVP-3b: competing explanations, their predictions per tool, and the D they give a candidate. + +The chain's judge (the model ``runner.build_judge`` builds for M1-M5) is asked, +for every active route, for up to ``max_per_route`` local explanations of why +that route's FAIL cases fail. It is asked once the sample has settled (an +expansion revises the routes, as it supersedes batch-dependent readings), and +again, up to ``max_asks`` times in all, when the evidence has decided a +prediction and a route with tools left has fewer than two live explanations; +each ask sees the previous explanations' verdicts. For each tool still to run +on the route, every explanation predicts the direction of the tool's readings +on the route's FAIL cases against their PASS controls: + +* ``up``: FAIL mean - control mean > the reading's band; +* ``down``: < -band; +* ``same``: within +-band; +* ``unknown``: the explanation does not say. + +The readings, their meaning, sign and band are fixed here, per step, in +``CARDS``: the judge picks a direction, never the metric, the comparison or +the threshold. Code, not the judge, checks the predictions against the +evidence (``verdict``): a prediction is a hit when the 95% interval of the +difference lies inside its region, a miss when it lies outside, and +undetermined otherwise. An explanation with a miss is contradicted and leaves +the live set; one without any explicit prediction is untestable and is not in +it either. + +``D(a)`` for a candidate on route r is the share of pairs of r's live +explanations whose explicit predictions for that step conflict on at least +one reading; a pair with an ``unknown`` counts in the denominator only. Zero +or one live explanation gives ``D = 0``. Confidence the judge states is not +asked for and never weights anything. D is a disagreement heuristic, not a +posterior or an information gain. + +The judge sees the route summaries and readings of EXPLORE only, never a +case's content, media or CONFIRM. Each call's prompt, reply and cost are +stored under ``explanations/.json``, keyed by the prompt and the judge's +identity, so a resumed run reads the same reply back instead of asking again +(a call that raised is not stored: it is asked again). +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import time +from dataclasses import dataclass, field +from itertools import combinations +from pathlib import Path +from typing import Any, Callable + +from evalrx.eval_agent.probing.metering import usage_counters, usage_delta +from evalrx.eval_agent.probing.triage import difference_interval + +EXPLAIN_VERSION = "mvp3-explain-1" +DIRECTIONS = ("up", "down", "same", "unknown") +_ALIASES = {"↑": "up", "↓": "down", "≈": "same", "=": "same", "~": "same", "?": "unknown", + "higher": "up", "lower": "down", "increase": "up", "decrease": "down", "none": "unknown"} +MIN_N = 2 # cases per side before an interval is computed + + +@dataclass(frozen=True) +class Metric: + """One reading a prediction may be about: the step's per-case field, compared FAIL - control.""" + + field: str + meaning: str + band: float + kind: str = "mean" # "mean" (Welch interval) | "rate" (0/1 per case, Newcombe interval) + + def card(self) -> dict[str, Any]: + return {"field": self.field, "meaning": self.meaning, "band": self.band, + "kind": "share of cases" if self.kind == "rate" else "mean"} + + +def _rate(field_: str, meaning: str, band: float = 0.1) -> Metric: + return Metric(field_, meaning, band, "rate") + + +_MARGIN = "the gold first-token logit margin (gold vs its strongest competitor, fixed on the clean run)" + +#: The readings each step's predictions may name, by step key (``PlanStep.name``). +#: Bands are fixed before any run: 0.1 for shares of cases, 0.5 for logit +#: margins, otherwise in the reading's own units. Steps without a card get no +#: predictions (D = 0): the H re-ask and continuation run on FAIL cases only, +#: so their readings have no PASS control to compare with. +CARDS: dict[str, tuple[Metric, ...]] = { + # N: does the media path carry the gold answer + "attention_knockout": ( + Metric("ko_delta_full", f"{_MARGIN}, clean minus with text-to-media attention cut in every layer; " + ">0 = the media reading supported gold", 0.5), + Metric("ko_delta_late", "the same with the cut in the last third of layers only", 0.5)), + "causal_trace": ( + Metric("ct_media_effect", f"{_MARGIN}, clean minus with the media embeddings noised; >0 = the media " + "supported gold", 0.5), + _rate("ct_effect_traceable", "the noising moved the margin by at least 1 logit")), + "attention_temperature": ( + Metric("tt_slope", "change of the gold margin per log-unit of attention temperature over the media " + "(flat minus sharp over ln 4); <0 = sharper focus on the media helps gold", 0.25), + Metric("tt_delta_sharp", f"{_MARGIN} with media attention sharpened (temperature 0.5) minus clean", 0.5), + Metric("tt_media_entropy", "normalised entropy of text-to-media attention (1 = spread evenly)", 0.05)), + "attention_sensitivity": ( + Metric("rw_slope", "change of the gold margin per log-unit of media attention scaling (x2 vs x0.5); " + ">0 = more attention to the media helps gold", 0.25), + Metric("rw_delta_up", f"{_MARGIN} with media attention doubled minus clean", 0.5)), + "describe_first": ( + _rate("changed_describe_first", "the answer changes when asked to describe the media first"), + _rate("fixed_describe_first", "wrong before, right after describing first")), + # U: is the answer near a tie, does it follow content + "logprob_entropy": ( + Metric("mean_top_entropy", "entropy (nats) over the top alternatives per output token, mean; " + "higher = less certain", 0.05), + Metric("min_token_logprob", "lowest output-token log-probability; lower = a closer call", 0.1)), + "self_consistency_n10": ( + Metric("consistency", "share of 10 samples giving the modal answer; lower = less stable", 0.05),), + "format_sensitivity": ( + Metric("format_flip_rate", "share of option rotations whose chosen content differs from the modal " + "content; higher = the answer does not follow content", 0.1), + Metric("positional_bias", "share of rotations choosing the same letter; higher = position, not " + "content", 0.1)), + # S: where the stable error sits + "prompt_threshold": ( + _rate("changed_sensitive", "the answer changes when told not to default to a negative answer"), + _rate("fixed_sensitive", "wrong before, right after that instruction")), + "gradcam": ( + Metric("gc_media_grad_share", "share of gradient x activation on the media tokens (at mid depth) of " + "the gold margin; low = the margin hinges on the text", 0.05), + Metric("gc_top5_share", "share of the media map's positive mass in its top 5% of positions; " + "higher = more concentrated", 0.05), + Metric("gc_entropy", "normalised entropy of the media map (1 = diffuse)", 0.05)), + "generic_attention": ( + Metric("rel_media_share", "share of propagated attention relevance of the gold margin on the media " + "tokens; low = built from the text", 0.05), + Metric("rel_top5_share", "share of the media relevance map in its top 5% of positions", 0.05), + Metric("rel_entropy", "normalised entropy of the media relevance map (1 = diffuse)", 0.05)), + "embed_lens": ( + Metric("el_query_sim", "cosine of the case's own question word to its nearest media token, late in " + "the stack; higher = the object is readable off the media", 0.02), + Metric("el_frac_specific", "share of media tokens decoding to case-specific (not recurring, not " + "high-norm) words", 0.05)), + "patchscope": ( + Metric("ps_peak_prob", "highest probability of the gold answer read off the answer position at any " + "layer", 0.05), + Metric("ps_late_drop", "that peak minus the output's gold probability; >0 = gold was more readable " + "mid-stack than at the output", 0.05), + Metric("ps_media_query_share", "share of media-token readouts that are the case's question word", 0.05)), + "tuned_lens": ( + Metric("tl_late_drop", "peak minus final probability of the model's own final answer across fitted " + "layer readouts (not gold)", 0.05), + Metric("tl_decision_frac", "relative depth from which every readout agrees with the final answer; " + "later = decided near the top", 0.05)), + "layer_contrast": ( + Metric("contrast_margin", "log-prob of the final answer at the output minus at the most divergent " + "earlier layer; <0 = stronger earlier, suppressed late", 0.25), + Metric("layer_agreement_frac", "share of upper layers whose top-1 already is the final answer", 0.05)), + "media_drop": ( + _rate("grounded_in_image", "the answer changes when the image is removed"), + _rate("grounded_in_audio", "the answer changes when the audio is removed")), +} + + +# -- checking predictions -------------------------------------------------------------------- + +_T975 = (12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, + 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, + 2.045, 2.042) + + +def _t975(df: float) -> float: + """Two-sided 95% Student-t quantile at ``floor(df)`` (conservative), normal beyond 120.""" + k = max(1, int(math.floor(df))) + if k <= 30: + return _T975[k - 1] + return 2.021 if k < 60 else 2.000 if k < 120 else 1.960 + + +def _mean(xs: list[float]) -> float: + return sum(xs) / len(xs) + + +def difference(fail: list[float], control: list[float], kind: str) -> "tuple[float, list[float]] | None": + """``(FAIL mean - control mean, 95% interval)``; ``None`` below ``MIN_N`` cases a side.""" + if len(fail) < MIN_N or len(control) < MIN_N: + return None + diff = _mean(fail) - _mean(control) + if kind == "rate": + ci = difference_interval(sum(1 for x in fail if x >= 0.5), len(fail), + sum(1 for x in control if x >= 0.5), len(control)) + return diff, list(ci or [diff, diff]) + vf = sum((x - _mean(fail)) ** 2 for x in fail) / (len(fail) - 1) / len(fail) + vc = sum((x - _mean(control)) ** 2 for x in control) / (len(control) - 1) / len(control) + se = math.sqrt(vf + vc) + if se == 0.0: + return diff, [diff, diff] + df = (vf + vc) ** 2 / ((vf ** 2 / (len(fail) - 1) if vf else 0.0) + (vc ** 2 / (len(control) - 1) if vc else 0.0)) + half = _t975(df) * se + return diff, [diff - half, diff + half] + + +def observed(ci: list[float], band: float) -> str: + """The direction the whole interval lies in, else ``undetermined``.""" + lo, hi = ci + if lo > band: + return "up" + if hi < -band: + return "down" + if lo >= -band and hi <= band: + return "same" + return "undetermined" + + +def verdict(direction: str, ci: "list[float] | None", band: float) -> str: + """``hit`` (the interval inside the predicted region), ``miss`` (outside it) or ``undetermined``.""" + if ci is None or direction not in ("up", "down", "same"): + return "undetermined" + lo, hi = ci + if direction == "up": + return "hit" if lo > band else "miss" if hi <= band else "undetermined" + if direction == "down": + return "hit" if hi < -band else "miss" if lo >= -band else "undetermined" + return "hit" if -band <= lo and hi <= band else "miss" if lo > band or hi < -band else "undetermined" + + +def outcome(values: "dict[str, dict[str, Any]]", fail_ids: list[str], control_ids: list[str], + metric: Metric) -> dict[str, Any]: + """The reading's FAIL-vs-control difference on these cases, from per-case ``follow_up_values``.""" + def take(ids: list[str]) -> list[float]: + return [float(values[c]["values"][metric.field]) for c in ids + if values.get(c, {}).get("state") == "measured" and metric.field in values[c]["values"]] + + f, c = take(fail_ids), take(control_ids) + out: dict[str, Any] = {"n": [len(f), len(c)]} + if f: + out["fail_mean"] = round(_mean(f), 4) + if c: + out["control_mean"] = round(_mean(c), 4) + res = difference(f, c, metric.kind) + if res is None: + out["observed"] = "not_measured" if not f and not c else "undetermined" + return out + diff, ci = res + out.update(diff=round(diff, 4), ci95=[round(ci[0], 4), round(ci[1], 4)], observed=observed(ci, metric.band)) + return out + + +# -- explanations ------------------------------------------------------------------------------- + + +@dataclass +class Hypothesis: + id: str + route: str + claim: str + predictions: dict[str, dict[str, str]] # step key -> reading -> direction (explicit ones only) + basis: str = "" + + def explicit(self) -> list[tuple[str, str, str]]: + return [(step, f, d) for step, by in sorted(self.predictions.items()) for f, d in sorted(by.items())] + + def to_dict(self) -> dict[str, Any]: + return {"id": self.id, "route": self.route, "claim": self.claim, "basis": self.basis, + "predictions": self.predictions} + + +@dataclass +class ExplanationSet: + """One judge call's explanations for every active route at one sample revision.""" + + revision: int + key: str + hypotheses: list[Hypothesis] = field(default_factory=list) + offered: dict[str, dict[str, list[str]]] = field(default_factory=dict) # route -> step -> readings + dropped: list[dict[str, Any]] = field(default_factory=list) + seen: dict[str, list[str]] = field(default_factory=dict) # route -> steps with readings shown when asked + reason: str = "" # why the judge was asked + decided_at_ask: set = field(default_factory=set) # predictions already decided when asked + source: str = "judge" # "judge" | "read_back" | "failed" + cost: dict[str, Any] = field(default_factory=dict) + error: "str | None" = None + + def to_dict(self) -> dict[str, Any]: + return {"revision": self.revision, "key": self.key, "source": self.source, "reason": self.reason, + "error": self.error, + "cost": self.cost, "offered": self.offered, "seen": self.seen, "dropped": self.dropped, + "hypotheses": [h.to_dict() for h in self.hypotheses]} + + +Outcomes = Callable[[str, str, Metric], dict[str, Any]] # (route, step key, metric) -> outcome + + +def check(hypotheses: list[Hypothesis], outcome_of: Outcomes) -> dict[str, dict[str, Any]]: + """Every hypothesis' state on the current evidence: ``live`` / ``contradicted`` / ``untestable``, + with each explicit prediction's verdict.""" + out = {} + for h in hypotheses: + rows = [] + for step, name, direction in h.explicit(): + metric = next(m for m in CARDS[step] if m.field == name) + o = outcome_of(h.route, step, metric) + rows.append({"step": step, "reading": name, "predicted": direction, "band": metric.band, + "outcome": o, "verdict": verdict(direction, o.get("ci95"), metric.band)}) + state = ("untestable" if not rows else + "contradicted" if any(r["verdict"] == "miss" for r in rows) else "live") + out[h.id] = {"state": state, "predictions": rows} + return out + + +def disagreement(route: str, step: str, live: list[Hypothesis]) -> tuple[float, dict[str, Any]]: + """``D`` of running *step* on *route*, and which pairs of live explanations it separates.""" + hyps = [h for h in live if h.route == route] + if len(hyps) < 2: + return 0.0, {"n_live": len(hyps), "n_pairs": 0, "conflicting": []} + pairs = list(combinations(hyps, 2)) + conflicting = [] + for a, b in pairs: + pa, pb = a.predictions.get(step, {}), b.predictions.get(step, {}) + on = sorted(f for f in set(pa) & set(pb) if pa[f] != pb[f]) + if on: + conflicting.append({"pair": [a.id, b.id], "readings": on}) + return len(conflicting) / len(pairs), {"n_live": len(hyps), "n_pairs": len(pairs), "conflicting": conflicting} + + +# -- the judge call --------------------------------------------------------------------------------- + +_INSTRUCTIONS = """\ +You are helping to triage the errors of a model under test on a benchmark. A +controller has run checks on a sample of the model's EXPLORE cases and grouped +the wrong (FAIL) cases into routes; each route's FAIL cases are compared with +correct (PASS) cases of the same gold answer (its controls). Some tools have not +run on a route yet. The controller will run them one at a time and wants to run +first the ones whose result would tell competing explanations apart. + +For every route listed under "routes", propose at most {max_per_route} competing +local explanations of why that route's FAIL cases fail. Local: about these cases +and the mechanisms the tools can see, not the model in general. Competing: they +should differ in what at least one listed tool would show. Do not split one +explanation into variants only to disagree, and propose fewer (or none) when you +have no real alternative. + +For each explanation and each tool listed under the route's "to_run", predict +for each of its readings the direction of (FAIL mean - control mean): + "up" the difference is above +band + "down" the difference is below -band + "same" the difference is within +-band + "unknown" the explanation does not imply a direction (the default) +Only predict a direction the explanation implies; a wrong confident prediction +counts against it. Readings measured so far are under "measured"; use them, and +the previous explanations' verdicts under "previous", to revise. + +Answer with JSON only, no prose, in this shape: +{{"routes": {{"": [{{"id": "h1", "claim": "", + "basis": "", + "predictions": {{"": {{"": "up|down|same|unknown"}}}}}}]}}}} + +Evidence (JSON): +""" + + +def prompt(context: dict[str, Any], max_per_route: int) -> str: + return _INSTRUCTIONS.format(max_per_route=max_per_route) + json.dumps(context, indent=1, sort_keys=True, + ensure_ascii=False) + + +def _json_object(text: str) -> Any: + text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.S) + try: + return json.loads(text) + except json.JSONDecodeError: + start, end = text.find("{"), text.rfind("}") + if start < 0 or end <= start: + raise + return json.loads(text[start:end + 1]) + + +def parse(reply: str, offered: dict[str, dict[str, list[str]]], + max_per_route: int) -> tuple[list[Hypothesis], list[dict[str, Any]]]: + """The valid explanations in *reply*, and what was dropped and why. + + Kept: routes and steps that were offered, readings on the step's card, + the four directions (arrows accepted). A second explanation with the same + explicit predictions as an earlier one is a duplicate (it can never be told + apart from it); explanations beyond *max_per_route* are dropped. + """ + dropped: list[dict[str, Any]] = [] + try: + data = _json_object(reply) + except (json.JSONDecodeError, ValueError) as exc: + return [], [{"what": "reply", "reason": f"not JSON: {exc}"}] + routes = data.get("routes") if isinstance(data, dict) else None + if not isinstance(routes, dict): + return [], [{"what": "reply", "reason": "no 'routes' object"}] + out: list[Hypothesis] = [] + for route, items in sorted(routes.items()): + if route not in offered: + dropped.append({"what": f"route {route}", "reason": "not offered"}) + continue + if not isinstance(items, list): + dropped.append({"what": f"route {route}", "reason": "not a list"}) + continue + kept: list[Hypothesis] = [] + for i, item in enumerate(items): + if not isinstance(item, dict) or not str(item.get("claim") or "").strip(): + dropped.append({"what": f"{route}[{i}]", "reason": "no claim"}) + continue + hid = f"{route}.{str(item.get('id') or f'h{i + 1}').strip()}" + if any(h.id == hid for h in kept): + hid = f"{route}.h{i + 1}" + preds: dict[str, dict[str, str]] = {} + for step, by in (item.get("predictions") or {}).items(): + if step not in offered[route]: + dropped.append({"what": f"{hid} {step}", "reason": "step not offered on this route"}) + continue + for reading, raw in (by or {}).items() if isinstance(by, dict) else (): + d = str(raw).strip().lower() + d = _ALIASES.get(d, d) + if reading not in offered[route][step]: + dropped.append({"what": f"{hid} {step}.{reading}", "reason": "reading not on the card"}) + elif d not in DIRECTIONS: + dropped.append({"what": f"{hid} {step}.{reading}", "reason": f"direction {raw!r}"}) + elif d != "unknown": + preds.setdefault(step, {})[reading] = d + h = Hypothesis(id=hid, route=route, claim=str(item["claim"]).strip(), predictions=preds, + basis=str(item.get("basis") or "").strip()) + if preds and any(k.predictions == preds for k in kept): + dropped.append({"what": hid, "reason": "same explicit predictions as an earlier explanation"}) + continue + if len(kept) >= max_per_route: + dropped.append({"what": hid, "reason": f"more than {max_per_route} explanations"}) + continue + kept.append(h) + out += kept + return out, dropped + + +class Explainer: + """Asks a text judge (``generate(prompt) -> str``) for explanations, through the run's store. + + *identity* names the judge (provider, model, effort) and is part of the + store key; *price_fn* turns the judge's usage counters into USD when it + reports them (an API judge). A CLI judge reports neither: its calls are + charged in wall seconds only. + """ + + def __init__(self, judge: Any, *, identity: dict[str, Any], max_per_route: int = 3, max_asks: int = 3, + price_fn: "Callable[[dict[str, Any] | None], float | None] | None" = None) -> None: + self.judge, self.identity, self.price_fn = judge, identity, price_fn + self.max_per_route, self.max_asks = max_per_route, max_asks + + def propose(self, root: "str | Path", revision: int, context: dict[str, Any], + offered: dict[str, dict[str, list[str]]]) -> ExplanationSet: + text = prompt(context, self.max_per_route) + key = hashlib.sha1(json.dumps({"version": EXPLAIN_VERSION, "judge": self.identity, "prompt": text}, + sort_keys=True).encode()).hexdigest()[:16] + store = Path(root) / "explanations" + store.mkdir(parents=True, exist_ok=True) + path = store / f"{key}.json" + if path.is_file(): + rec = json.loads(path.read_text(encoding="utf-8")) + hyps, dropped = parse(rec["reply"], offered, self.max_per_route) + return ExplanationSet(revision, key, hyps, offered=offered, dropped=dropped, source="read_back", + cost=rec["cost"]) + before = usage_counters(self.judge) + started = time.monotonic() + try: + reply = str(self.judge.generate(text)) + except Exception as exc: # noqa: BLE001 - a judge failure leaves D at 0 for this revision + cost = {"wall_sec": round(time.monotonic() - started, 3), "calls": {"judge": 1}} + return ExplanationSet(revision, key, offered=offered, source="failed", cost=cost, + error=f"{type(exc).__name__}: {exc}") + cost: dict[str, Any] = {"wall_sec": round(time.monotonic() - started, 3), "calls": {"judge": 1}} + usage = usage_delta(before, usage_counters(self.judge)) + if usage is not None: + cost["api_usage"] = usage + cost["usd"] = self.price_fn(usage) if self.price_fn is not None else None + rec = {"version": EXPLAIN_VERSION, "judge": self.identity, "revision": revision, "prompt": text, + "reply": reply, "cost": cost} + tmp = path.with_suffix(".json.tmp") + tmp.write_text(json.dumps(rec, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, path) + hyps, dropped = parse(reply, offered, self.max_per_route) + return ExplanationSet(revision, key, hyps, offered=offered, dropped=dropped, source="judge", cost=cost) diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/probing/scoring.py index aa197ea2..ce496c58 100644 --- a/evalrx/eval_agent/probing/scoring.py +++ b/evalrx/eval_agent/probing/scoring.py @@ -7,9 +7,12 @@ axis' metering floor. The definitions are the design's first executable ones, written down so a run can show why each action won: -* **D** (prediction disagreement) needs competing explanations with predictions - per tool; none are proposed yet, so ``D = 0`` and actions earn budget through - T and C (as the design allows with zero or one explanation). +* **D** (prediction disagreement): with an explainer, the share of pairs of the + route's live competing explanations whose predictions for the step conflict + (:mod:`.explanations`); the explanations come once per sample revision, and + an explanation a prediction already missed on leaves the live set at the next + decision. Without one, or with fewer than two live explanations, ``D = 0`` + and actions earn budget through T and C. An expansion's D is 0. * **T** (evidence gap): 1 completes a recorded gap — a layer done on a smaller sample whose step only has to run on the route's new cases (a ``reuse`` step), or a contradiction between two readings of the same check; 0.5 is an @@ -55,7 +58,7 @@ from evalrx.eval_agent.probing.actions import OK, UNSUPPORTED, PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -SCORING_VERSION = "mvp3-score-1" +SCORING_VERSION = "mvp3-score-2" BACKWARD_FORWARDS = 3.0 @@ -87,6 +90,7 @@ class Scored: U: float = 0.0 gaps: list[str] = field(default_factory=list) units: list[str] = field(default_factory=list) + d_detail: dict[str, Any] = field(default_factory=dict) # which live explanations D separates note: str = "" payload: Any = None # the proposal / expansion plan; not serialised diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index 1ce63dd3..2e5b30e1 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -165,3 +165,28 @@ def run(loop, data): monkeypatch.setattr(AgenticDiagnoseLoop, 'run', run) with pytest.raises(ReachedController): runner.run(args, get(dataset), resolved) + + +def test_triage_explainer_is_the_chain_judge_and_never_the_model_under_test(monkeypatch): + from evalrx.eval_agent.probing.explanations import Explainer + + seen = {} + + def build(args): + seen.update(allow_codegen=args.allow_codegen, skip_m5=args.skip_m5) + return SimpleNamespace(generate=lambda prompt: 'OK'), 'llm', args.judge_model or 'gemini-2.5-flash', () + + monkeypatch.setattr(runner, 'build_judge', build) + spec = SimpleNamespace(key='qwen3.5-0.8b', hf_repo='Qwen/Qwen3.5-0.8B') + args = build_parser().parse_args(['--judge-provider', 'gemini', '--m1-policy', 'triage_active', + '--triage-scheduler', 'scored', '--triage-explanations', 'judge']) + explainer = runner._triage_explainer(args, spec) + assert isinstance(explainer, Explainer) and seen == {'allow_codegen': False, 'skip_m5': True} + assert explainer.identity == {'provider': 'gemini', 'model': 'gemini-2.5-flash', 'effort': 'high'} + rules = build_parser().parse_args(['--triage-explanations', 'judge']) + with pytest.raises(SystemExit, match='--triage-scheduler scored'): + runner._triage_explainer(rules, spec) + same = build_parser().parse_args(['--judge-provider', 'gemini', '--judge-model', 'Qwen/Qwen3.5-0.8B', + '--triage-scheduler', 'scored', '--triage-explanations', 'judge']) + with pytest.raises(SystemExit, match='model under test'): + runner._triage_explainer(same, spec) diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_probing_mvp2.py index fa2f4a98..ba8e25d9 100644 --- a/tests/test_eval_agent/test_probing_mvp2.py +++ b/tests/test_eval_agent/test_probing_mvp2.py @@ -314,7 +314,7 @@ def summary(k_fail, k_pass, n): assert next_size(8, 32, 100) == 16 and next_size(16, 32, 20) == 20 and next_size(32, 32, 100) is None -def test_budget_estimates_come_from_the_same_steps_earlier_seconds(tmp_path): +def test_budget_estimates_come_from_the_same_steps_earlier_seconds_and_charge_the_evidence(tmp_path): from evalrx.eval_agent.probing.controller import _Run from evalrx.eval_agent.probing.ledger import Ledger @@ -326,12 +326,20 @@ def test_budget_estimates_come_from_the_same_steps_earlier_seconds(tmp_path): obs = _obs("sc", ["c0-0", "c1-0"]) obs.cost = {"wall_sec": 4.0, "calls": {"generate": 10}} run.evidence[step.name] = StepEvidence(step, [obs]) - ledger.cost({"kind": "action", "wall_sec": 4.0}) assert run.estimate_sec(step, 4) == 8.0 assert "exceeds the 6.0s left" in run.over_budget(8.0) assert run.over_budget(5.0) is None - ledger.cost({"kind": "action", "wall_sec": 7.0}) - assert "spent" in run.over_budget(None) + # what another invocation spent on the same ledger is not this run's evidence + ledger.cost({"kind": "action", "wall_sec": 70.0}) + assert run.over_budget(5.0) is None + other = _obs("sc2", ["c2-0"]) + other.cost = {"wall_sec": 7.0, "calls": {"generate": 5}} + run.evidence[step.name].add(other) + assert run.charged("wall_sec") == 11.0 and "spent" in run.over_budget(None) + run.evidence[step.name].add(other) # one observation read twice is charged once + assert run.charged("wall_sec") == 11.0 + run.judge_cost["wall_sec"] = 2.0 + assert run.charged("wall_sec") == 13.0 # -- the reuse declarations hold -------------------------------------------------------- diff --git a/tests/test_eval_agent/test_probing_mvp3b.py b/tests/test_eval_agent/test_probing_mvp3b.py new file mode 100644 index 00000000..dc9076fe --- /dev/null +++ b/tests/test_eval_agent/test_probing_mvp3b.py @@ -0,0 +1,274 @@ +"""MVP-3b: D from competing explanations the judge proposes, checked by code. + +* a prediction is a hit when the 95% interval of FAIL - control lies in its + region, a miss when it lies outside, undetermined otherwise; +* D is the share of pairs of a route's live explanations whose predictions for + the step conflict; ``unknown`` counts in the denominator only; +* the judge's reply keeps only offered steps, card readings and the four + directions, and a duplicate explanation is dropped; +* the scored scheduler asks once the sample has settled and again when the + evidence thins a route's live explanations, reads a stored reply back on + resume, never shows the judge a case, and charges its calls to the budget. +""" + +from __future__ import annotations + +import json + +import pytest + +from evalrx.eval_agent.probing import run_triage +from evalrx.eval_agent.probing.explanations import ( + CARDS, + Explainer, + Hypothesis, + Metric, + check, + difference, + disagreement, + observed, + outcome, + parse, + verdict, +) +from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table + + +def test_verdicts_follow_the_interval_against_the_predicted_region(): + assert observed([0.2, 0.4], 0.1) == "up" and observed([-0.05, 0.08], 0.1) == "same" + assert observed([-0.4, -0.2], 0.1) == "down" and observed([-0.05, 0.3], 0.1) == "undetermined" + assert verdict("up", [0.2, 0.4], 0.1) == "hit" and verdict("up", [-0.3, 0.1], 0.1) == "miss" + assert verdict("up", [0.05, 0.3], 0.1) == "undetermined" + assert verdict("same", [-0.05, 0.08], 0.1) == "hit" and verdict("same", [0.15, 0.3], 0.1) == "miss" + assert verdict("down", [-0.05, 0.3], 0.1) == "miss" and verdict("unknown", [0.2, 0.4], 0.1) == "undetermined" + assert verdict("up", None, 0.1) == "undetermined" + diff, ci = difference([1.0, 1.2, 0.8, 1.0], [0.0, 0.2, -0.2, 0.0], "mean") + assert diff == pytest.approx(1.0) and ci[0] > 0.5 and ci[1] < 1.5 + diff, ci = difference([1, 1, 1, 0], [0, 0, 0, 0], "rate") + assert diff == 0.75 and ci[0] < 0.75 < ci[1] + assert difference([1.0], [0.0, 1.0], "mean") is None + + +def test_outcome_reads_the_cases_with_the_field_and_says_when_nothing_was_measured(): + m = Metric("x", "a reading", 0.1) + values = {"f1": {"state": "measured", "values": {"x": 1.0}}, "f2": {"state": "measured", "values": {"x": 1.0}}, + "f3": {"state": "untested", "reason": "failed"}, + "c1": {"state": "measured", "values": {"x": 0.0}}, "c2": {"state": "measured", "values": {"y": 3.0}}} + o = outcome(values, ["f1", "f2", "f3"], ["c1", "c2"], m) + assert o["n"] == [2, 1] and o["observed"] == "undetermined" and "ci95" not in o + assert outcome({}, ["f1"], ["c1"], m)["observed"] == "not_measured" + + +def _h(hid, route, **preds): + return Hypothesis(hid, route, f"claim {hid}", {k: dict(v) for k, v in preds.items()}) + + +def test_disagreement_is_the_share_of_live_pairs_whose_predictions_conflict(): + a = _h("S.h1", "S", gradcam={"gc_top5_share": "up"}) + b = _h("S.h2", "S", gradcam={"gc_top5_share": "down"}) + c = _h("S.h3", "S", patchscope={"ps_late_drop": "up"}) # unknown on gradcam + D, detail = disagreement("S", "gradcam", [a, b, c]) + assert D == pytest.approx(1 / 3) and detail["conflicting"] == [{"pair": ["S.h1", "S.h2"], + "readings": ["gc_top5_share"]}] + assert disagreement("S", "patchscope", [a, b, c])[0] == 0.0 + assert disagreement("S", "gradcam", [a])[0] == 0.0 + assert disagreement("N", "gradcam", [a, b])[0] == 0.0 # another route's explanations + + +def test_check_contradicts_on_a_miss_and_calls_an_explanation_without_predictions_untestable(): + a = _h("S.h1", "S", gradcam={"gc_top5_share": "up"}) + b = _h("S.h2", "S", gradcam={"gc_top5_share": "same"}) + c = _h("S.h3", "S") + seen = {"gc_top5_share": {"n": [17, 17], "ci95": [0.2, 0.4], "observed": "up"}} + states = check([a, b, c], lambda route, step, m: seen.get(m.field, {"n": [0, 0], "observed": "not_measured"})) + assert {k: v["state"] for k, v in states.items()} == {"S.h1": "live", "S.h2": "contradicted", + "S.h3": "untestable"} + assert states["S.h1"]["predictions"][0]["verdict"] == "hit" + + +def test_parse_keeps_offered_steps_card_readings_and_directions_and_drops_duplicates(): + offered = {"S": {"gradcam": ["gc_top5_share", "gc_entropy"]}, "N": {"attention_temperature": ["tt_slope"]}} + reply = "```json\n" + json.dumps({"routes": { + "S": [{"id": "h1", "claim": "concentrated off target", "predictions": { + "gradcam": {"gc_top5_share": "↑", "gc_entropy": "sideways", "gc_margin": "up"}, + "patchscope": {"ps_late_drop": "up"}}}, + {"id": "h2", "claim": "same as h1, reworded", "predictions": {"gradcam": {"gc_top5_share": "up"}}}, + {"id": "h3", "claim": "diffuse", "predictions": {"gradcam": {"gc_entropy": "up"}}}, + {"id": "h4", "claim": "nothing to say", "predictions": {"gradcam": {"gc_entropy": "unknown"}}}], + "U": [{"id": "h1", "claim": "not offered"}], + "N": [{"claim": ""}]}}) + "\n```" + hyps, dropped = parse(reply, offered, max_per_route=2) + assert [(h.id, h.predictions) for h in hyps] == [("S.h1", {"gradcam": {"gc_top5_share": "up"}}), + ("S.h3", {"gradcam": {"gc_entropy": "up"}})] + reasons = {d["what"]: d["reason"] for d in dropped} + assert reasons["route U"] == "not offered" and reasons["N[0]"] == "no claim" + assert reasons["S.h1 gradcam.gc_entropy"] == "direction 'sideways'" + assert reasons["S.h1 gradcam.gc_margin"] == "reading not on the card" + assert reasons["S.h1 patchscope"] == "step not offered on this route" + assert "same explicit predictions" in reasons["S.h2"] and "more than 2" in reasons["S.h4"] + assert parse("no json here", offered, 3) == ([], [{"what": "reply", "reason": parse("no json here", offered, + 3)[1][0]["reason"]}]) + assert parse(json.dumps({"x": 1}), offered, 3)[1] == [{"what": "reply", "reason": "no 'routes' object"}] + + +def test_every_card_reading_names_its_band_and_kind(): + for key, metrics in CARDS.items(): + assert metrics and len({m.field for m in metrics}) == len(metrics), key + assert all(m.band > 0 and m.kind in ("mean", "rate") and m.meaning for m in metrics), key + + +class _Judge: + """Two explanations per route that disagree on the first reading of every offered step.""" + + def __init__(self, fail=False): + self.prompts, self.fail = [], fail + + def generate(self, prompt): + self.prompts.append(prompt) + if self.fail: + raise RuntimeError("timed out") + ctx = json.loads(prompt[prompt.index("Evidence (JSON):") + len("Evidence (JSON):"):]) + routes = {} + for route, r in ctx["routes"].items(): + up = {c["step"]: {c["readings"][0]["field"]: "up"} for c in r["to_run"]} + same = {c["step"]: {c["readings"][0]["field"]: "same"} for c in r["to_run"]} + routes[route] = [{"id": "h1", "claim": "it moves", "predictions": up}, + {"id": "h2", "claim": "it does not", "predictions": same}] + return json.dumps({"routes": routes}) + + +def test_explainer_reads_a_stored_reply_back_and_asks_again_after_a_failure(tmp_path): + offered = {"S": {"gradcam": ["gc_top5_share"]}} + context = {"routes": {"S": {"to_run": [{"step": "gradcam", "readings": [{"field": "gc_top5_share"}]}]}}} + judge = _Judge() + first = Explainer(judge, identity={"provider": "stub", "model": "a"}).propose(tmp_path, 0, context, offered) + again = Explainer(judge, identity={"provider": "stub", "model": "a"}).propose(tmp_path, 0, context, offered) + assert (first.source, again.source, len(judge.prompts)) == ("judge", "read_back", 1) + assert [h.to_dict() for h in again.hypotheses] == [h.to_dict() for h in first.hypotheses] + assert again.cost == first.cost and first.cost["calls"] == {"judge": 1} + # another judge is another key + Explainer(judge, identity={"provider": "stub", "model": "b"}).propose(tmp_path, 0, context, offered) + assert len(judge.prompts) == 2 + broken = _Judge(fail=True) + failed = Explainer(broken, identity={"provider": "stub", "model": "c"}).propose(tmp_path, 0, context, offered) + assert failed.source == "failed" and "timed out" in failed.error and not failed.hypotheses + Explainer(broken, identity={"provider": "stub", "model": "c"}).propose(tmp_path, 0, context, offered) + assert len(broken.prompts) == 2 # a failure is not stored + + +def _explained(out, judge, **over): + return run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored", + explainer=Explainer(judge, identity={"provider": "stub", "model": "stub"}), **over)) + + +def test_scored_run_asks_once_the_sample_settles_and_resumes_without_asking(tmp_path): + cases, _ = _pope_like() + out = tmp_path / "p" + judge = _Judge() + report = _explained(out, judge) + last = report["revisions"][-1]["revision"] + (asked,) = report["explanations"]["sets"] + assert len(judge.prompts) == 1 and asked["source"] == "judge" and asked["revision"] == last == 1 + assert "settled" in asked["reason"] and len(list((out / "explanations").glob("*.json"))) == 1 + # before the sample settled, D is 0: the routes the explanations are about still change + for d in report["decisions"]: + if d.get("candidates") and d["revision"] < last: + assert all(c["D"] == 0.0 for c in d["candidates"]) and "explanations" not in d + scored = [c for d in report["decisions"] for c in d.get("candidates") or [] if c["kind"] != "expand"] + assert any(c["D"] == 1.0 and c["d_detail"]["conflicting"] for c in scored) + # the judge never sees a case: no case id, no question text, no CONFIRM + for p in judge.prompts: + assert not any(str(c.id) in p for c in cases) and "Is there a" not in p and "confirm" not in p.lower() + cost = report["cost"] + assert cost["judge"]["n_calls"] == 1 and cost["charged"]["wall_sec"] >= cost["judge"]["wall_sec"] + assert report["explanations"]["tally"]["live"] >= 2 and report["outcomes"] + assert not (out / "triage_report.scored.json").exists() # the D = 0 arm's report is not overwritten + md = (out / "triage_report.scored_d.md").read_text() + assert "## Competing explanations (D)" in md and "S.h1" in md + + again_judge = _Judge() + again = _explained(out, again_judge) + assert not again_judge.prompts and again["cost"]["judge"]["n_read_back"] == 1 + assert [(d["kind"], d.get("key")) for d in again["decisions"]] == [(d["kind"], d.get("key")) + for d in report["decisions"]] + + +def test_a_decided_prediction_that_thins_a_route_asks_the_judge_again(tmp_path, monkeypatch): + from evalrx.eval_agent.probing import LAYERS + from evalrx.eval_agent.probing.actions import PlanStep + from evalrx.eval_agent.probing.rules import Layer + + # the table model ignores wrappers: prompt_sensitivity is 0 on every case, so "up" misses at once + monkeypatch.setitem(CARDS, "wrapped", (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) + step = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "w": "Q: {prompt}"}}, "Z1", + "re-ask inside a wrapper", key="wrapped") + at = next(i for i, x in enumerate(LAYERS) if x.rule_id == "Sb") + layers = (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (step,)), *LAYERS[at:]) + judge = _Judge() + report = _explained(tmp_path / "a", judge, layers=layers) + first, second = report["explanations"]["sets"] + assert len(judge.prompts) == 2 and "settled" in first["reason"] and "fewer than two live" in second["reason"] + assert first["final"]["S.h1"]["state"] == "contradicted" and first["final"]["S.h2"]["state"] == "live" + previous = json.loads(judge.prompts[1][judge.prompts[1].index("Evidence (JSON):") + 16:])["previous"] + assert {p["id"]: p["state"] for p in previous}["S.h1"] == "contradicted" + assert "wrapped" not in second["offered"]["S"] # what ran is no longer offered + + +def test_a_failed_judge_call_leaves_D_at_zero_and_the_run_completes(tmp_path): + report = _explained(tmp_path / "f", _Judge(fail=True)) + sets = report["explanations"]["sets"] + assert sets and all(s["source"] == "failed" and "timed out" in s["error"] for s in sets) + assert all(c["D"] == 0.0 for d in report["decisions"] for c in d.get("candidates") or []) + assert report["cost"]["judge"]["n_failed"] == len(sets) and report["stop"]["reason"] + + +def test_the_rules_scheduler_does_not_take_an_explainer(tmp_path): + with pytest.raises(ValueError, match="scored scheduler"): + run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(tmp_path / "r", explainer=Explainer(_Judge(), identity={}))) + + +def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence(tmp_path): + from evalrx.eval_agent.probing.compare import compare, markdown + + out = tmp_path / "c" + rules = run_triage(_Table(_pope_like()[1]), _pope_like()[0], **_kw(out, max_fail=8, min_route_fail=1)) + explained = _explained(out, _Judge()) + diff = compare(rules, explained) + d = diff["discrimination"] + assert d["baseline"]["revision"] == d["other"]["revision"] == explained["explanations"]["sets"][-1]["revision"] + assert d["other"]["n_conflicting_pairs"] >= 1 and d["baseline"]["n_conflicting_pairs"] == d["other"][ + "n_conflicting_pairs"] + assert diff["judge"]["other"]["n_calls"] == 1 and "tells apart" in markdown(diff) + json.dumps(diff) + + +@pytest.mark.parametrize("scheduler", ["rules", "scored"]) +def test_a_budgeted_rerun_on_the_same_ledger_decides_as_the_run_that_executed(tmp_path, monkeypatch, scheduler): + import evalrx.eval_agent.probing.controller as controller + + real = controller.execute + + def metered(action, *args, **kwargs): # a second per case, so the budget binds the same way every run + obs = real(action, *args, **kwargs) + obs.cost["wall_sec"] = float(len(obs.planned_ids)) + return obs + + monkeypatch.setattr(controller, "execute", metered) + cases, table = _pope_like() + kw = dict(max_fail=8, min_route_fail=1, scheduler=scheduler) + full = run_triage(_Table(table), cases, **_kw(tmp_path / "full", **kw)) + budget = round(full["cost"]["charged"]["wall_sec"] * 0.8) + first = run_triage(_Table(table), cases, **_kw(tmp_path / "b", budget_sec=budget, **kw)) + assert any(e["status"] == "skipped" for e in first["executions"]) # the budget bound + assert first["cost"]["charged"]["wall_sec"] < full["cost"]["charged"]["wall_sec"] + # resumed on its own ledger, and run on the ledger of the unbudgeted run (which holds + # evidence the budget excludes): the same steps, skips and charge, without a model call + for out in ("b", "full"): + model = _Table(table) + again = run_triage(model, cases, **_kw(tmp_path / out, budget_sec=budget, **kw)) + assert model.n_generate == 0 and again["stop"] == first["stop"] + assert [(e["key"], e["status"], e.get("n_cases")) for e in again["executions"]] == [ + (e["key"], e["status"], e.get("n_cases")) for e in first["executions"]] + assert again["cost"]["charged"] == first["cost"]["charged"] From 0379f58e2bb9c387109c1389ec6c8e9bba4854f0 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:59:44 -0700 Subject: [PATCH 06/26] triage: chunked steps, spending by measured cost Steps run in chunks of --triage-chunk cases (default 8, FAIL and PASS alternating). The budget is checked before every chunk on the cost measured so far, so a step whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. Cost estimates no longer use per-call rates (calls_per_case is kept for reservations only): a step that has run is priced at its own measured cost per case in this run, one that has not at the run's median case when ranking and its most expensive case in budget checks. A cost calibration on Qwen3.5-0.8B showed the ratios hold within a tool family on one model but not across input sizes (patchscope 3.9-16.7x embed_lens between 72 and 985 media tokens), and per-case cost grows with batch size for several tools. The scored scheduler decides one chunk at a time (scoring mvp3-score-3): T and D are earned in proportion to the share of the route's remaining FAIL cases a chunk covers, and further chunks of a step it already took do not count against --triage-max-actions. On Qwen3.5-0.8B POPE no budgeted run exceeds its budget (before: +111 s rules, +185 s scored at 800 s); chunking adds about 2% to the unbudgeted cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 +++ docs/agentic_benchmark.md | 6 +- evalrx/benchmark/run.py | 7 +- evalrx/benchmark/runner.py | 1 + evalrx/eval_agent/probing/controller.py | 153 ++++++++++++++----- evalrx/eval_agent/probing/scoring.py | 96 ++++++------ tests/test_eval_agent/test_probing_chunks.py | 111 ++++++++++++++ tests/test_eval_agent/test_probing_mvp3.py | 26 ++-- tests/test_eval_agent/test_probing_mvp3b.py | 3 +- 9 files changed, 322 insertions(+), 100 deletions(-) create mode 100644 tests/test_eval_agent/test_probing_chunks.py diff --git a/CHANGELOG.md b/CHANGELOG.md index dd13bbac..6d04bb35 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,25 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed — triage spends by measurement: chunked steps, no per-analyzer cost prior + +Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS +alternating); the budget is checked before every chunk on the cost measured +so far, so a step whose cost nobody knew overshoots by at most one chunk, and +a chunk that raises stops the rest of the step. Cost estimates no longer use +per-call rates or `calls_per_case` (kept for reservations only): a step that +has run is priced at its own measured cost per case, one that has not at the +run's median case (ranking) or its most expensive case (budget checks). A +calibration on Qwen3.5-0.8B showed why: tools' cost ratios hold within a +family on one model (generate tools ~ the number of generate calls, forward +tools within ~15% against `embed_lens`) but not across input sizes +(`patchscope` 3.9-16.7x `embed_lens` between 72 and 985 media tokens), and +per-case cost also grows with batch size for several tools. The scored +scheduler decides one chunk at a time (scoring `mvp3-score-3`): T and D are +earned in proportion to the share of the route's remaining FAIL cases a chunk +covers, and further chunks of a step it already took do not count against +`--triage-max-actions`. + ### Added — triage competing explanations: D for the scored scheduler (MVP-3, second part) `--triage-explanations judge` (with `--triage-scheduler scored`) has the diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index bde025f9..1755d1f0 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -29,13 +29,13 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend --m1-policy triage_active --run-tag triage0 ``` -After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once its estimate (the same step's earlier seconds per case) exceeds what is left. The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. -**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Steps whose per-case rows do not depend on the batch (the audits, the swap with donors from the whole partition, the knockout, re-sampling, the wrappers) run on the new cases alone and keep the old rows. `embed_lens` and `patchscope` infer the question words from the batch, but no route reads them, so they wait until the sample stops growing and run once on the whole of it. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). +**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Steps whose per-case rows do not depend on the batch (the audits, the swap with donors from the whole partition, the knockout, re-sampling, the wrappers) run on the new cases alone and keep the old rows. `embed_lens` and `patchscope` infer the question words from the batch, but no route reads them, so they wait until the sample stops growing and run once on the whole of it. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). **Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. -**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — each active route's open or stale layer, the expansion, and the batch-dependent battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for extending a step to a route's new cases or resolving a contradiction and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist; q is the analyzer's smoothed success rate in this run; c is the estimated cost on the primary axis (USD when every action is priced, else seconds). Every 10th decision explores with a seed, and the run stops when no candidate's gain reaches 0.01. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. +**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as is D) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet; one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Every 10th decision explores with a seed, and the run stops when no candidate's gain reaches 0.01. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. **Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D is the share of pairs of its route's live explanations whose predictions for it conflict (a pair with `unknown` counts only in the denominator). The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Only each open layer's current candidate is offered for prediction. On Qwen3.5-0.8B POPE D reorders the follow-ups but changes neither what runs nor which pairs the final evidence tells apart, and the judge's two asks (169 s) cost about a sixth of the evidence time; D does not yet discount predictions the route's case count cannot decide. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index db5467f8..028b04c2 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -157,13 +157,18 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP help="triage_active: the most FAIL cases the expansion rule may grow the sample to " "(doubling from --triage-n-fail; a value at or below it disables expansion)") p.add_argument("--triage-max-actions", type=int, default=12, - help="triage_active: decisions after the battery (expansions + route follow-ups)") + help="triage_active: decisions after the battery (expansions + route follow-ups; the " + "scored scheduler's further chunks of a step it already took do not count)") p.add_argument("--triage-scheduler", choices=["rules", "scored"], default="rules", help="triage_active: rules = MVP-2 fixed rounds over the routes' layers; scored = MVP-3 " "value per cost, U = q*[D+T+C-R]+/(c+eps) (report: triage_report.scored.*)") p.add_argument("--triage-budget-usd", type=float, default=0.0, help="triage_active: USD cap on priced API models (0 = none), charged like " "--triage-budget-sec") + p.add_argument("--triage-chunk", type=int, default=8, + help="triage_active: cases per chunk of a reusable step (FAIL and PASS alternating; 0 = one " + "piece). The budget is checked before every chunk on the cost measured so far, and the " + "scored scheduler decides one chunk at a time") p.add_argument("--triage-explanations", choices=["none", "judge"], default="none", help="triage_active with --triage-scheduler scored: judge = the --judge-provider/" "--judge-model judge proposes competing explanations with predictions once per " diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 53c2760c..d188cecb 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -451,6 +451,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: price_fn=_price_fn(spec), per_call_generation=sampling is not None, scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, + chunk=int(args.triage_chunk), partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "confirm_visible_to_controller": False}, diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 4cb04d33..5280fd90 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -29,6 +29,9 @@ are not read by the routes, so nothing the expansion rule looks at depends on them: they run once, on the whole sample the expansions settle on. + Steps run in chunks of ``chunk`` cases (FAIL and PASS alternating), with the + budget checked before each chunk on the cost measured so far. + 3. **Follow-ups.** Each active route proposes its next layer's candidate (see :mod:`~evalrx.eval_agent.probing.rules`), and the candidate runs on the route's FAIL cases plus matched PASS controls. @@ -38,7 +41,9 @@ * no route has a candidate left; * ``max_actions`` decisions (expansions + follow-ups) have been made; or -* the wall-clock budget is spent, or an action's estimate exceeds what is left. +* the budget is spent, or the next chunk's estimate exceeds what is left (a + step's own measured cost per case, else the most expensive case measured in + this run; there is no per-analyzer cost prior). The rules scheduler calls no judge and names no hypothesis. The scored scheduler (MVP-3) may take an explainer: the judge then proposes competing @@ -65,7 +70,14 @@ from typing import TYPE_CHECKING, Any, Callable from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES -from evalrx.eval_agent.probing.actions import OK, SKIPPED, PlanStep, ProbeAction, canonical +from evalrx.eval_agent.probing.actions import ( + FAILED, + OK, + SKIPPED, + PlanStep, + ProbeAction, + canonical, +) from evalrx.eval_agent.probing.evidence import StepEvidence from evalrx.eval_agent.probing.executor import execute, gate from evalrx.eval_agent.probing.explanations import ( @@ -106,9 +118,8 @@ choose, coverage_gain, coverage_units, - estimate_cost, - method_rates, public_units, + step_cost, value, ) from evalrx.eval_agent.probing.triage import ( @@ -226,9 +237,9 @@ class _Run: def __init__(self, model: Any, explore: "CaseBatch", ledger: Ledger, *, context: dict[str, Any], extras: dict[str, dict[str, Any]], task_kind: "str | None", budget_sec: float, price_fn: Any, run_logger: Any, say: Callable[[str], None], - per_call_generation: bool = True, budget_usd: float = 0.0) -> None: + per_call_generation: bool = True, budget_usd: float = 0.0, chunk: int = 0) -> None: self.model, self.ledger, self.context, self.extras = model, ledger, context, extras - self.per_call_generation, self.budget_usd = per_call_generation, budget_usd + self.per_call_generation, self.budget_usd, self.chunk = per_call_generation, budget_usd, chunk self.task_kind, self.budget_sec, self.price_fn, self.run_logger, self.say = ( task_kind, budget_sec, price_fn, run_logger, say) self.by_id = {str(c.id): c for c in explore} @@ -277,16 +288,29 @@ def gate(self, step: PlanStep, ids: "list[str]") -> "tuple[str, str] | None": return ("unsupported", why) if why else None def estimate_sec(self, step: PlanStep, n_cases: int) -> "float | None": - ev = self.evidence.get(step.name) - per_case = ev.sec_per_case() if ev is not None else None - return round(per_case * n_cases, 1) if per_case is not None else None + """Seconds a budget check assumes: the step's own cost per case, else the most + expensive case measured in this run (``None`` before anything was measured).""" + cost, _ = step_cost(step, n_cases, self.evidence, "wall_sec", unmeasured="max") + return round(cost, 1) if cost is not None else None def estimate_usd(self, step: PlanStep, n_cases: int) -> "float | None": - ev = self.evidence.get(step.name) - rows = [(float(o.cost.get("usd") or 0.0), len(o.planned_ids)) for o in (ev.chunks if ev else []) - if o.cost.get("usd") is not None and o.planned_ids] - n = sum(k for _, k in rows) - return round(sum(v for v, _ in rows) / n * n_cases, 6) if n else None + cost, _ = step_cost(step, n_cases, self.evidence, "usd", unmeasured="max") + return round(cost, 6) if cost is not None else None + + def chunks(self, step: PlanStep, ids: "list[str]") -> "list[list[str]]": + """*ids* in the order a step runs them: a ``reuse`` step in chunks of ``self.chunk`` + cases with FAIL and PASS alternating (so every chunk can be compared with its + controls); any other step, or no chunk size, in one piece.""" + if not step.reuse or self.chunk <= 0 or len(ids) <= self.chunk: + return [list(ids)] if ids else [] + def is_fail(cid: str) -> bool: + return getattr(getattr(self.by_id[cid], "label", None), "value", None) == "fail" + + fails = [c for c in ids if is_fail(c)] + passes = [c for c in ids if not is_fail(c)] + order = [c for pair in zip(fails, passes) for c in pair] + order += fails[len(passes):] + passes[len(fails):] + return [order[i:i + self.chunk] for i in range(0, len(order), self.chunk)] def charged(self, axis: str) -> float: """What this run's evidence cost when each observation was first executed (a read-back @@ -374,8 +398,12 @@ def _adopt(self, ev: StepEvidence, step_id: str, target: "list[str]", def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: int, rule_id: "str | None" = None, route: "str | None" = None, budget_checked: bool = False) -> "dict[str, Any] | None": - """Bring *step*'s evidence up to date on *target*; the execution record, or ``None`` - when every case is already covered.""" + """Bring *step*'s evidence up to date on *target*; the last execution record, or + ``None`` when every case is already covered. + + A ``reuse`` step runs in chunks (:meth:`chunks`) with the budget checked before + each one on the cost measured so far, so an action overshoots by at most one + chunk; a refusal by the step's own check stops the remaining chunks.""" ev = self.evidence.setdefault(step.name, StepEvidence(step)) base = {"kind": kind, "revision": revision, "key": step.name, "analyzer": step.analyzer, "rule_id": rule_id, "route": route} @@ -401,6 +429,27 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: self._log(record) return record todo = ev.todo(target) + if not todo: + return None + record = None + for part in self.chunks(step, todo): + out = self._run_part(step, part, ev, base, analyzer, version, context, step_id, config, + kind=kind, revision=revision, rule_id=rule_id, budget_checked=budget_checked) + record = out if out is not None else record + if out is not None and out["status"] == FAILED and not out.get("reused"): + # an execution that raised costs time and would likely raise again on the rest + # (an unsupported chunk costs nothing: the rest still get their own verdict) + self.blocked.setdefault(step.name, f"failed: {out.get('error') or ''}".strip()) + break + if (out is not None and out["status"] == SKIPPED) or ev.refused() is not None: + break + return record + + def _run_part(self, step: PlanStep, target: "list[str]", ev: StepEvidence, base: dict[str, Any], + analyzer: Any, version: str, context: dict[str, Any], step_id: str, config: dict[str, Any], *, + kind: str, revision: int, rule_id: "str | None", budget_checked: bool) -> "dict[str, Any] | None": + """One case set of :meth:`run_step`: read back what exists, else execute.""" + todo = ev.todo(target) if not todo: return None # Checked as if the cases ran fresh, before anything is read back: the budget is @@ -505,6 +554,7 @@ def run_triage( min_gain: float = 0.01, min_cover: int = 8, budget_usd: float = 0.0, + chunk: int = 8, explainer: "Explainer | None" = None, run_logger: Any = None, progress: "Callable[[str], None] | None" = print, @@ -521,7 +571,8 @@ def run_triage( n_fail: FAIL cases in the first sample (PASS controls are matched to them). max_fail: the most FAIL cases expansion may reach (``None`` = *n_fail*: no expansion). - max_actions: decisions after the battery (expansions + follow-ups). + max_actions: decisions after the battery (expansions + follow-ups); the scored + scheduler's further chunks of a step it already took do not count. min_route_fail: FAIL cases a route needs before it proposes follow-ups. min_cohort: S cohort / stable-PASS size per stratum below which the expansion rule counts a gap. @@ -561,6 +612,10 @@ def run_triage( and per-unit coverage target. budget_usd: USD cap (0 = none), charged like ``budget_sec`` and checked with the step's earlier USD per case. + chunk: cases per chunk of a ``reuse`` step (FAIL and PASS alternating; + 0 = one piece). The budget is checked before each chunk on the + cost measured so far, so an action overshoots by at most one + chunk; the scored scheduler decides one chunk at a time. explainer: the scored scheduler's source of competing explanations (:mod:`.explanations`): asked once the sample has settled and again when the evidence has thinned a route's live explanations @@ -584,7 +639,8 @@ def run_triage( n_available = sum(1 for c in explore if getattr(getattr(c, "label", None), "value", None) == "fail") run = _Run(model, explore, ledger, context={"policy": POLICY_VERSION, "model": model_identity}, extras=extras, task_kind=task_kind, budget_sec=budget_sec, price_fn=price_fn, - run_logger=run_logger, say=say, per_call_generation=per_call_generation, budget_usd=budget_usd) + run_logger=run_logger, say=say, per_call_generation=per_call_generation, budget_usd=budget_usd, + chunk=chunk) rank_of = partial(rank, seed) triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn) @@ -633,8 +689,17 @@ def decide(record: dict[str, Any]) -> None: ledger.trace(record) decisions.append(record) - def n_actions() -> int: # decisions that spend: expansions, follow-ups, scheduled battery steps - return sum(1 for d in decisions if d["kind"] in ("expand", "follow_up", "extend", "battery")) + spending = ("expand", "follow_up", "extend", "battery") + + def n_spent() -> int: # every decision that spends + return sum(1 for d in decisions if d["kind"] in spending) + + def n_actions() -> int: + """What ``max_actions`` caps: expansions, follow-ups and scheduled battery steps. The scored + scheduler's further chunks of a step it already took (``extend``) do not count: chunking a + step must not use up the cap a whole step used before.""" + kinds = ("expand", "follow_up", "battery") if scheduler == "scored" else spending + return sum(1 for d in decisions if d["kind"] in kinds) def expansion_plan() -> "tuple[Any, Any, list[str], float | None] | None": """The next nested sample, its new cases and the battery's estimated seconds; ``None`` at the cap.""" @@ -710,8 +775,9 @@ def route_view(records: list[dict[str, Any]], gaps: list[dict[str, Any]] sample_ids = list(draw.case_ids) growing = bool(gaps) and expansion_note is None and \ next_size(len(draw.fail_ids), max_fail, n_available) is not None - pending = {s.name: (s, sample_ids) for s in deferred - if s.name not in run.evidence or run.evidence[s.name].todo(sample_ids)} + pending = {s.name: (s, sample_ids) for s in deferred if s.name not in run.blocked and ( + s.name not in run.evidence or (run.evidence[s.name].refused() is None + and run.evidence[s.name].todo(sample_ids)))} rows = [r for r in active_routes(records, min_route_fail) if r["active"]] # Decisions read only this scheduler's own evidence and price every candidate as if # it ran fresh: chunks in the ledger (an earlier invocation, the other scheduler) @@ -843,7 +909,6 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], # layer waits for it (a battery step) rather than falling back to another tool. units = coverage_units(states, records, run.evidence, layers, min_cover=min_cover) axis = axis_of(run.evidence) - rates, wall_rates = method_rates(run.evidence, axis), method_rates(run.evidence, "wall_sec") by_id = {r["case_id"]: r for r in records} pool: list[Scored] = [] filtered: list[dict[str, Any]] = [] @@ -861,26 +926,34 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], todo = ev.todo(target) if ev is not None else list(target) if not todo: # the same observation exists: R = 1, not a candidate continue - fail_new = set(todo) & set(st["_fail_ids"]) + # a reuse step runs its next chunk; T and D are about the step on the whole route, + # so the chunk earns them for the share of the route's remaining FAIL cases it covers + part = run.chunks(step, todo)[0] + fail_left = set(todo) & set(st["_fail_ids"]) + fail_new = set(part) & fail_left + share = len(fail_new) / len(fail_left) if fail_left else len(part) / len(todo) C, touched = coverage_gain(layer.rule_id, fail_new, units) + # a step already measured on part of the route's FAIL cases (a smaller sample, earlier + # chunks); a battery step on part of the sample. Shared PASS controls do not count: + # describe-first measured for S has not started N's question + started = step.reuse and ev is not None and bool( + ev.covered() & set(target if st.get("battery") else st["_fail_ids"])) T, gap_ids = 0.0, [] - if st["state"] == "extend" and step.reuse: - T, gap_ids = 1.0, [f"stale:{layer.rule_id}:{step.name}"] + if started: + T, gap_ids = share, [f"incomplete:{layer.rule_id}:{step.name}"] elif layer.route == "H" and any(by_id[c]["H"]["disagreements"] for c in fail_new): - T, gap_ids = 1.0, [f"contradiction:{layer.rule_id}"] - kind = "battery" if st.get("battery") else ("extend" if st["state"] == "extend" else "follow_up") + T, gap_ids = share, [f"contradiction:{layer.rule_id}"] + kind = "extend" if started else ("battery" if st.get("battery") else "follow_up") D, d_detail = disagreement(route, step.name, live) if live else (0.0, {}) + cost, basis = step_cost(step, len(part), run.evidence, axis) cand = Scored(kind=kind, key=step.name, route=route, rule_id=layer.rule_id, - order=(ROUTE_ORDER.index(route), li), n_new_cases=len(todo), D=D, T=T, C=C, - d_detail=d_detail, - q=availability(step.analyzer, run.evidence), - cost=estimate_cost(step, len(todo), run.evidence, axis, rates), + order=(ROUTE_ORDER.index(route), li), n_new_cases=len(part), D=D * share, T=T, C=C, + d_detail=d_detail, q=availability(step.analyzer, run.evidence), cost=cost, basis=basis, gaps=gap_ids, units=touched, payload=Proposal(layer=layer, step=step, kind=st["state"], fail_ids=st["_fail_ids"], - control_ids=st["_control_ids"], todo=todo, tried=st.get("tried", []), - before=[], target_override=st.get("target"))) - why = run.over_budget(estimate_cost(step, len(todo), run.evidence, "wall_sec", wall_rates), - run.estimate_usd(step, len(todo))) + control_ids=st["_control_ids"], todo=part, tried=st.get("tried", []), + before=[], target_override=part)) + why = run.over_budget(run.estimate_sec(step, len(part)), run.estimate_usd(step, len(part))) if why is not None: filtered.append({"key": step.name, "route": route, "rule_id": layer.rule_id, "reason": why}) continue @@ -894,7 +967,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], steps = [s for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] qs = [availability(s.analyzer, run.evidence) for s in steps if any(o.status != "unsupported" for o in run.evidence[s.name].chunks)] - costs = [estimate_cost(s, len(plan[2]), run.evidence, axis, rates) for s in steps] + costs = [step_cost(s, len(plan[2]), run.evidence, axis)[0] for s in steps] cand = Scored(kind="expand", key="expand", rule_id="E1", order=(-1, 0), n_new_cases=len(plan[2]), T=0.5, q=sum(qs) / len(qs) if qs else 0.5, cost=sum(c for c in costs if c is not None) if any(c is not None for c in costs) else None, @@ -927,7 +1000,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], current.decided_at_ask = _decided(verdicts) live = [h for h in (current.hypotheses if current is not None else []) if verdicts[h.id]["state"] == "live"] pool, filtered, axis = scored_pool(records, gaps, states, growing, live) - pick, why = choose(pool, decision_no=n_actions(), seed=seed, explore_every=explore_every, + pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_every=explore_every, min_gain=min_gain) if pick is None: over = [f for f in filtered if not f["reason"].startswith("batch-dependent")] @@ -936,7 +1009,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], "every remaining candidate is over budget" if over else "no feasible candidate"), "best_gain": max((c.gain for c in pool), default=None), "filtered": filtered} break - if n_actions() >= max_actions: + if pick.kind != "extend" and n_actions() >= max_actions: stop = {"reason": "max_actions", "max_actions": max_actions, "pending": f"{pick.route}:{pick.rule_id}:{pick.key}"} break @@ -1068,7 +1141,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], "n_needs_counterfactual": n_needs_counterfactual, "budget_sec": budget_sec, "task_kind": task_kind, "answer_fn": canonical(answer_fn), "n_fail": n_fail, "max_fail": max_fail, "max_actions": max_actions, "min_route_fail": min_route_fail, - "min_cohort": min_cohort, "per_call_generation": per_call_generation}, + "min_cohort": min_cohort, "per_call_generation": per_call_generation, "chunk": chunk}, "executions": run.executions, "battery": _battery_state(battery, run, draw), "revisions": revisions, diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/probing/scoring.py index ce496c58..6d1605c8 100644 --- a/evalrx/eval_agent/probing/scoring.py +++ b/evalrx/eval_agent/probing/scoring.py @@ -9,17 +9,24 @@ * **D** (prediction disagreement): with an explainer, the share of pairs of the route's live competing explanations whose predictions for the step conflict - (:mod:`.explanations`); the explanations come once per sample revision, and - an explanation a prediction already missed on leaves the live set at the next - decision. Without one, or with fewer than two live explanations, ``D = 0`` - and actions earn budget through T and C. An expansion's D is 0. -* **T** (evidence gap): 1 completes a recorded gap — a layer done on a smaller - sample whose step only has to run on the route's new cases (a ``reuse`` - step), or a contradiction between two readings of the same check; 0.5 is an - expansion that may close a recorded uncertainty (an uncertain routing - signal, a small S cohort); 0 otherwise. A batch-dependent step that went - stale re-runs on the whole sample: its value is the coverage it restores (C), - not a gap of its own. Every T names the gap ids it serves. + (:mod:`.explanations`); the explanations come once the sample has settled, + and an explanation a prediction already missed on leaves the live set at the + next decision. Without one, or with fewer than two live explanations, + ``D = 0`` and actions earn budget through T and C. An expansion's D is 0. +* **T** (evidence gap): 1 completes a recorded gap — a ``reuse`` step measured + on part of the route's FAIL cases (a smaller sample, or earlier chunks) that + still has to run on the rest, or a contradiction between two readings of the + same check; 0.5 is an expansion that may close a recorded uncertainty (an + uncertain routing signal, a small S cohort); 0 otherwise. A batch-dependent + step that went stale re-runs on the whole sample: its value is the coverage + it restores (C), not a gap of its own. Every T names the gap ids it serves. + +A ``reuse`` step runs one chunk per decision (a fixed number of cases, FAIL and +PASS alternating), so a decision spends at most one chunk before the scheduler +sees the step's measured cost. T and D are about the step on the whole route, +so a chunk earns them in proportion to the share of the route's remaining FAIL +cases it covers, and the chunks of a step add up to what it earns unchunked; C +is counted per chunk already. * **C** (coverage): units are ``layer × gold stratum`` for every route with FAIL cases there. A unit's gap is 1 untested, 0.5 measured on fewer than ``min(min_cover, route FAIL cases in the stratum)`` cases, else 0. ``C(a)`` is @@ -32,10 +39,11 @@ counts once, so a resumed run decides the same way); ``ok`` and not refused by its own check is a success, and ``unsupported`` (a gate result, filtered before scoring) is not an attempt. -* **c** (marginal cost): the step's own earlier cost per case, else the per-call - rate of each method it calls (measured on this run), times the new cases. - ``backward`` has no measured rate until a gradient tool runs; it is priced at - three forwards (a prior, stated here). +* **c** (marginal cost): the step's own measured cost per case in this run, + times the new cases; a step that has not run yet is priced at the run's + median cost per case (budget checks use the maximum). There is no + per-analyzer prior: measured costs do not transfer across input sizes, + models or backends, and a reusable step's first chunk shows its real cost. Candidates are each route's open or stale layers (the layer's next candidate in its fallback order, as in the rules), the expansion, and the batch-dependent @@ -58,8 +66,7 @@ from evalrx.eval_agent.probing.actions import OK, UNSUPPORTED, PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -SCORING_VERSION = "mvp3-score-2" -BACKWARD_FORWARDS = 3.0 +SCORING_VERSION = "mvp3-score-3" @dataclass(frozen=True) @@ -88,6 +95,7 @@ class Scored: cost: "float | None" = None gain: float = 0.0 U: float = 0.0 + basis: str = "" # what the cost rests on: "own" / "typical" / "none" gaps: list[str] = field(default_factory=list) units: list[str] = field(default_factory=list) d_detail: dict[str, Any] = field(default_factory=dict) # which live explanations D separates @@ -131,39 +139,39 @@ def _amount(cost: dict[str, Any], axis: str) -> float: return float(cost.get(axis) or 0.0) -def method_rates(evidence: dict[str, StepEvidence], axis: str) -> dict[str, float]: - """Cost per call by method, from observations that called one method only.""" - spent: dict[str, float] = {} - calls: dict[str, int] = {} - seen = set() +def per_case_costs(evidence: dict[str, StepEvidence], axis: str) -> list[float]: + """Cost per planned case of every distinct observation that called the model.""" + seen: dict[str, float] = {} for ev in evidence.values(): for obs in ev.chunks: - used = {k: int(v) for k, v in (obs.cost.get("calls") or {}).items() if v} - if obs.action_id in seen or len(used) != 1: + cost = obs.cost or {} + if obs.action_id in seen or not cost.get("calls") or not obs.planned_ids or cost.get(axis) is None: continue - seen.add(obs.action_id) - (method, n), = used.items() - spent[method] = spent.get(method, 0.0) + _amount(obs.cost, axis) - calls[method] = calls.get(method, 0) + n - rates = {m: spent[m] / calls[m] for m in calls if calls[m]} - if "backward" not in rates and "forward" in rates: - rates["backward"] = BACKWARD_FORWARDS * rates["forward"] - if "logprobs" not in rates and "generate" in rates: - rates["logprobs"] = rates["generate"] - return rates - - -def estimate_cost(step: PlanStep, n_cases: int, evidence: dict[str, StepEvidence], axis: str, - rates: dict[str, float]) -> "float | None": - """Marginal cost of running *step* on *n_cases* new cases (``None`` = no basis yet).""" + seen[obs.action_id] = _amount(cost, axis) / len(obs.planned_ids) + return list(seen.values()) + + +def step_cost(step: PlanStep, n_cases: int, evidence: dict[str, StepEvidence], axis: str, *, + unmeasured: str = "typical") -> "tuple[float | None, str]": + """Cost of running *step* on *n_cases* new cases, and its basis. + + No analyzer-specific prior: a step that has run in this run is priced at its + own measured cost per case (``own``). One that has not is priced at the + run's ``typical`` (median) cost per case when ranking, or its ``max`` when + checking a budget, so an unknown tool cannot look cheap; ``None`` before + anything was measured. + """ ev = evidence.get(step.name) rows = [(_amount(o.cost, axis), len(o.planned_ids)) for o in (ev.chunks if ev else []) - if (o.cost or {}).get("calls") and o.planned_ids] + if (o.cost or {}).get("calls") and o.planned_ids and o.cost.get(axis) is not None] if rows and sum(k for _, k in rows): - return sum(s for s, _ in rows) / sum(k for _, k in rows) * n_cases - if step.calls_per_case and all(m in rates for m in step.calls_per_case): - return sum(rates[m] * k for m, k in step.calls_per_case.items()) * n_cases - return None + return sum(s for s, _ in rows) / sum(k for _, k in rows) * n_cases, "own" + pool = per_case_costs(evidence, axis) + if not pool: + return None, "none" + pool.sort() + per_case = pool[-1] if unmeasured == "max" else (pool[(len(pool) - 1) // 2] + pool[len(pool) // 2]) / 2 + return per_case * n_cases, unmeasured # -- C: coverage units ------------------------------------------------------------------- diff --git a/tests/test_eval_agent/test_probing_chunks.py b/tests/test_eval_agent/test_probing_chunks.py new file mode 100644 index 00000000..77193e89 --- /dev/null +++ b/tests/test_eval_agent/test_probing_chunks.py @@ -0,0 +1,111 @@ +"""Chunked execution: no per-analyzer cost prior, spending bounded by what was measured. + +* a ``reuse`` step runs in chunks with FAIL and PASS alternating, and every case + reads the same as when the step ran in one piece; +* the budget is checked before each chunk on the cost measured so far, so an + action whose cost nobody knew overshoots by at most one chunk; +* the scored scheduler prices a step it has not run at the run's typical case, + and at its own measured cost once a chunk of it ran; +* further chunks of a step the scored scheduler already took do not use up + ``max_actions``. +""" + +from __future__ import annotations + +import pytest + +import evalrx.eval_agent.probing.controller as controller +from evalrx.eval_agent.probing import run_triage +from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _strip, _Table + +DESCRIBE_SEC = 10.0 # an expensive step whose cost no prior knows + + +@pytest.fixture +def metered(monkeypatch): + """One second per case, ten for describe-first: deterministic costs a budget can bind on.""" + real = controller.execute + + def execute(action, *args, **kwargs): + obs = real(action, *args, **kwargs) + if obs.cost.get("calls"): + per_case = DESCRIBE_SEC if "describe_first" in (action.config.get("strategies") or {}) else 1.0 + obs.cost["wall_sec"] = per_case * len(obs.planned_ids) + return obs + + monkeypatch.setattr(controller, "execute", execute) + + +def _label(cases, cid): + return next(c for c in cases if str(c.id) == cid).label.value + + +def test_a_reuse_step_runs_in_alternating_chunks_and_reads_the_same_as_in_one_piece(tmp_path): + cases, table = _pope_like() + whole_model, chunked_model = _Table(table), _Table(table) + whole = run_triage(whole_model, cases, **_kw(tmp_path / "w", max_fail=8, min_route_fail=1, chunk=0)) + chunked = run_triage(chunked_model, cases, **_kw(tmp_path / "c", max_fail=8, min_route_fail=1, chunk=4)) + assert {r["case_id"]: _strip(r) for r in chunked["cases"]} == {r["case_id"]: _strip(r) for r in whole["cases"]} + assert chunked_model.n_generate == whole_model.n_generate + runs = [e for e in chunked["executions"] if e["key"] == "self_consistency" and not e["reused"]] + assert len(runs) > 1 and all(e["n_cases"] <= 4 for e in runs) + first = controller.Ledger(tmp_path / "c").settled(runs[0]["action_id"]).planned_ids + assert {_label(cases, cid) for cid in first} == {"fail", "pass"} # comparable from the first chunk + assert chunked["settings"]["chunk"] == 4 + + +def _budget_before_first_follow_up(tmp_path, scheduler): + """The charge just before the first follow-up of an unbudgeted run, plus ten seconds: room + for the follow-up at the worst case measured so far (one second per case), not at its real cost.""" + full = run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(tmp_path / f"{scheduler}-full", max_fail=4, min_route_fail=1, chunk=4, scheduler=scheduler)) + spent = 0.0 + for e in full["executions"]: + if e["kind"] == "follow_up": + break + if not e["reused"]: + spent += float((e.get("cost") or {}).get("wall_sec") or 0.0) + return spent + 10.0 + + +@pytest.mark.parametrize("scheduler", ["rules", "scored"]) +def test_an_unknown_expensive_step_overshoots_the_budget_by_at_most_one_chunk(tmp_path, metered, scheduler): + budget = _budget_before_first_follow_up(tmp_path, scheduler) + overshoot = {} + for chunk in (0, 4): + report = run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(tmp_path / f"{scheduler}-{chunk}", max_fail=4, min_route_fail=1, chunk=chunk, + scheduler=scheduler, budget_sec=budget)) + overshoot[chunk] = report["cost"]["charged"]["wall_sec"] - budget + if chunk: # the first chunk showed the real cost: the rest is not run, and the run stops there + assert report["stop"]["reason"] == "budget" + assert [e["key"] for e in report["executions"] if e["key"] == "describe_first" and e["status"] == "ok"] == [ + "describe_first"] + assert 0 < overshoot[4] <= 4 * DESCRIBE_SEC < overshoot[0] + + +def test_the_scored_scheduler_prices_a_step_at_the_typical_case_until_a_chunk_of_it_ran(tmp_path, metered): + report = run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(tmp_path / "s", max_fail=4, min_route_fail=1, chunk=2, scheduler="scored")) + rows = [(d["n"], c) for d in report["decisions"] for c in d.get("candidates") or [] if c["key"] == "describe_first"] + first_n = rows[0][0] + assert {c["basis"] for n, c in rows if n == first_n} == {"typical"} + assert rows[0][1]["cost"] == pytest.approx(2 * 1.0) # every case measured so far cost one second + later = [c for n, c in rows if n > first_n] + assert later and {c["basis"] for c in later} == {"own"} + assert all(c["cost"] == pytest.approx(DESCRIBE_SEC * c["n_new_cases"]) for c in later) + + +def test_further_chunks_of_a_taken_step_do_not_use_up_max_actions(tmp_path): + cases, table = _pope_like() + report = run_triage(_Table(table), cases, **_kw(tmp_path / "m", max_fail=8, min_route_fail=1, chunk=2, + scheduler="scored", max_actions=2)) # an expansion and one step + kinds = [d["kind"] for d in report["decisions"] if d["kind"] != "expand_not_possible"] + (taken,) = [d for d in report["decisions"] if d["kind"] == "follow_up"] + extends = [d for d in report["decisions"] if d["kind"] == "extend" and d["route"] == taken["route"]] + assert kinds[:2] == ["expand", "follow_up"] and extends + assert report["stop"]["reason"] == "max_actions" and report["stop"]["pending"] != ( + f"{taken['route']}:{taken['rule_id']}:{taken['key']}") + route_cases = [r for r in report["routes"] if r["route"] == taken["route"]][0] + layer = next(x for x in route_cases["layers"] if x["rule_id"] == taken["rule_id"]) + assert layer["state"] == "done" # the step ran on all of its route's cases diff --git a/tests/test_eval_agent/test_probing_mvp3.py b/tests/test_eval_agent/test_probing_mvp3.py index d4a55573..82ae5094 100644 --- a/tests/test_eval_agent/test_probing_mvp3.py +++ b/tests/test_eval_agent/test_probing_mvp3.py @@ -23,8 +23,8 @@ availability, choose, coverage_gain, - estimate_cost, - method_rates, + per_case_costs, + step_cost, ) from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table @@ -47,16 +47,20 @@ def test_availability_counts_each_observation_once_and_a_refusal_as_a_failure(): assert availability("gradcam", ev) == 0.5 # never tried -def test_costs_come_from_the_steps_own_history_else_measured_rates(): - sc = _step("self_consistency") +def test_costs_come_from_the_steps_own_measurement_else_the_runs_typical_or_worst_case(): + sc, ko = _step("self_consistency"), _step("attention_knockout") ev = {"self_consistency": StepEvidence(sc, [_obs("s", ["a", "b"], cost={"wall_sec": 10.0, "calls": {"generate": 10}})]), - "attention_knockout": StepEvidence(_step("attention_knockout"), - [_obs("k", ["a"], cost={"wall_sec": 4.0, "calls": {"forward": 8}})])} - rates = method_rates(ev, "wall_sec") - assert rates == {"generate": 1.0, "forward": 0.5, "backward": 1.5, "logprobs": 1.0} - assert estimate_cost(sc, 3, ev, "wall_sec", rates) == 15.0 # 5 s per case, its own - assert estimate_cost(_step("gradcam"), 2, ev, "wall_sec", rates) == 3.0 # 1 backward per case - assert estimate_cost(_step("causal_trace"), 2, {}, "wall_sec", {}) is None + "attention_knockout": StepEvidence(ko, [_obs("k", ["a"], cost={"wall_sec": 4.0, "calls": {"forward": 8}}), + _obs("k2", ["b", "c"], cost={"wall_sec": 2.0, "calls": {"forward": 16}})]), + "answer_extraction_audit": StepEvidence(_step("answer_extraction_audit"), + [_obs("x", ["a", "b"], cost={"wall_sec": 0.0, "calls": {}})])} + assert sorted(per_case_costs(ev, "wall_sec")) == [1.0, 4.0, 5.0] # no model call: not a cost sample + assert step_cost(sc, 3, ev, "wall_sec") == (15.0, "own") # 5 s per case, its own + assert step_cost(ko, 3, ev, "wall_sec") == (6.0, "own") # 6 s over 3 cases + # never run: priced at the run's median case when ranking, its worst case in a budget check + assert step_cost(_step("gradcam"), 2, ev, "wall_sec") == (8.0, "typical") + assert step_cost(_step("gradcam"), 2, ev, "wall_sec", unmeasured="max") == (10.0, "max") + assert step_cost(_step("causal_trace"), 2, {}, "wall_sec") == (None, "none") def test_coverage_gain_is_the_gap_removed_over_all_units(): diff --git a/tests/test_eval_agent/test_probing_mvp3b.py b/tests/test_eval_agent/test_probing_mvp3b.py index dc9076fe..b968197d 100644 --- a/tests/test_eval_agent/test_probing_mvp3b.py +++ b/tests/test_eval_agent/test_probing_mvp3b.py @@ -212,7 +212,8 @@ def test_a_decided_prediction_that_thins_a_route_asks_the_judge_again(tmp_path, assert first["final"]["S.h1"]["state"] == "contradicted" and first["final"]["S.h2"]["state"] == "live" previous = json.loads(judge.prompts[1][judge.prompts[1].index("Evidence (JSON):") + 16:])["previous"] assert {p["id"]: p["state"] for p in previous}["S.h1"] == "contradicted" - assert "wrapped" not in second["offered"]["S"] # what ran is no longer offered + # what ran is shown to the judge as measured (still offered while chunks of it are left) + assert "wrapped" in second["seen"]["S"] def test_a_failed_judge_call_leaves_D_at_zero_and_the_run_completes(tmp_path): From c853b48e7a097c9596e5e3ab6f360966ad9417f3 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 18 Oct 2026 18:03:02 -0700 Subject: [PATCH 07/26] analyzers: batch-independent lenses and causal trace; seeded self-consistency embed_lens(reference=...) and patchscope(reference=...) tell a case's own question words from a fixed reference set's prompts instead of the batch (embed_lens also its recurring words, from the reference's first reference_media distinct media, cached on the model). tuned_lens( fit_cases=...) fits its translators on fixed cases, cached per fit set. causal_trace and attribution_patching seed each case's noise from its content (prompt and media) instead of its position; the default case id is a random uuid, so content is the stable key (_internals/seeds.py). self_consistency(seed=0) draws a case's samples under torch's random state seeded the same way and restores it afterwards (seed=None keeps the global state; provider-side sampling is unaffected). Without the new arguments the lenses behave as before. The triage passes EXPLORE in the sampler's rank order as the reference (its first 32 cases as the tuned lens's fit set), so all four steps are reuse steps that run on new cases only and in chunks; PlanStep.deferred keeps the descriptive steps no route reads (embed_lens, patchscope) waiting for the settled sample. Decomposability tests on TinyVLM cover the four. On Qwen3.5-0.8B, twelve cases sampled at temperature 1.0 give identical samples in chunks, in one batch and in reverse order; before, 7 of 64 route labels changed between two runs that executed in a different order. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 ++++ docs/agentic_benchmark.md | 2 +- evalrx/analyzers/_internals/seeds.py | 42 ++++++++ evalrx/analyzers/_internals/words.py | 44 +++++++- evalrx/analyzers/lens/embed_lens.py | 102 ++++++++++++++---- evalrx/analyzers/lens/patchscope.py | 27 ++++- evalrx/analyzers/lens/tuned_lens.py | 99 +++++++++++------ .../patching/attribution_patching.py | 5 +- evalrx/analyzers/patching/causal_trace.py | 8 +- .../analyzers/uncertainty/self_consistency.py | 15 ++- evalrx/eval_agent/probing/actions.py | 5 + evalrx/eval_agent/probing/controller.py | 32 ++++-- evalrx/eval_agent/probing/rules.py | 10 +- .../test_self_consistency_seed.py | 66 ++++++++++++ tests/test_eval_agent/test_probing_mvp2.py | 23 +++- 15 files changed, 412 insertions(+), 88 deletions(-) create mode 100644 evalrx/analyzers/_internals/seeds.py create mode 100644 tests/test_analyzers/test_self_consistency_seed.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d04bb35..78483238 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,26 @@ earned in proportion to the share of the route's remaining FAIL cases a chunk covers, and further chunks of a step it already took do not count against `--triage-max-actions`. +### Changed — the batch-dependent analyzers run per case; seeded self-consistency + +`embed_lens(reference=...)` and `patchscope(reference=...)` tell a case's own +question words from a fixed reference set's prompts (`embed_lens` also its +recurring words, from the reference's first `reference_media` distinct media, +cached on the model) instead of the batch; `tuned_lens(fit_cases=...)` fits +its translators on fixed cases (cached per fit set); `causal_trace` and +`attribution_patching` seed each case's noise from its content (prompt and +media) instead of its position in the batch. Without the new arguments the +lenses behave as before. `self_consistency(seed=0)` draws each case's samples +under torch's random state seeded from the seed and the case's content +(restored afterwards; `seed=None` keeps the global state): on Qwen3.5-0.8B +every case's samples at temperature 1.0 are identical whether the cases run in +chunks, in one batch or in reverse order, where before 7 of 64 route labels +changed between two runs that executed in a different order. A model that +samples on the provider's side is not affected. The triage passes EXPLORE in the sampler's rank +order (the first 32 cases as the tuned lens's fit set), so all four steps are +`reuse` steps: they run on new cases only and in chunks. `PlanStep.deferred` +marks the battery steps no route reads (`embed_lens`, `patchscope`). + ### Added — triage competing explanations: D for the scored scheduler (MVP-3, second part) `--triage-explanations judge` (with `--triage-scheduler scored`) has the diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 1755d1f0..6aaf1069 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -31,7 +31,7 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. -**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Steps whose per-case rows do not depend on the batch (the audits, the swap with donors from the whole partition, the knockout, re-sampling, the wrappers) run on the new cases alone and keep the old rows. `embed_lens` and `patchscope` infer the question words from the batch, but no route reads them, so they wait until the sample stops growing and run once on the whole of it. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). +**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Every step's per-case rows are independent of the batch, so steps run on the new cases alone and keep the old rows: `embed_lens` and `patchscope` tell question words (and `embed_lens` recurring media words, from the first 16 distinct images) from a fixed reference — EXPLORE in the sampler's rank order — instead of the batch, `tuned_lens` is fit once on the first 32 of those cases (cached on the model), and `causal_trace` seeds its noise from each case's content instead of its position; `self_consistency` draws each case's samples under a seed of its content too, so the U sampling check is the same in every run. No route reads `embed_lens` or `patchscope`, so they still wait until the sample stops growing. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). **Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. diff --git a/evalrx/analyzers/_internals/seeds.py b/evalrx/analyzers/_internals/seeds.py new file mode 100644 index 00000000..aaf4b672 --- /dev/null +++ b/evalrx/analyzers/_internals/seeds.py @@ -0,0 +1,42 @@ +"""Per-case seeds: the same draws for a case whatever batch it is in, and in every rerun. + +A seed taken from a case's position in its batch changes when the batch does, +and the default case id is a random uuid; the case's content (prompt and +media) is neither. +""" + +from __future__ import annotations + +import hashlib +from contextlib import contextmanager +from typing import Any, Iterator + + +def case_seed(seed: int, case: Any) -> int: + """From the run *seed* and the case's content (prompt and media), never its position or id.""" + h = hashlib.sha1(str(seed).encode()) + inputs = getattr(case, "inputs", None) + h.update(str(getattr(inputs, "prompt", "")).encode()) + for slot in ("image", "audio", "video"): + media = getattr(inputs, slot, None) + if media is None: + continue + h.update(slot.encode()) + h.update(media.tobytes() if hasattr(media, "tobytes") else str(media).encode()) + return int(h.hexdigest()[:12], 16) + + +@contextmanager +def seeded(seed: int) -> Iterator[None]: + """Torch's random state seeded with *seed* inside the block (CPU and every CUDA device), + restored afterwards, so nothing outside sees the reseed. Without torch it does nothing: + an API model samples on the provider's side.""" + try: + import torch + except ImportError: + yield + return + devices = list(range(torch.cuda.device_count())) if torch.cuda.is_available() else [] + with torch.random.fork_rng(devices=devices): + torch.manual_seed(seed) + yield diff --git a/evalrx/analyzers/_internals/words.py b/evalrx/analyzers/_internals/words.py index 9af57645..15121540 100644 --- a/evalrx/analyzers/_internals/words.py +++ b/evalrx/analyzers/_internals/words.py @@ -2,14 +2,19 @@ The lenses that read media tokens as words (``embed_lens``, ``patchscope``) ask whether a case's own question word shows up there. Which prompt words are -the case's own is told apart from the task's template by the batch itself: a +the case's own is told apart from the task's template by a set of prompts: a word found in at most ``max_share`` of the distinct prompts is specific ("snowboard"), one found in most of them is template ("image", "answer"). + +That set is the analysed batch (:func:`specific_words`), or a fixed reference +set of prompts (:func:`reference_specific_words`), with which a case's words +no longer depend on which other cases share its batch. """ from __future__ import annotations -from typing import Any +from collections import Counter +from typing import Any, Iterable # Function words the decoder emits for almost any state; kept out of word tallies. STOP = frozenset("""a an and are as at be but by for from has have in into is it its of on or @@ -62,3 +67,38 @@ def specific_words(prompt_words: "dict[str, tuple[Any, set[str]]]", *, max_share limit = max_share * len(distinct) return {cid: {w for w in words if share.get(w, 0) <= limit} for cid, (_, words) in prompt_words.items()}, True + + +def text_words(tokenizer: Any, text: str, special: "set[str]") -> set[str]: + """Content words of *text* tokenized on its own (a prompt without the chat template around it).""" + try: + ids = tokenizer(str(text), add_special_tokens=False)["input_ids"] + except Exception: # noqa: BLE001 - a tokenizer that is not callable + try: + ids = tokenizer.encode(str(text), add_special_tokens=False) + except Exception: # noqa: BLE001 - no tokenizer at all -> no words + return set() + return {w for t in ids if (w := content_word(tokenizer, t, special)) is not None} + + +def reference_specific_words(texts: "dict[str, str]", reference: "Iterable[str]", tokenizer: Any, + special: "set[str]", *, max_share: float = 0.5, + min_prompts: int = 3) -> "tuple[dict[str, set[str]], bool]": + """Each case's prompt words found in at most *max_share* of the distinct *reference* prompts. + + Args: + texts: ``{case_id: prompt}`` of the analysed cases (the prompt text alone). + reference: prompts of a fixed reference set (repeats count once). + + Returns: + ``({case_id: specific_words}, inferred)`` as :func:`specific_words`, except that + the template is told from the reference, so a case's specific words are the + same whatever else is in its batch. + """ + distinct = {str(p): text_words(tokenizer, p, special) for p in dict.fromkeys(str(p) for p in reference)} + if len(distinct) < min_prompts: + return {cid: set() for cid in texts}, False + share = Counter(w for words in distinct.values() for w in words) + limit = max_share * len(distinct) + return {cid: {w for w in text_words(tokenizer, text, special) if share.get(w, 0) <= limit} + for cid, text in texts.items()}, True diff --git a/evalrx/analyzers/lens/embed_lens.py b/evalrx/analyzers/lens/embed_lens.py index 3b18b9ac..3830c60b 100644 --- a/evalrx/analyzers/lens/embed_lens.py +++ b/evalrx/analyzers/lens/embed_lens.py @@ -11,7 +11,9 @@ * its activation norm. The paper sorts tokens into *sink* / *dead* / *alive* by checkpoint-specific -neighbour ids. Without such ids, the batch supplies the evidence: +neighbour ids. Without such ids, a set of images supplies the evidence (the +analysed batch, or the first ``reference_media`` distinct images of +``reference``): * **recurring** — the token's nearest word is the nearest word of media tokens in at least ``recurring_frac`` of the images: a direction the projector emits @@ -25,8 +27,13 @@ word's embedding. A question about an object the image does contain should find a media token close to the object's word. ``el_query_sim`` keeps only the case's own question words — prompt words found in at most half of the batch's -distinct prompts — so a template word ("image", "answer") cannot be the best -match on every case. +distinct prompts (or of ``reference``'s) — so a template word ("image", +"answer") cannot be the best match on every case. + +With ``reference`` (a fixed set of cases, e.g. the whole EXPLORE partition) +both the template words and the recurring words come from it, not from the +batch: a case's row is then the same whichever cases share its batch, so the +lens can run on a growing sample in chunks. The paper reads the INPUT (``layer=0``, the default). Whether a model's projector writes into vocabulary space there is itself the finding: on a @@ -49,7 +56,12 @@ from collections import Counter from typing import TYPE_CHECKING, Any -from evalrx.analyzers._internals.words import content_word, decode_word, specific_words +from evalrx.analyzers._internals.words import ( + content_word, + decode_word, + reference_specific_words, + specific_words, +) from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer @@ -74,8 +86,14 @@ class EmbedLensAnalyzer(Analyzer): min_images: fewest images from which recurring words are inferred. norm_ratio: a token is "high-norm" at ``norm ≥ norm_ratio × median``. vocab_chunk: embedding rows compared per block (bounds memory). + reference: fixed cases the template words (their prompts) and the + recurring words (their first ``reference_media`` distinct + media, forwarded once and cached on the model) are inferred + from instead of the batch; ``None`` = the batch. + reference_media: distinct reference media the recurring words come from. max_cases: label-stratified cap; 0 (the default) = every case. - Cost: 1 forward per case + one pass over the embedding table. + Cost: 1 forward per case + one pass over the embedding table + (with ``reference``: once, the same for its media). """ name = "embed_lens" @@ -100,14 +118,17 @@ class EmbedLensAnalyzer(Analyzer): def __init__(self, layer: "int | float" = 0, top_k: int = 5, recurring_frac: float = 0.5, min_images: int = 3, norm_ratio: float = 4.0, vocab_chunk: int = 32768, + reference: "CaseBatch | None" = None, reference_media: int = 16, max_cases: int = 0) -> None: if top_k < 1: raise ValueError(f"top_k must be >= 1, got {top_k}") if not 0 < recurring_frac <= 1: raise ValueError(f"recurring_frac must be in (0, 1], got {recurring_frac}") + if reference_media < 1: + raise ValueError(f"reference_media must be >= 1, got {reference_media}") super().__init__(layer=layer, top_k=top_k, recurring_frac=recurring_frac, min_images=min_images, norm_ratio=norm_ratio, vocab_chunk=vocab_chunk, - max_cases=max_cases) + reference=reference, reference_media=reference_media, max_cases=max_cases) def _run(self, model: "Model", cases: "CaseBatch") -> Result: import torch @@ -151,6 +172,41 @@ def nearest(x: Any) -> "tuple[Any, Any]": best_s, best_i = s, merged_i.gather(-1, order) return best_s, best_i + def fingerprint(x: Any) -> tuple: + # The media tokens precede the question, so several questions about one + # image give identical media states: count each image once. + return (tuple(x.shape), round(float(x.float().sum()), 2), + tuple(round(v, 3) for v in x[0, :8].float().tolist())) + + def reference_recurring() -> "tuple[set, Counter, int]": + """Recurring top-1 ids over the reference's first distinct media, cached on the model.""" + key = (layer, self.recurring_frac, self.min_images, self.reference_media, + tuple(str(c.id) for c in self.reference)) + cache = module.__dict__.setdefault("_evalrx_embed_lens_reference", {}) + if key not in cache: + counts: Counter = Counter() + seen: set = set() + for ref in self.reference: + if len(seen) >= self.reference_media: + break + with torch.no_grad(), residual_hooks(model, capture={layer: None}, analyzer=self.name) as res: + trace = model.forward(ref.inputs, capture={Capability.LOGITS}, spec=spec) + _, positions = media_positions(trace) + if not positions: + continue + with torch.no_grad(): + x = res.captured[layer][positions] + mark = fingerprint(x) + if mark not in seen: + seen.add(mark) + counts.update(set(nearest(x)[1][:, 0].tolist())) + del trace, res, x + n = len(seen) + rec = ({tid for tid, k in counts.items() if k >= self.recurring_frac * n} + if n >= self.min_images else set()) + cache[key] = (rec, counts, n) + return cache[key] + rows: list[dict[str, Any]] = [] per_token: dict[str, dict[str, Any]] = {} prompt_sims: dict[str, dict[str, float]] = {} @@ -159,6 +215,7 @@ def nearest(x: Any) -> "tuple[Any, Any]": seen_media: set = set() # fingerprints of the media already counted skipped: Counter = Counter() spec = CaptureSpec(to_cpu=False) + texts: dict[str, str] = {} for case in cases.stratified_head(self.max_cases): with torch.no_grad(), residual_hooks(model, capture={layer: None}, analyzer=self.name) as res: trace = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) @@ -186,12 +243,9 @@ def nearest(x: Any) -> "tuple[Any, Any]": best = (xn @ w.T).max(0).values.tolist() grounding = {word: round(s, 4) for word, s in zip(words, best)} top1 = ids[:, 0].tolist() - # The media tokens precede the question, so several questions about one - # image give identical media states: count each image once. - fingerprint = (tuple(x.shape), round(float(x.float().sum()), 2), - tuple(round(v, 3) for v in x[0, :8].float().tolist())) - if fingerprint not in seen_media: - seen_media.add(fingerprint) + mark = fingerprint(x) + if mark not in seen_media: + seen_media.add(mark) images_with.update(set(top1)) median = float(norms.median()) or 1e-12 per_token[case.id] = { @@ -203,6 +257,7 @@ def nearest(x: Any) -> "tuple[Any, Any]": prompt_sims[case.id] = grounding prompt_words[case.id] = (tuple(t for p, t in enumerate(trace.token_ids) if p not in media_set), set(words)) + texts[case.id] = str(case.inputs.prompt) row: dict[str, Any] = { "sample_id": case.id, "el_n_media_tokens": len(media), @@ -219,15 +274,23 @@ def nearest(x: Any) -> "tuple[Any, Any]": if not rows: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") n_cases, n_images = len(rows), len(seen_media) - query, query_inferred = specific_words(prompt_words) + if self.reference is not None: + query, query_inferred = reference_specific_words(texts, [c.inputs.prompt for c in self.reference], + tokenizer, special) + else: + query, query_inferred = specific_words(prompt_words) for row in rows: sims = {w: s for w, s in prompt_sims[row["sample_id"]].items() if w in query[row["sample_id"]]} if sims: row["el_query_word"] = max(sims, key=sims.get) row["el_query_sim"] = sims[row["el_query_word"]] recurring: set = set() - if n_images >= self.min_images: - recurring = {tid for tid, count in images_with.items() if count >= self.recurring_frac * n_images} + if self.reference is not None: + recurring, images_with, n_recurring_images = reference_recurring() + else: + n_recurring_images = n_images + if n_images >= self.min_images: + recurring = {tid for tid, count in images_with.items() if count >= self.recurring_frac * n_images} specific_counts: Counter = Counter() recurring_mass: Counter = Counter() total_tokens = 0 @@ -260,7 +323,9 @@ def label(tid: int) -> str: "top_k": self.top_k, "layer_used": layer, "n_layers": n_layers, - "recurring_inferred": n_images >= self.min_images, + "recurring_inferred": n_recurring_images >= self.min_images, + "recurring_from": "reference" if self.reference is not None else "batch", + "n_recurring_images": n_recurring_images, "recurring_words": [ {"word": label(tid), "token_id": int(tid), "n_images": images_with[tid], "token_share": round(recurring_mass[tid] / max(1, total_tokens), 4)} @@ -275,8 +340,9 @@ def label(tid: int) -> str: "per_case": rows, "_caveat": ( f"Nearest neighbours by cosine similarity in the input-embedding table, read at the " - f"input of decoder layer {layer}. 'Recurring' is inferred from this batch (a nearest word " - "shared across at least recurring_frac of the distinct images), not from " + f"input of decoder layer {layer}. 'Recurring' is inferred from " + + ("the reference's first distinct images" if self.reference is not None else "this batch") + + " (a nearest word shared across at least recurring_frac of the distinct images), not from " "checkpoint-specific token ids; with fewer than min_images distinct images nothing " "is called recurring. The rule is the paper's, for the input layer: read deep, a " "scene word common to most of the batch's images can recur too." diff --git a/evalrx/analyzers/lens/patchscope.py b/evalrx/analyzers/lens/patchscope.py index 7b054709..9d679be9 100644 --- a/evalrx/analyzers/lens/patchscope.py +++ b/evalrx/analyzers/lens/patchscope.py @@ -26,7 +26,9 @@ per-token word map and tallied (content words only) across cases. Per case, ``ps_media_query_hits`` counts the media readouts that are one of the case's own question words — prompt words in at most half of the batch's distinct - prompts, so template words ("image", "answer") never count. + prompts (or of ``reference``'s), so template words ("image", "answer") never + count. With ``reference`` (a fixed set of cases) every row is the same + whichever cases share its batch. The patch is checked once per run, on the fixed decoding prompt (it does not depend on the case): patching the placeholder with its own residual must leave @@ -44,7 +46,13 @@ from collections import Counter from typing import TYPE_CHECKING, Any -from evalrx.analyzers._internals.words import STOP, content_word, decode_word, specific_words +from evalrx.analyzers._internals.words import ( + STOP, + content_word, + decode_word, + reference_specific_words, + specific_words, +) from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer @@ -70,6 +78,8 @@ class PatchscopeAnalyzer(Analyzer): media_layers: layers at which every media token is decoded too, spread over the stack above the embedding (which decodes to noise); 0 = off. batch_rows: rows per batched decoding forward. + reference: fixed cases whose prompts tell the template words from the + case's own question words (``None`` = the batch's prompts). max_cases: label-stratified cap; 0 (the default) = every case. Cost per case: 1 forward + one batched forward of the short target prompt (+ media tokens × media_layers rows). @@ -97,9 +107,10 @@ class PatchscopeAnalyzer(Analyzer): def __init__(self, target: str = "prediction", target_prompt: str = IDENTITY_PROMPT, n_points: int = 0, media_layers: int = 0, batch_rows: int = 64, - max_cases: int = 0) -> None: + reference: "CaseBatch | None" = None, max_cases: int = 0) -> None: super().__init__(target=target, target_prompt=target_prompt, n_points=n_points, - media_layers=media_layers, batch_rows=batch_rows, max_cases=max_cases) + media_layers=media_layers, batch_rows=batch_rows, reference=reference, + max_cases=max_cases) def _run(self, model: "Model", cases: "CaseBatch") -> Result: import torch @@ -180,6 +191,7 @@ def grab(mod, args, kwargs): media_words: dict[str, dict[int, list]] = {} word_counts: Counter = Counter() prompt_words: dict[str, tuple[Any, set[str]]] = {} + texts: dict[str, str] = {} skipped: Counter = Counter() for case in cases.stratified_head(self.max_cases): with torch.no_grad(), residual_hooks(model, capture=dict.fromkeys(set(layers) | set(media_at)), @@ -228,6 +240,7 @@ def grab(mod, args, kwargs): prompt = [tid for pos, tid in enumerate(trace_ids) if pos not in media_set] prompt_words[case.id] = (tuple(prompt), { w for w in (content_word(tokenizer, t, special) for t in prompt) if w is not None}) + texts[case.id] = str(case.inputs.prompt) rows = [(layer, states[layer][pos]) for layer in media_at for pos in media] ids = decode(rows).argmax(-1).tolist() words: dict[int, list] = {} @@ -242,7 +255,11 @@ def grab(mod, args, kwargs): if not per_case: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") - query, query_inferred = specific_words(prompt_words) + if self.reference is not None: + query, query_inferred = reference_specific_words(texts, [c.inputs.prompt for c in self.reference], + tokenizer, special) + else: + query, query_inferred = specific_words(prompt_words) for row in per_case: words = media_words.get(row["sample_id"]) own = query.get(row["sample_id"]) diff --git a/evalrx/analyzers/lens/tuned_lens.py b/evalrx/analyzers/lens/tuned_lens.py index 3698b20f..c893e447 100755 --- a/evalrx/analyzers/lens/tuned_lens.py +++ b/evalrx/analyzers/lens/tuned_lens.py @@ -9,10 +9,13 @@ model's outputs, never PASS/FAIL. Here the translators are fit on token positions sampled from the batch being -analysed (a pretraining corpus is not at hand), then each case's final prompt -position is read through them; ``fit_kl`` in the findings reports how well the -lens fits. Fitted translators are cached on the model per configuration and can -be saved to / loaded from ``translators_path``. +analysed (a pretraining corpus is not at hand), or from a fixed set of +``fit_cases``, then each case's final prompt position is read through them; +``fit_kl`` in the findings reports how well the lens fits. With ``fit_cases`` +a case's row does not depend on the rest of its batch, so the lens can run on +a growing sample in chunks. Fitted translators are cached on the model per +configuration (and fit set) and can be saved to / loaded from +``translators_path``. Per-case columns mirror ``logit_lens`` (decision depth, interim peak, late drop) plus the tuned KL to the final distribution in the middle of the stack. @@ -71,8 +74,10 @@ class TunedLensAnalyzer(Analyzer): """Tuned-lens readout of the final prompt position, per case. Hyper-parameters: - train_tokens: token positions sampled (across the analysed cases) to fit - the translators; the final position of every case is included. + train_tokens: token positions sampled (across the fit cases) to fit the + translators; the final position of every fit case is included. + fit_cases: fixed cases the translators are fit on; ``None`` = the + analysed batch (then every row depends on the whole batch). steps: Adam steps per layer translator. batch_size: positions per step. lr: Adam learning rate. @@ -100,9 +105,10 @@ class TunedLensAnalyzer(Analyzer): def __init__(self, train_tokens: int = 4096, steps: int = 200, batch_size: int = 256, lr: float = 1e-3, seed: int = 0, translators_path: "str | None" = None, - max_cases: int = 0) -> None: + fit_cases: "CaseBatch | None" = None, max_cases: int = 0) -> None: super().__init__(train_tokens=train_tokens, steps=steps, batch_size=batch_size, lr=lr, - seed=seed, translators_path=translators_path, max_cases=max_cases) + seed=seed, translators_path=translators_path, fit_cases=fit_cases, + max_cases=max_cases) def _run(self, model: "Model", cases: "CaseBatch") -> Result: import torch @@ -116,17 +122,23 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: norm = model.final_norm() if hasattr(model, "final_norm") else None # One forward per case: keep every layer's final-position state for the - # readout, plus a seeded sample of positions for fitting the translators. + # readout, plus a seeded sample of positions for fitting the translators + # (from the fit cases instead, when they are given and not fit yet). rows = cases.stratified_head(self.max_cases) if not rows: raise ValueError("tuned_lens: empty case batch") + fit_rows = list(self.fit_cases) if self.fit_cases is not None else rows + if not fit_rows: + raise ValueError("tuned_lens: empty fit_cases") + fit_key = None if self.fit_cases is None else ( + "fit_cases", tuple(str(c.id) for c in fit_rows), self.train_tokens, self.steps, self.batch_size, + self.lr, self.seed) gen = torch.Generator().manual_seed(self.seed) - per_case_budget = max(1, self.train_tokens // len(rows)) - last_states: list[tuple[str, list]] = [] + per_case_budget = max(1, self.train_tokens // len(fit_rows)) train: "list[list] | None" = None - for case in rows: - hidden = model.forward(case.inputs, capture={Capability.HIDDEN_STATES}).require( - Capability.HIDDEN_STATES) + + def sample(hidden: Any) -> None: + nonlocal train seq = hidden[0].shape[0] pick = torch.randperm(seq, generator=gen)[: per_case_budget - 1].tolist() pick = sorted(set(pick) | {seq - 1}) @@ -134,13 +146,24 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: train = [[] for _ in hidden] for layer, h in enumerate(hidden): train[layer].append(h[pick].detach().float().cpu()) + + last_states: list[tuple[str, list]] = [] + for case in rows: + hidden = model.forward(case.inputs, capture={Capability.HIDDEN_STATES}).require( + Capability.HIDDEN_STATES) + if self.fit_cases is None: + sample(hidden) last_states.append((case.id, [h[-1].detach().float().cpu() for h in hidden])) - data = [torch.cat(chunks) for chunks in train] - n_layers = len(data) - 1 # entries 0..L-1 premature, L = final (post-norm) - dim = data[0].shape[1] - apply_norm = _functional_norm(norm, data[0][:1].to(device)) + n_layers = len(last_states[0][1]) - 1 # entries 0..L-1 premature, L = final (post-norm) + dim = last_states[0][1][0].shape[0] + if self.fit_cases is not None and self._cached(model, fit_key) is None: + for case in fit_rows: + sample(model.forward(case.inputs, capture={Capability.HIDDEN_STATES}).require( + Capability.HIDDEN_STATES)) + data = [torch.cat(chunks) for chunks in train] if train is not None else None + apply_norm = _functional_norm(norm, last_states[0][1][0][None].to(device)) - translators, fit_kl = self._translators(model, data, W, apply_norm, n_layers, dim, device) + translators, fit_kl = self._translators(model, data, W, apply_norm, n_layers, dim, device, key=fit_key) def layer_logprobs(states: list) -> list: out = [] @@ -179,35 +202,43 @@ def layer_logprobs(states: list) -> list: findings={ "n_cases_analyzed": len(per_case), "n_layers": n_layers, - "n_train_tokens": int(data[0].shape[0]), + "n_train_tokens": int(data[0].shape[0]) if data is not None else None, + "fit_on": "fit_cases" if self.fit_cases is not None else "batch", "fit_kl_per_layer": [round(k, 4) for k in fit_kl], "fit_kl_mean": round(sum(fit_kl) / max(1, len(fit_kl)), 4), "final_norm_applied": norm is not None, "per_case": per_case, "_caveat": ( - "Translators are fit label-free on token positions of the analysed batch " - "itself (no separate corpus), so they are in-sample for these prompts; " - "fit_kl_per_layer is the held-in KL after fitting." + "Translators are fit label-free on token positions of " + + ("the fixed fit_cases" if self.fit_cases is not None else + "the analysed batch itself (no separate corpus), so they are in-sample for these prompts") + + "; fit_kl_per_layer is the held-in KL after fitting." ), }, ) - def _translators(self, model: Any, data: list, W: Any, apply_norm: Any, n_layers: int, - dim: int, device: Any) -> "tuple[list, list[float]]": - """Fit (or load / reuse) one affine translator per premature layer.""" - import os - - import torch - - key = (n_layers, dim, int(data[0].shape[0]), self.steps, self.batch_size, self.lr, self.seed) - module = None + def _cache(self, model: Any) -> dict: try: from evalrx.analyzers._internals.access import torch_module module = torch_module(model, self.name) except ValueError: - pass - cache = module.__dict__.setdefault("_evalrx_tuned_lens", {}) if module is not None else {} + return {} + return module.__dict__.setdefault("_evalrx_tuned_lens", {}) + + def _cached(self, model: Any, key: Any) -> "tuple[list, list[float]] | None": + return self._cache(model).get(key) + + def _translators(self, model: Any, data: "list | None", W: Any, apply_norm: Any, n_layers: int, + dim: int, device: Any, key: Any = None) -> "tuple[list, list[float]]": + """Fit (or load / reuse) one affine translator per premature layer.""" + import os + + import torch + + if key is None: + key = (n_layers, dim, int(data[0].shape[0]), self.steps, self.batch_size, self.lr, self.seed) + cache = self._cache(model) if key in cache: return cache[key] path = self.translators_path diff --git a/evalrx/analyzers/patching/attribution_patching.py b/evalrx/analyzers/patching/attribution_patching.py index 9ca04ef9..a0083f99 100644 --- a/evalrx/analyzers/patching/attribution_patching.py +++ b/evalrx/analyzers/patching/attribution_patching.py @@ -219,6 +219,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: torch_module, ) from evalrx.analyzers._internals.residual import residual_hooks + from evalrx.analyzers._internals.seeds import case_seed from evalrx.analyzers._internals.targets import build_margin from evalrx.analyzers.patching.causal_trace import ( _merge, @@ -283,7 +284,7 @@ def attributed(clean_h: list, corrupt_h: list, grads: list) -> Any: trusted: set = set() # traced cases whose estimates passed their exact check skipped: Counter = Counter() slots: Counter = Counter() - for index, case in enumerate(cases.stratified_head(self.max_cases)): + for case in cases.stratified_head(self.max_cases): clean_variant = (case.inputs, {}, (None, None)) # A gray image's DeepStack copies are interpolated too: record both runs' copies. clean_rec: "dict | None" = {} if (integrated and mergers and self.corruption == "gray") else None @@ -309,7 +310,7 @@ def attributed(clean_h: list, corrupt_h: list, grads: list) -> Any: variants, why = corrupted_variants( case.inputs, self.corruption, slot=slot, media=media, embeddings=clean_h[0][media], deepstack=bool(mergers), noise_scale=self.noise_scale, n_noise=self.n_noise, - seed=self.seed * 100003 + index) + seed=case_seed(self.seed, case)) if not variants: skipped[why] += 1 continue diff --git a/evalrx/analyzers/patching/causal_trace.py b/evalrx/analyzers/patching/causal_trace.py index 82013a5c..72992571 100755 --- a/evalrx/analyzers/patching/causal_trace.py +++ b/evalrx/analyzers/patching/causal_trace.py @@ -41,6 +41,7 @@ from contextlib import contextmanager, nullcontext from typing import TYPE_CHECKING, Any, Iterator +from evalrx.analyzers._internals.seeds import case_seed from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer @@ -192,7 +193,8 @@ class CausalTraceAnalyzer(Analyzer): ~0.06–0.125 at typical magnitudes, so a smaller effect yields recoveries dominated by rounding. target: ``"prediction"`` or ``"gold"``. - seed: noise seed (offset per case, so reruns reproduce). + seed: noise seed, combined with each case's content: reruns reproduce, and + a case's noise (so its row) does not depend on its batch. max_cases: label-stratified cap; 0 (the default) = every case. Cost per case: 1 + n_noise · (1 + 2 · n_points) logits-only forwards. """ @@ -258,7 +260,7 @@ def margin_with(variant: "tuple[Any, dict, Any]", margin: Any, restore: "dict | skipped: Counter = Counter() slots: Counter = Counter() sites = sorted(set(points) | {0}) - for index, case in enumerate(cases.stratified_head(self.max_cases)): + for case in cases.stratified_head(self.max_cases): with residual_hooks(model, capture={layer: None for layer in sites}, analyzer=self.name) as clean: probe = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) @@ -281,7 +283,7 @@ def margin_with(variant: "tuple[Any, dict, Any]", margin: Any, restore: "dict | variants, why = corrupted_variants( case.inputs, self.corruption, slot=slot, media=media, embeddings=clean_media[0][1], deepstack=bool(mergers), noise_scale=self.noise_scale, n_noise=self.n_noise, - seed=self.seed * 100003 + index) + seed=case_seed(self.seed, case)) if not variants: skipped[why] += 1 continue diff --git a/evalrx/analyzers/uncertainty/self_consistency.py b/evalrx/analyzers/uncertainty/self_consistency.py index 59f5a203..277534f7 100755 --- a/evalrx/analyzers/uncertainty/self_consistency.py +++ b/evalrx/analyzers/uncertainty/self_consistency.py @@ -91,6 +91,11 @@ class SelfConsistencyAnalyzer(Analyzer): entailment_fn: ``callable(a, b) -> bool`` equivalence test used for that clustering; defaults to :func:`lexical_equivalent`. answer_fn: ``callable(text) -> str`` applied BEFORE comparing. + seed: the case's samples are drawn under torch's random state seeded + from this and the case's content (prompt and media), so a case + gets the same samples whatever batch it is in and in every + rerun; ``None`` = the global random state as it stands. A model + that samples on the provider's side (an API) is not affected. ``answer_fn`` is what makes this usable on a reasoning model. Without it the comparison is over the whole generation, and two samples of a 3,000-token @@ -122,15 +127,21 @@ def __init__( semantic: bool = True, entailment_fn: Optional[Callable[[str, str], bool]] = None, answer_fn: Optional[Callable[[str], str]] = None, + seed: Optional[int] = 0, ) -> None: - super().__init__(n=n, gen_kwargs=gen_kwargs or {}, semantic=semantic) + super().__init__(n=n, gen_kwargs=gen_kwargs or {}, semantic=semantic, seed=seed) # ctor name, so sklearn-style get_params() reflection works self.entailment_fn = entailment_fn or lexical_equivalent self.answer_fn = answer_fn def _run(self, model: "Model", cases: "CaseBatch") -> Result: + from contextlib import nullcontext + + from evalrx.analyzers._internals.seeds import case_seed, seeded + case = cases[0] - samples = [model.generate(case.inputs, **self.gen_kwargs) for _ in range(self.n)] + with seeded(case_seed(self.seed, case)) if self.seed is not None else nullcontext(): + samples = [model.generate(case.inputs, **self.gen_kwargs) for _ in range(self.n)] raw = [str(s).strip().lower() for s in samples] if self.answer_fn is not None: norm = [str(self.answer_fn(s) or "").strip().lower() for s in samples] diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/probing/actions.py index c8bc3a1e..0f481a45 100644 --- a/evalrx/eval_agent/probing/actions.py +++ b/evalrx/eval_agent/probing/actions.py @@ -84,6 +84,10 @@ class PlanStep: ``min_output_tokens``: the step asks for text before the answer (e.g. a description), so a known output cap below this leaves it nothing to read. + + ``deferred``: a battery step no route reads (a descriptive reading): the + rules run it once the sample has settled, and the scored scheduler takes it + as a candidate of the layer it serves instead of running it up front. """ analyzer: str @@ -100,6 +104,7 @@ class PlanStep: reuse_note: str = "" caveat: str = "" min_output_tokens: int = 0 + deferred: bool = False @property def name(self) -> str: diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 5280fd90..031b1ca4 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -23,11 +23,13 @@ controller decides to expand. The sample then doubles along the sampler's rank prefixes, and the battery runs again only where it has to: - * steps whose per-case rows do not depend on the batch run on the new cases - alone, and their old rows stay current; - * steps that infer something from the batch (``embed_lens``, ``patchscope``) - are not read by the routes, so nothing the expansion rule looks at depends - on them: they run once, on the whole sample the expansions settle on. + * every step's per-case rows are independent of the batch (the lenses tell + question words from a fixed reference, the tuned lens is fit on fixed + EXPLORE cases, the causal trace seeds noise per case), so steps run on the + new cases alone and the old rows stay current; + * the descriptive steps no route reads (``embed_lens``, ``patchscope``) are + ``deferred``: nothing the expansion rule looks at depends on them, so they + run once the expansions have settled. Steps run in chunks of ``chunk`` cases (FAIL and PASS alternating), with the budget checked before each chunk on the cost measured so far. @@ -148,8 +150,9 @@ #: moves when the model is told not to default to it from one that does not. THRESHOLD_STRATEGIES = {"baseline": "{prompt}", "sensitive": _PROMPT_STRATEGIES["sensitive"]} -_BATCH_WORDS = ("the question words (and recurring media words) are inferred from the batch's prompts " - "and images") +#: Cases of EXPLORE (in the sampler's rank order) the tuned lens is fit on: fixed, so a +#: case's readout does not depend on the sample it is read with. +FIT_CASES = 32 #: What a FAIL case on each route has shown, as the judge is told. ROUTE_MEANING = { @@ -188,12 +191,12 @@ PlanStep("embed_lens", {"layer": 0.9}, "S2", "nearest vocabulary words of the media tokens late in the stack: how close the " "case's own question word gets", - calls_per_case={"forward": 1}, reuse=False, reuse_note=_BATCH_WORDS), + calls_per_case={"forward": 1}, deferred=True), PlanStep("patchscope", {"target": "gold", "media_layers": 3}, "S3", "decode the answer position at every layer and the media tokens at three depths: " "whether the gold answer was readable before the output, and whether the question " "word is read off the media", - fidelity_check="patch", calls_per_case={"forward": 1}, reuse=False, reuse_note=_BATCH_WORDS), + fidelity_check="patch", calls_per_case={"forward": 1}, deferred=True), ) @@ -635,6 +638,15 @@ def run_triage( extras = {k: dict(v) for k, v in (analyzer_kwargs or {}).items()} # swap donors come from the whole partition the sample was drawn from extras.setdefault("modality_ablation", {}).setdefault("donor_pool", explore) + # Fixed references in the sampler's rank order, so a case's row never depends on the + # sample it is read with: the lenses tell question words (and embed_lens recurring + # words) from them, and the tuned lens is fit on the first FIT_CASES of them. + from evalrx.core.case import CaseBatch + + ranked = CaseBatch(sorted(explore, key=lambda c: rank(seed, str(c.id)))) + for name in ("embed_lens", "patchscope"): + extras.setdefault(name, {}).setdefault("reference", ranked) + extras.setdefault("tuned_lens", {}).setdefault("fit_cases", CaseBatch(list(ranked)[:FIT_CASES])) max_fail = max(int(n_fail), int(max_fail or n_fail)) n_available = sum(1 for c in explore if getattr(getattr(c, "label", None), "value", None) == "fail") run = _Run(model, explore, ledger, context={"policy": POLICY_VERSION, "model": model_identity}, @@ -666,7 +678,7 @@ def manifest() -> None: # A step whose rows depend on the batch would have to re-run on every larger # sample. When the routes do not read it, nothing the expansion rule looks at # depends on it either, so it runs once, on the sample the expansions settle on. - deferred = [s for s in battery if not s.reuse and s.name not in ROUTE_STEPS] + deferred = [s for s in battery if s.deferred or (not s.reuse and s.name not in ROUTE_STEPS)] immediate = [s for s in battery if s not in deferred] revision = 0 for step in immediate: diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index c05d566c..a82334fb 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -51,10 +51,6 @@ ROUTE_ORDER = ("H", "N", "U", "S", "X") DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} -_NOISE_BY_POSITION = "the corruption noise is seeded by the case's position in the batch" -_FIT_ON_BATCH = "the translators are fit on the batch" - - #: Room for a description before the answer, asked per call (the task's own cap #: is sized for the answer alone: 16 tokens on POPE). DESCRIBE_OUTPUT_TOKENS = 256 @@ -96,7 +92,7 @@ class Layer: key="termination_continue", calls_per_case={"generate": 1}),)), Layer("N1", "N", "does the media path carry a measurable effect on the gold answer", ( PlanStep("causal_trace", {"target": "gold"}, "N1", "corrupt the media, restore one site at a time", - calls_per_case={"forward": 20}, reuse=False, reuse_note=_NOISE_BY_POSITION),), + calls_per_case={"forward": 20}),), served_by=("attention_knockout",)), Layer("N2", "N", "does reading the media with sharper or flatter attention change the gold margin", ( PlanStep("attention_temperature", {"target": "gold"}, "N2", "rescale the media attention temperature", @@ -124,8 +120,8 @@ class Layer: fidelity_check="edit", calls_per_case={"backward": 1}))), Layer("S2", "S", "is the case's own question word readable off the media tokens", (), served_by=("embed_lens",)), Layer("S3", "S", "was the gold answer readable before the output", ( - PlanStep("tuned_lens", {}, "S3", "fitted per-layer readout of the answer position", - calls_per_case={"forward": 1}, reuse=False, reuse_note=_FIT_ON_BATCH), + PlanStep("tuned_lens", {}, "S3", "fitted per-layer readout of the answer position (translators " + "fit once on a fixed set of EXPLORE cases)", calls_per_case={"forward": 1}), PlanStep("layer_contrast", {}, "S3", "early-vs-late layer contrast at the answer position", calls_per_case={"forward": 1})), served_by=("patchscope",)), diff --git a/tests/test_analyzers/test_self_consistency_seed.py b/tests/test_analyzers/test_self_consistency_seed.py new file mode 100644 index 00000000..3707c350 --- /dev/null +++ b/tests/test_analyzers/test_self_consistency_seed.py @@ -0,0 +1,66 @@ +"""self_consistency draws a case's samples from a seed of its content. + +The same case gets the same samples in every run and whatever else ran +before it; another seed draws others; the caller's random state is left as +it was; ``seed=None`` keeps the old behaviour (the global random state). +""" + +from __future__ import annotations + +import pytest + +from evalrx.core.capability import Capability +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.core.model import Model + +torch = pytest.importorskip("torch") + + +class _Sampler(Model): + """Answers drawn from torch's global random state, like a sampling local model.""" + + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text"}) + + def generate(self, inputs, **kwargs): + return ["yes", "no", "maybe", "unsure"][int(torch.randint(0, 4, (1,)))] + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +def _case(prompt): + return FailureCase(inputs=Inputs(prompt=prompt), expected="yes", observed="no", label=Label.FAIL) + + +def _samples(analyzer, case): + return analyzer.run(_Sampler(), CaseBatch([case])).artifacts["samples"] + + +def test_a_case_gets_the_same_samples_in_every_run_whatever_ran_before(): + from evalrx.analyzers.uncertainty.self_consistency import SelfConsistencyAnalyzer + + a, b = _case("is it red?"), _case("is it blue?") + first = _samples(SelfConsistencyAnalyzer(n=8), a) + torch.rand(100) # someone else used the random state + _samples(SelfConsistencyAnalyzer(n=8), b) # another case ran first + assert _samples(SelfConsistencyAnalyzer(n=8), a) == first + # a case with another id but the same content draws the same; another seed draws others + assert _samples(SelfConsistencyAnalyzer(n=8), _case("is it red?")) == first + assert _samples(SelfConsistencyAnalyzer(n=8, seed=1), a) != first + assert len(set(first)) > 1 # still n samples, not one repeated + + +def test_the_callers_random_state_is_left_as_it_was_and_none_keeps_the_global_state(): + from evalrx.analyzers.uncertainty.self_consistency import SelfConsistencyAnalyzer + + torch.manual_seed(123) + expected = torch.rand(3) + torch.manual_seed(123) + _samples(SelfConsistencyAnalyzer(n=4), _case("is it red?")) + assert torch.equal(torch.rand(3), expected) + unseeded = SelfConsistencyAnalyzer(n=8, seed=None) + torch.manual_seed(5) + one = _samples(unseeded, _case("is it red?")) + torch.manual_seed(6) + assert _samples(unseeded, _case("is it red?")) != one diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_probing_mvp2.py index ba8e25d9..99d1f8d6 100644 --- a/tests/test_eval_agent/test_probing_mvp2.py +++ b/tests/test_eval_agent/test_probing_mvp2.py @@ -111,9 +111,11 @@ def test_expansion_runs_only_new_cases_and_matches_drawing_the_larger_sample_at_ if e["kind"] == "expansion" and e["status"] != "not_applicable": assert next(s for s in BATTERY if s.name == e["key"]).reuse and e["n_cases"] == n_new # the batch-dependent steps the routes do not read run once, on the settled sample + # the descriptive steps no route reads wait for the settled sample, then run on it once (in chunks) for key in ("embed_lens", "patchscope"): - (once,) = [e for e in grown["executions"] if e["key"] == key] - assert (once["revision"], once["n_cases"]) == (1, len(direct["sample"]["case_ids"])) + runs = [e for e in grown["executions"] if e["key"] == key] + assert {e["revision"] for e in runs} == {1} + assert sum(e["n_cases"] for e in runs) == len(direct["sample"]["case_ids"]) # every case reads the same as when the 8-FAIL sample is drawn at once, for the same calls assert {r["case_id"]: _strip(r) for r in grown["cases"]} == {r["case_id"]: _strip(r) for r in direct["cases"]} assert _generated(grown) == _generated(direct) == grown_model.n_generate == direct_model.n_generate @@ -287,7 +289,10 @@ def test_a_refusal_on_any_chunk_refuses_the_step_on_every_case(): plain = StepEvidence(_step("self_consistency"), [_obs("sc", ["a", "b"]), _obs("sc", ["c"], status=FAILED)]) assert plain.for_case("a").status == OK and plain.for_case("c").status == FAILED assert plain.todo(["a", "b", "c", "d"]) == ["d"] - batchy = StepEvidence(_step("embed_lens"), [_obs("el", ["a", "b"])]) + from evalrx.eval_agent.probing.actions import PlanStep + + batchy = StepEvidence(PlanStep("x", {}, "S", "reads the batch", reuse=False, reuse_note="test"), + [_obs("el", ["a", "b"])]) assert batchy.todo(["a", "b"]) == [] and batchy.todo(["a", "b", "c"]) == ["a", "b", "c"] @@ -348,7 +353,8 @@ def test_budget_estimates_come_from_the_same_steps_earlier_seconds_and_charge_th #: ``per_case`` steps run once per case by construction. _CHECKED = {"answer_extraction_audit", "termination_audit", "modality_ablation", "prompt_contrast", "attention_knockout", "attention_temperature", "attention_sensitivity", "gradcam", - "generic_attention", "layer_contrast", "format_sensitivity"} + "generic_attention", "layer_contrast", "format_sensitivity", + "embed_lens", "patchscope", "tuned_lens", "causal_trace"} def test_every_reuse_step_is_covered_by_a_decomposability_check(): @@ -395,6 +401,9 @@ def vlm_cases(): return CaseBatch(out) +REF = "" + + @pytest.mark.parametrize("name, config", [ ("attention_knockout", {"target": "gold"}), ("attention_temperature", {"target": "gold"}), @@ -402,12 +411,18 @@ def vlm_cases(): ("gradcam", {"target": "gold"}), ("generic_attention", {"target": "gold"}), ("layer_contrast", {}), + # with a fixed reference / fit set and per-case noise seeds (the triage passes EXPLORE) + ("embed_lens", {"layer": 0.9, "reference": REF}), + ("patchscope", {"target": "gold", "media_layers": 2, "reference": REF}), + ("tuned_lens", {"steps": 10, "fit_cases": REF}), + ("causal_trace", {"target": "gold", "min_effect": 0.0, "n_points": 3}), ]) def test_white_box_reuse_steps_give_the_same_rows_whatever_shares_the_batch(vlm_cases, name, config): from evalrx.core.registry import registry from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") + config = {k: (vlm_cases if v == REF else v) for k, v in config.items()} same, rows = _split_equals_whole(registry.analyzers.get(name)(**config), model, vlm_cases) assert rows and same From 1420c3a1e8d573016658445036f3e1154a4a2f40 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 18 Oct 2026 21:50:42 -0700 Subject: [PATCH 08/26] triage MVP-3: decidable D, alternatives priced by R, exploration share - D counts each conflicting pair of live explanations by how decidable the conflict is on the route's cases (explanations.decidability, mvp3-explain-2): the cases a side the verdict's interval needs to contradict one prediction with the other true at its reference difference; unmeasured readings take the least favourable spread. - An answered layer offers its other candidates as alternatives: R = 0.5 for the same kind of evidence (PlanStep.evidence) as the tool that answered it, 0 otherwise; the judge is offered them from the first ask (alternative_to). - Exploration takes a share of the spending (--triage-explore-share, default 0.1) instead of every 10th decision, and continues below the gain floor until nothing fits; --triage-weights for ablations (mvp3-score-4). - The judge is asked only while its largest call so far fits the budget; a run with budget-filtered candidates stops for "budget". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 28 ++ docs/agentic_benchmark.md | 4 +- evalrx/benchmark/run.py | 29 +- evalrx/benchmark/runner.py | 4 + evalrx/eval_agent/probing/actions.py | 9 + evalrx/eval_agent/probing/compare.py | 6 + evalrx/eval_agent/probing/controller.py | 255 +++++++++++++----- evalrx/eval_agent/probing/explanations.py | 123 ++++++++- evalrx/eval_agent/probing/rules.py | 29 +- evalrx/eval_agent/probing/scoring.py | 68 +++-- tests/test_analysis/test_run_cli.py | 16 ++ .../test_probing_alternatives.py | 128 +++++++++ tests/test_eval_agent/test_probing_mvp2.py | 3 +- tests/test_eval_agent/test_probing_mvp3.py | 25 +- tests/test_eval_agent/test_probing_mvp3b.py | 76 +++++- 15 files changed, 675 insertions(+), 128 deletions(-) create mode 100644 tests/test_eval_agent/test_probing_alternatives.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 78483238..4cf2aee3 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,34 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed — triage scored scheduler: decidable D, alternatives priced by R, exploration share (MVP-3) + +D counts each conflicting pair of live explanations by how decidable the +conflict is on the route's cases (`explanations.decidability`, version +`mvp3-explain-2`): taking each prediction as true at a reference difference (0 +for `same`, one standard deviation of the reading past the band for +`up`/`down`), the cases a side the verdict's interval needs to contradict the +other; each side scores `min(1, n / needed)` and the conflict the mean. The +spread comes from the step's own measurements in this run, else the least +favourable value, so three FAIL cases settle an unmeasured up-versus-same +conflict to 1/6 where they counted in full before. An answered layer offers its +other candidates as alternatives with R = 0.5 when they give the same kind of +evidence as the tool that answered it (`PlanStep.evidence`) and 0 otherwise; +they close no gap and cover no unit, so they run only on a D above their R, and +the judge is offered them (`alternative_to`) from the first ask. Exploration +takes a share of the spending (`--triage-explore-share`, default 0.1) instead +of every 10th decision, and below the gain floor the run explores until no +candidate fits the share. `--triage-weights` sets the weights of D, T, C and R +for ablations (scoring `mvp3-score-4`). A judge call is asked only while the +largest call so far fits the budget, so a run overshoots by at most its first +call; a run whose remaining candidates are over budget stops for `budget` +even when cheaper zero-gain alternatives are left. On Qwen3.5-0.8B POPE +decidability cut D on the 3-case N route from 0.67-1.0 to 0.11-0.22 and the +unbudgeted D arm's evidence from 1603 s to 1350 s; of 19 alternatives the D arms +ran, 7 were chosen on value and 12 by exploration, so the extra evidence +mostly comes from exploration, and whether D pays for its judge (about 30% of +the evidence cost) still needs MVP-4's validated metric. + ### Changed — triage spends by measurement: chunked steps, no per-analyzer cost prior Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 6aaf1069..9dba08b1 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -35,9 +35,9 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. -**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as is D) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet; one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Every 10th decision explores with a seed, and the run stops when no candidate's gain reaches 0.01. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. +**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet; one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the spending, `--triage-explore-share` (default 0.1), not of the decisions: whenever a candidate other than the best fits — exploration's spending plus its estimate stays within the share of everything spent — a seeded draw among those runs instead. When no candidate's gain reaches 0.01, every feasible candidate is an exploration candidate, and the run stops once none fits. `--triage-weights` (e.g. `c=0`) sets the weights of D, T, C and R for ablations. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. -**Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D is the share of pairs of its route's live explanations whose predictions for it conflict (a pair with `unknown` counts only in the denominator). The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Only each open layer's current candidate is offered for prediction. On Qwen3.5-0.8B POPE D reorders the follow-ups but changes neither what runs nor which pairs the final evidence tells apart, and the judge's two asks (169 s) cost about a sixth of the evidence time; D does not yet discount predictions the route's case count cannot decide. +**Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 028b04c2..4c173f19 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -171,8 +171,15 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "scored scheduler decides one chunk at a time") p.add_argument("--triage-explanations", choices=["none", "judge"], default="none", help="triage_active with --triage-scheduler scored: judge = the --judge-provider/" - "--judge-model judge proposes competing explanations with predictions once per " - "sample revision, giving D (none = D stays 0, no judge is built)") + "--judge-model judge proposes competing explanations with predictions once the " + "sample has settled (and again when the evidence thins them), giving D (none = D " + "stays 0, no judge is built)") + p.add_argument("--triage-weights", default="d=1,t=1,c=1,r=1", + help="triage_active with --triage-scheduler scored: the weights of D, T, C and R in U, " + "as k=v pairs (keys left out keep 1; an ablation sets one to 0)") + p.add_argument("--triage-explore-share", type=float, default=0.1, + help="triage_active with --triage-scheduler scored: the share of the spending exploration " + "may take, on candidates other than the best (0 = none)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, @@ -253,6 +260,10 @@ def run_args(args) -> int: raise ValueError("--triage-n-fail must be positive") if triage and args.triage_max_actions < 0: raise ValueError("--triage-max-actions must be non-negative") + if triage: + triage_weights(args.triage_weights) + if not 0.0 <= args.triage_explore_share < 1.0: + raise ValueError("--triage-explore-share must be in [0, 1)") dataset = args.dataset or T.DEFAULT_TASK[args.modality] task = T.get(dataset) if task.modality != args.modality: @@ -264,5 +275,19 @@ def run_args(args) -> int: return run(args, task, resolved) +def triage_weights(text: str) -> dict[str, float]: + """``"d=1,t=1,c=0"`` -> ``{"d": 1.0, "t": 1.0, "c": 0.0, "r": 1.0}``: the scored scheduler's weights.""" + out = {"d": 1.0, "t": 1.0, "c": 1.0, "r": 1.0} + for part in filter(None, (x.strip() for x in str(text).split(","))): + key, sep, value = part.partition("=") + key = key.strip().lower() + if not sep or key not in out: + raise ValueError(f"--triage-weights: {part!r} is not one of d=, t=, c=, r=") + out[key] = float(value) + if out[key] < 0: + raise ValueError(f"--triage-weights: {key} must be non-negative") + return out + + if __name__ == "__main__": raise SystemExit(main()) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index d188cecb..9161840e 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -412,6 +412,9 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: route summaries, never a case). Outputs go to ``/probing/``. """ from evalrx.eval_agent.probing import explore_confirm_split, run_triage + from evalrx.eval_agent.probing.scoring import Weights + + from .run import triage_weights explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED) runtime = getattr(model, "runtime", None) @@ -452,6 +455,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: per_call_generation=sampling is not None, scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, chunk=int(args.triage_chunk), + weights=Weights(**triage_weights(args.triage_weights)), explore_share=float(args.triage_explore_share), partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "confirm_visible_to_controller": False}, diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/probing/actions.py index 0f481a45..3c9a5553 100644 --- a/evalrx/eval_agent/probing/actions.py +++ b/evalrx/eval_agent/probing/actions.py @@ -88,6 +88,10 @@ class PlanStep: ``deferred``: a battery step no route reads (a descriptive reading): the rules run it once the sample has settled, and the scored scheduler takes it as a candidate of the layer it serves instead of running it up front. + + ``evidence``: the kind of evidence the step gives (default: its analyzer). + Two tools for one layer that give the same kind ask the same question the + same way: once one has answered the layer, the other is redundant (R = 0.5). """ analyzer: str @@ -105,11 +109,16 @@ class PlanStep: caveat: str = "" min_output_tokens: int = 0 deferred: bool = False + evidence: str = "" @property def name(self) -> str: return self.key or self.analyzer + @property + def evidence_kind(self) -> str: + return self.evidence or self.analyzer + @dataclass(frozen=True) class ProbeAction: diff --git a/evalrx/eval_agent/probing/compare.py b/evalrx/eval_agent/probing/compare.py index a3363382..035a8fdf 100644 --- a/evalrx/eval_agent/probing/compare.py +++ b/evalrx/eval_agent/probing/compare.py @@ -73,6 +73,11 @@ def open_units(r: dict[str, Any]) -> list[dict[str, Any]]: # units some tool co "controller_sec": {"baseline": (baseline.get("cost") or {}).get("controller_sec"), "other": (other.get("cost") or {}).get("controller_sec")}, "coverage_gap": gap, "coverage_units": units, + "alternatives": {name: [f"{d['route']}:{d['rule_id']}:{d['key']} (to {d['alternative_to']})" + for d in r["decisions"] if d.get("alternative_to") and d["kind"] == "follow_up"] + for name, r in (("baseline", baseline), ("other", other))}, + "explored": {name: {"decisions": sum(1 for d in r["decisions"] if d.get("choice") == "explore"), + **(r.get("explored") or {})} for name, r in (("baseline", baseline), ("other", other))}, "stop": {"baseline": baseline["stop"], "other": other["stop"]}, } source = next((r for r in (other, baseline) if r.get("explanations")), None) @@ -97,6 +102,7 @@ def markdown(diff: dict[str, Any]) -> str: f"Controller time outside the actions and the judge: {diff['controller_sec']}.", f"Coverage gap left on units some tool can close here (sum): {diff['coverage_gap']} of " f"{diff['coverage_units']} units.", + f"Alternatives run on answered layers: {diff['alternatives']}; exploration: {diff['explored']}.", f"Stop: {diff['stop']}.", ""] if "discrimination" in diff: d = diff["discrimination"] diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 031b1ca4..a5dce05e 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -90,12 +90,16 @@ Hypothesis, Metric, check, + decidability, disagreement, outcome, ) +from evalrx.eval_agent.probing.explanations import spread as reading_spread from evalrx.eval_agent.probing.ledger import Ledger from evalrx.eval_agent.probing.rules import ( + LAYER_READOUT, LAYERS, + MEDIA_ATTENTION_CUT, ROUTE_ORDER, RULES_VERSION, Layer, @@ -174,7 +178,7 @@ calls_per_case={"generate": 2}), PlanStep("attention_knockout", {"target": "gold"}, "N1", "cut text-to-media attention per layer band; margin change of the gold first token", - fidelity_check="edit", calls_per_case={"forward": 5}), + fidelity_check="edit", calls_per_case={"forward": 5}, evidence=MEDIA_ATTENTION_CUT), PlanStep("self_consistency", {"n": 5}, "U", "re-sample each case at the host's frozen sampling settings; an answer that differs " "from the Stage-0 answer is the U signal", @@ -196,7 +200,7 @@ "decode the answer position at every layer and the media tokens at three depths: " "whether the gold answer was readable before the output, and whether the question " "word is read off the media", - fidelity_check="patch", calls_per_case={"forward": 1}, deferred=True), + fidelity_check="patch", calls_per_case={"forward": 1}, deferred=True, evidence=LAYER_READOUT), ) @@ -553,7 +557,7 @@ def run_triage( per_call_generation: bool = True, scheduler: str = "rules", weights: "Weights | None" = None, - explore_every: int = 10, + explore_share: float = 0.1, min_gain: float = 0.01, min_cover: int = 8, budget_usd: float = 0.0, @@ -610,9 +614,9 @@ def run_triage( or ``"scored"`` (MVP-3: the candidate with the highest U = q·[D+T+C−R]₊/(c+ε), see :mod:`.scoring`). Both share the ledger; the scored report is ``triage_report.scored``. - weights, explore_every, min_gain, min_cover: the scored scheduler's weights, - exploration period (every k-th decision), value floor - and per-unit coverage target. + weights, explore_share, min_gain, min_cover: the scored scheduler's weights, + exploration's share of the spending, value floor and + per-unit coverage target. budget_usd: USD cap (0 = none), charged like ``budget_sec`` and checked with the step's earlier USD per case. chunk: cases per chunk of a ``reuse`` step (FAIL and PASS alternating; @@ -622,8 +626,9 @@ def run_triage( explainer: the scored scheduler's source of competing explanations (:mod:`.explanations`): asked once the sample has settled and again when the evidence has thinned a route's live explanations - (at most ``explainer.max_asks`` times); its predictions give - each candidate its D. ``None`` = D stays 0. + (at most ``explainer.max_asks`` times, and only while the largest + call so far fits the budget); its predictions give each + candidate its D. ``None`` = D stays 0. run_logger: optional RunLoggerV2 for per-call model logs. """ if scheduler not in SCHEDULERS: @@ -757,28 +762,108 @@ def do_expand(plan: Any, gaps: list[dict[str, Any]], extra: dict[str, Any]) -> N for name in (*x.served_by, *(c.name for c in x.candidates)): step_layers.setdefault((x.route, name), x) - def outcomes_for(records: list[dict[str, Any]]) -> Callable[[str, str, Metric], dict[str, Any]]: - """``(route, step key, reading) -> outcome``: the reading's FAIL-minus-control difference - on the route's current FAIL cases (the layer's filter applied) and their PASS controls.""" - groups: dict[Any, tuple[list[str], list[str]]] = {} - values: dict[tuple[str, str], dict[str, Any]] = {} + class Readings: + """The current evidence read per case, once per decision. Called as ``(route, step key, + reading) -> outcome``: the reading's FAIL-minus-control difference on the route's current + FAIL cases (the layer's filter applied) and their PASS controls.""" - def get(route: str, key: str, metric: Metric) -> dict[str, Any]: + def __init__(self, records: list[dict[str, Any]]) -> None: + self.records = records + self.groups: dict[Any, tuple[list[str], list[str]]] = {} + self.values: dict[tuple[str, str], dict[str, Any]] = {} + self.spreads: dict[tuple[str, str], "float | None"] = {} + + def value(self, key: str, cid: str) -> dict[str, Any]: + if (key, cid) not in self.values: + self.values[(key, cid)] = follow_up_values(run.evidence[key], run.by_id[cid], answer_fn) + return self.values[(key, cid)] + + def cases(self, route: str, key: str) -> tuple[list[str], list[str]]: + """The route's FAIL cases for *key* (its layer's filter applied) and their PASS controls.""" + layer = step_layers.get((route, key)) + flt = layer.case_filter if layer is not None else None + if (route, flt) not in self.groups: + fail_ids = route_fail_ids(self.records, route, flt) + self.groups[(route, flt)] = (fail_ids, matched_controls(self.records, fail_ids, rank_of)[0]) + return self.groups[(route, flt)] + + def __call__(self, route: str, key: str, metric: Metric) -> dict[str, Any]: ev = run.evidence.get(key) if ev is None or not ev.chunks: return {"n": [0, 0], "observed": "not_measured"} - layer = step_layers.get((route, key)) - flt = layer.case_filter if layer is not None else None - if (route, flt) not in groups: - fail_ids = route_fail_ids(records, route, flt) - groups[(route, flt)] = (fail_ids, matched_controls(records, fail_ids, rank_of)[0]) - fail_ids, controls = groups[(route, flt)] - for cid in (*fail_ids, *controls): - if (key, cid) not in values: - values[(key, cid)] = follow_up_values(ev, run.by_id[cid], answer_fn) - return outcome({cid: values[(key, cid)] for cid in (*fail_ids, *controls)}, fail_ids, controls, metric) + fail_ids, controls = self.cases(route, key) + return outcome({cid: self.value(key, cid) for cid in (*fail_ids, *controls)}, fail_ids, controls, metric) + + def spread(self, key: str, metric: Metric) -> "float | None": + """The reading's spread within FAIL and within PASS cases, over every case the step + measured in this run (``None`` before it measured one).""" + if (key, metric.field) not in self.spreads: + ev = run.evidence.get(key) + groups: dict[str, list[float]] = {"fail": [], "pass": []} + for cid in sorted(ev.covered()) if ev is not None else (): + v = self.value(key, cid) + if v["state"] == "measured" and metric.field in v["values"]: + label = getattr(getattr(run.by_id[cid], "label", None), "value", None) + groups["fail" if label == "fail" else "pass"].append(float(v["values"][metric.field])) + self.spreads[(key, metric.field)] = reading_spread(list(groups.values()), metric.kind) + return self.spreads[(key, metric.field)] + + def decidable(self, route: str, key: str) -> Callable[[str, str, str], dict[str, Any]]: + """``(reading, direction a, direction b) -> decidability`` of a conflict on *route*'s cases.""" + fail_ids, controls = self.cases(route, key) + n = min(len(fail_ids), len(controls)) + metrics = {m.field: m for m in CARDS.get(key, ())} + return lambda field, a, b: decidability(a, b, n, metrics[field], self.spread(key, metrics[field])) + + outcomes_for = Readings + steps_by_name = {s.name: s for s in (*battery, *candidate_steps(layers))} + + def alternatives(st: dict[str, Any]) -> list[tuple[PlanStep, float, str]]: + """``(step, R, the step it is an alternative to)`` for a layer's other candidates that can + still run on the route: those of an answered layer (to the tool that answered it), and of + an open one (to its current candidate). R is 0.5 when the alternative gives the kind of + evidence that tool gives, 0 when it gives another kind (see :mod:`.scoring`).""" + if st["state"] == "done": + base = st.get("via") or "" + elif st["state"] in ("open", "extend"): + base = st["step"].name + else: + return [] + first = steps_by_name.get(base) + target = [*st["_fail_ids"], *st["_control_ids"]] + out = [] + for step in by_rule[st["rule_id"]].candidates: + if step.name == base or step.name in run.blocked: + continue + ev = run.evidence.get(step.name) + if ev is not None and (ev.refused() is not None or not ev.todo(target)): + continue + if run.gate(step, target) is not None: + continue + same = first is not None and step.evidence_kind == first.evidence_kind + out.append((step, 0.5 if same else 0.0, base)) + return out + + Option = tuple[int, dict[str, Any], PlanStep, float, str] # (layer index, state, step, R, alternative to) - return get + def runnable(states: dict[str, list[dict[str, Any]]]) -> tuple[dict[str, list[Option]], dict[str, list[Option]]]: + """Per route, what the scored scheduler may run (each open or extending layer's current + candidate, with R = 0, and the alternatives of its answered layers), and what the judge + is offered: those, and the alternatives of the open layers, which become candidates once + their layer is answered.""" + pool: dict[str, list[Option]] = {} + offer: dict[str, list[Option]] = {} + for route, sts in states.items(): + rows, extra = [], [] + for li, st in enumerate(sts): + alts = [(li, st, step, R, base) for step, R, base in alternatives(st)] + if st["state"] in ("open", "extend"): + rows.append((li, st, st["step"], 0.0, "")) + extra += alts + else: + rows += alts + pool[route], offer[route] = rows, rows + extra + return pool, offer def route_view(records: list[dict[str, Any]], gaps: list[dict[str, Any]] ) -> tuple[dict[str, list[dict[str, Any]]], bool]: @@ -799,24 +884,24 @@ def route_view(records: list[dict[str, Any]], gaps: list[dict[str, Any]] explanation_sets: list[ExplanationSet] = [] - def explanation_request(records: list[dict[str, Any]], states: dict[str, list[dict[str, Any]]], + def explanation_request(records: list[dict[str, Any]], options: dict[str, list[Any]], outcome_of: Callable[[str, str, Metric], dict[str, Any]] ) -> tuple[dict[str, Any], dict[str, dict[str, list[str]]]]: - """What the judge sees, and per route the steps (with their readings) it may predict: - each open layer's current candidate, in a seeded order. A fallback only becomes a - candidate when its layer's first choice fails; predictions on it would mostly go - unchecked (a later ask covers it once it is the candidate).""" + """What the judge sees, and per route the steps (with their readings) it may predict, in a + seeded order: each open layer's current candidate, and every layer's other candidates as + alternatives (to the tool that answered it, or to its current candidate). An alternative + runs once its layer is answered if its D beats its redundancy, so its predictions are + asked for up front.""" offered: dict[str, dict[str, list[str]]] = {} routes: dict[str, Any] = {} - for route, sts in states.items(): + for route, rows in options.items(): to_run: list[dict[str, Any]] = [] - for st in sts: - if st["state"] not in ("open", "extend"): - continue - layer, step = by_rule[st["rule_id"]], st["step"] + for _, st, step, _, alternative_to in rows: + layer = by_rule[st["rule_id"]] if step.name in CARDS and all(c["step"] != step.name for c in to_run): to_run.append({"step": step.name, "tool": step.analyzer, "layer": layer.rule_id, "question": layer.question, "what": step.purpose, + **({"alternative_to": alternative_to} if alternative_to else {}), **({"caveat": step.caveat} if step.caveat else {}), "readings": [m.card() for m in CARDS[step.name]]}) if not to_run: @@ -856,10 +941,14 @@ def explanation_request(records: list[dict[str, Any]], states: dict[str, list[di } return context, offered + def judge_estimate(axis: str) -> "float | None": + costs = [float(es.cost[axis]) for es in explanation_sets if es.cost.get(axis) is not None] + return max(costs) if costs else None + def n_asked() -> int: return sum(1 for es in explanation_sets if es.source != "not_asked") - def ask_reason(states: dict[str, list[dict[str, Any]]], growing: bool, verdicts: dict[str, Any], + def ask_reason(options: dict[str, list[Any]], growing: bool, verdicts: dict[str, Any], current: "ExplanationSet | None") -> "str | None": """Why the judge is asked now (``None`` = it is not). @@ -872,9 +961,10 @@ def ask_reason(states: dict[str, list[dict[str, Any]]], growing: bool, verdicts: plan = expansion_plan() if plan is not None and run.over_budget(plan[3]) is None: return None - with_cards = sorted(route for route, sts in states.items() - if any(st["state"] in ("open", "extend") and st["step"].name in CARDS for st in sts)) - if not with_cards or run.over_budget(None) is not None: + with_cards = sorted(route for route, rows in options.items() if any(row[2].name in CARDS for row in rows)) + # a judge call is charged like an action: asked only while its estimate fits, the + # largest call so far (the first is unknown: a run overshoots by at most one call) + if not with_cards or run.over_budget(judge_estimate("wall_sec"), judge_estimate("usd")) is not None: return None if current is None: return "the sample has settled: no expansion can follow" @@ -886,9 +976,9 @@ def ask_reason(states: dict[str, list[dict[str, Any]]], growing: bool, verdicts: return (f"the evidence decided {len(new)} prediction(s) since the last ask, and route(s) {thin} " f"with tools left have fewer than two live explanations") - def explain(records: list[dict[str, Any]], states: dict[str, list[dict[str, Any]]], + def explain(records: list[dict[str, Any]], options: dict[str, list[Any]], outcome_of: Callable[[str, str, Metric], dict[str, Any]], reason: str) -> ExplanationSet: - context, offered = explanation_request(records, states, outcome_of) + context, offered = explanation_request(records, options, outcome_of) if not offered: es = ExplanationSet(revision, "", offered=offered, source="not_asked", error="no active route has a tool with readings to predict") @@ -912,8 +1002,8 @@ def explain(records: list[dict[str, Any]], states: dict[str, list[dict[str, Any] return es def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], - states: dict[str, list[dict[str, Any]]], growing: bool, live: list[Hypothesis] - ) -> tuple[list[Scored], list[dict[str, Any]], str]: + states: dict[str, list[dict[str, Any]]], options: dict[str, list[Any]], growing: bool, + live: list[Hypothesis], readings: Readings) -> tuple[list[Scored], list[dict[str, Any]], str]: """Every feasible candidate with its value, what the budget filtered out, and the cost axis.""" nonlocal expansion_note # A batch-dependent step's reading is superseded by any later expansion, and no @@ -924,16 +1014,15 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], by_id = {r["case_id"]: r for r in records} pool: list[Scored] = [] filtered: list[dict[str, Any]] = [] - for route, sts in states.items(): - for li, st in enumerate(sts): - if st["state"] not in ("open", "extend"): - continue - layer, step = by_rule[st["rule_id"]], st["step"] + for route, rows in options.items(): + for li, st, step, R, alternative_to in rows: + layer = by_rule[st["rule_id"]] if growing and not step.reuse: filtered.append({"key": step.name, "route": route, "rule_id": layer.rule_id, "reason": "batch-dependent: a pending expansion would supersede it"}) continue - target = st["target"] if st.get("battery") else [*st["_fail_ids"], *st["_control_ids"]] + battery_step = bool(st.get("battery")) and not alternative_to + target = st["target"] if battery_step else [*st["_fail_ids"], *st["_control_ids"]] ev = run.evidence.get(step.name) todo = ev.todo(target) if ev is not None else list(target) if not todo: # the same observation exists: R = 1, not a candidate @@ -949,22 +1038,24 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], # chunks); a battery step on part of the sample. Shared PASS controls do not count: # describe-first measured for S has not started N's question started = step.reuse and ev is not None and bool( - ev.covered() & set(target if st.get("battery") else st["_fail_ids"])) + ev.covered() & set(target if battery_step else st["_fail_ids"])) T, gap_ids = 0.0, [] if started: T, gap_ids = share, [f"incomplete:{layer.rule_id}:{step.name}"] elif layer.route == "H" and any(by_id[c]["H"]["disagreements"] for c in fail_new): T, gap_ids = share, [f"contradiction:{layer.rule_id}"] - kind = "extend" if started else ("battery" if st.get("battery") else "follow_up") - D, d_detail = disagreement(route, step.name, live) if live else (0.0, {}) + kind = "extend" if started else ("battery" if battery_step else "follow_up") + D, d_detail = (disagreement(route, step.name, live, readings.decidable(route, step.name)) + if live else (0.0, {})) cost, basis = step_cost(step, len(part), run.evidence, axis) cand = Scored(kind=kind, key=step.name, route=route, rule_id=layer.rule_id, order=(ROUTE_ORDER.index(route), li), n_new_cases=len(part), D=D * share, T=T, C=C, - d_detail=d_detail, q=availability(step.analyzer, run.evidence), cost=cost, basis=basis, - gaps=gap_ids, units=touched, - payload=Proposal(layer=layer, step=step, kind=st["state"], fail_ids=st["_fail_ids"], - control_ids=st["_control_ids"], todo=part, tried=st.get("tried", []), - before=[], target_override=part)) + R=R * share, d_detail=d_detail, q=availability(step.analyzer, run.evidence), cost=cost, + basis=basis, alternative_to=alternative_to, gaps=gap_ids, units=touched, + payload=Proposal(layer=layer, step=step, + kind="alternative" if alternative_to else st["state"], + fail_ids=st["_fail_ids"], control_ids=st["_control_ids"], todo=part, + tried=st.get("tried", []), before=[], target_override=part)) why = run.over_budget(run.estimate_sec(step, len(part)), run.estimate_usd(step, len(part))) if why is not None: filtered.append({"key": step.name, "route": route, "rule_id": layer.rule_id, "reason": why}) @@ -991,6 +1082,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], pool.append(value(cand, weights, axis)) return pool, filtered, axis + explored: dict[str, float] = {} # what exploration decisions spent, per cost axis if scheduler == "scored": current: "ExplanationSet | None" = None while stop is None: @@ -1000,26 +1092,32 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], if not revisions or revisions[-1]["revision"] != revision: revisions.append(_revision_row(revision, draw, summary, records, gaps)) states, growing = route_view(records, gaps) + options, offer = runnable(states) outcome_of = outcomes_for(records) # explanations a prediction already missed on leave the live set: D is recomputed # from the evidence at every decision, without asking the judge again verdicts = check(current.hypotheses, outcome_of) if current is not None else {} if explainer is not None and n_asked() < explainer.max_asks: - reason = ask_reason(states, growing, verdicts, current) + reason = ask_reason(offer, growing, verdicts, current) if reason is not None: - current = explain(records, states, outcome_of, reason) + current = explain(records, offer, outcome_of, reason) verdicts = check(current.hypotheses, outcome_of) current.decided_at_ask = _decided(verdicts) live = [h for h in (current.hypotheses if current is not None else []) if verdicts[h.id]["state"] == "live"] - pool, filtered, axis = scored_pool(records, gaps, states, growing, live) - pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_every=explore_every, - min_gain=min_gain) + pool, filtered, axis = scored_pool(records, gaps, states, options, growing, live, outcome_of) + spent = run.charged(axis) + pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_share=explore_share, + explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain) if pick is None: over = [f for f in filtered if not f["reason"].startswith("batch-dependent")] - stop = {"reason": "below_threshold" if why != "none" else "budget" if over else "no_candidate", - "detail": (f"no candidate reaches the gain floor {min_gain}" if why != "none" else - "every remaining candidate is over budget" if over else "no feasible candidate"), - "best_gain": max((c.gain for c in pool), default=None), "filtered": filtered} + # a candidate the budget filtered out binds before the gain floor does + stop = {"reason": "budget" if over else "below_threshold" if why != "none" else "no_candidate", + "detail": ((f"{len(over)} candidate(s) over budget; the rest " + + (f"below the gain floor {min_gain}" if pool else "none")) + if over else f"no candidate reaches the gain floor {min_gain}" if why != "none" + else "no feasible candidate"), + "best_gain": max((c.gain for c in pool), default=None), "filtered": filtered, + "candidates": [c.row() for c in sorted(pool, key=lambda c: (-c.U, c.order))]} break if pick.kind != "extend" and n_actions() >= max_actions: stop = {"reason": "max_actions", "max_actions": max_actions, @@ -1029,14 +1127,24 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], skipped = [c.rule_id for c in pool if pick.route and c.route == pick.route and c.order < pick.order] extra = {"choice": why, "scoring_version": SCORING_VERSION, "axis": axis, "U": round(pick.U, 6), "gain": round(pick.gain, 6), + "rationale": _scored_rationale(pick, why, explored.get(axis, 0.0), spent, explore_share), + **({"alternative_to": pick.alternative_to} if pick.alternative_to else {}), "candidates": [c.row() for c in ranked], "filtered": filtered, **({"explanations": {"key": current.key, "revision": current.revision, "states": {hid: v["state"] for hid, v in verdicts.items()}}} if current is not None else {}), **({"soft_order_exception": f"{pick.rule_id} taken before open layer(s) {skipped} of route " f"{pick.route}: higher value"} if skipped else {})} + before = {a: run.charged(a) for a in ("wall_sec", "usd")} + + def account() -> None: # what an exploration decision spent counts against its share + if why == "explore": + for a in before: + explored[a] = explored.get(a, 0.0) + run.charged(a) - before[a] + if pick.kind == "expand": do_expand(pick.payload, gaps, extra) + account() round_no += 1 continue proposal = pick.payload @@ -1046,6 +1154,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], record = run.run_step(proposal.step, proposal.target_ids, kind="battery" if pick.kind == "battery" else "follow_up", revision=revision, rule_id=pick.rule_id, route=pick.route) + account() if record is None: run.blocked.setdefault(proposal.step.name, "nothing left to run") elif record["status"] == SKIPPED: @@ -1144,7 +1253,8 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], report = { "policy": POLICY_VERSION, "scheduler": scheduler, - **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_every": explore_every, + **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_share": explore_share, + "explored": {a: round(v, 6) for a, v in explored.items()}, "min_gain": min_gain, "min_cover": min_cover} if scheduler == "scored" else {}), "rules_version": RULES_VERSION, "model": model_identity, @@ -1185,6 +1295,17 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], return report +def _scored_rationale(pick: Scored, why: str, explored: float, spent: float, share: float) -> str: + """One line saying why the scored scheduler took *pick*.""" + terms = f"U {pick.U:.4g} = q {pick.q:.2f} x [D {pick.D:.3f} + T {pick.T:.3f} + C {pick.C:.3f} - R {pick.R:.3f}]" + terms += f" / cost {pick.cost:.4g}" if pick.cost is not None else " / cost unknown" + if why == "explore": + return (f"exploration ({explored:.4g} of {spent:.4g} spent so far went to exploration; share {share}): " + + terms) + alt = f"; an alternative to {pick.alternative_to}" if pick.alternative_to else "" + return f"highest value: {terms}{alt}" + + def report_name(scheduler: str, explained: bool = False) -> str: """``triage_report`` (rules), ``triage_report.scored``, or ``triage_report.scored_d`` (with D): the arms of a comparison can share one probing directory and its ledger.""" diff --git a/evalrx/eval_agent/probing/explanations.py b/evalrx/eval_agent/probing/explanations.py index c1377b69..547c6316 100644 --- a/evalrx/eval_agent/probing/explanations.py +++ b/evalrx/eval_agent/probing/explanations.py @@ -24,12 +24,26 @@ the live set; one without any explicit prediction is untestable and is not in it either. -``D(a)`` for a candidate on route r is the share of pairs of r's live -explanations whose explicit predictions for that step conflict on at least -one reading; a pair with an ``unknown`` counts in the denominator only. Zero -or one live explanation gives ``D = 0``. Confidence the judge states is not -asked for and never weights anything. D is a disagreement heuristic, not a -posterior or an information gain. +``D(a)`` for a candidate on route r sums, over the pairs of r's live +explanations whose explicit predictions for that step conflict, how decidable +the conflict is on the route's cases, and divides by the number of pairs; a +pair with an ``unknown`` counts in the denominator only. Zero or one live +explanation gives ``D = 0``. Confidence the judge states is not asked for and +never weights anything. D is a disagreement heuristic, not a posterior or an +information gain. + +**Decidability** (``decidability``): a conflict is only worth something if the +route's sample can settle it. Take one prediction as true at its reference +difference: 0 for ``same``, one standard deviation of the reading beyond the +band for ``up``/``down``. The cases needed are the fewest per side at which the +verdict's interval would then contradict the other prediction. With *n* route +FAIL cases (and as many controls), each side scores ``min(1, n / needed)``, +and the conflict scores the mean of the two sides; a pair conflicting on +several readings takes its most decidable one. The spread comes from every +case the step measured in this run. Until then a share's spread is taken at +its largest (0.5) and a mean's band as negligible next to its spread: the +least favourable values, so that a "same" prediction about an unmeasured mean +reading counts as unsettleable. The judge sees the route summaries and readings of EXPLORE only, never a case's content, media or CONFIRM. Each call's prompt, reply and cost are @@ -54,7 +68,7 @@ from evalrx.eval_agent.probing.metering import usage_counters, usage_delta from evalrx.eval_agent.probing.triage import difference_interval -EXPLAIN_VERSION = "mvp3-explain-1" +EXPLAIN_VERSION = "mvp3-explain-2" DIRECTIONS = ("up", "down", "same", "unknown") _ALIASES = {"↑": "up", "↓": "down", "≈": "same", "=": "same", "~": "same", "?": "unknown", "higher": "up", "lower": "down", "increase": "up", "decrease": "down", "none": "unknown"} @@ -245,6 +259,74 @@ def take(ids: list[str]) -> list[float]: return out +# -- decidability ------------------------------------------------------------------------------- + +_MAX_CASES = 1 << 20 + + +def half_width(n: int) -> float: + """The verdict interval's half-width in standard deviations of the reading, with *n* cases on + each side of equal spread (Welch's degrees of freedom are then ``2n - 2``).""" + return _t975(2 * n - 2) * math.sqrt(2.0 / n) + + +def spread(groups: "list[list[float]]", kind: str) -> "float | None": + """The reading's standard deviation within groups (FAIL, PASS), pooled; ``None`` without data. + + A share's spread is that of its smoothed rate ``(k + 2) / (m + 4)``, so a share + measured at 0 still has one (the interval around 0/16 is not empty).""" + if kind == "rate": + rows = [(len(g), (sum(1 for x in g if x >= 0.5) + 2) / (len(g) + 4)) for g in groups if g] + if not rows: + return None + return math.sqrt(sum(m * p * (1 - p) for m, p in rows) / sum(m for m, _ in rows)) + rows = [g for g in groups if len(g) >= 2] + if not rows: + return None + ss = sum(sum((x - _mean(g)) ** 2 for x in g) for g in rows) + return math.sqrt(ss / sum(len(g) - 1 for g in rows)) + + +def cases_needed(true: str, other: str, z: float) -> float: + """Fewest cases a side at which, with *true* holding at its reference difference, the + interval contradicts *other*; ``inf`` when no sample would. *z* is the band in standard + deviations of the reading. + + In units of the spread, with half-width ``h``: ``same`` misses under a true ``up`` + (one past the band) once ``h < 1``; the opposite direction once ``h <= 2z + 1``; and + ``up``/``down`` misses under a true ``same`` only once the whole interval fits in + the band, ``h <= z``.""" + limit = z if true == "same" else 1.0 if other == "same" else 2.0 * z + 1.0 + if limit <= 0.0: + return math.inf + if math.isinf(limit) or half_width(MIN_N) <= limit: + return float(MIN_N) + lo, hi = MIN_N, MIN_N + while half_width(hi) > limit: + lo, hi = hi, hi * 2 + if hi > _MAX_CASES: + return math.inf + while hi - lo > 1: # half_width falls with n + mid = (lo + hi) // 2 + lo, hi = (mid, hi) if half_width(mid) > limit else (lo, mid) + return float(hi) + + +def decidability(a: str, b: str, n: int, metric: Metric, sd: "float | None") -> dict[str, Any]: + """How far *n* route FAIL cases (and as many controls) go towards settling predictions *a* + against *b* on *metric*, from 0 to 1; with the cases each side would need.""" + if sd is None: + # least favourable: a share at its largest spread, a mean's band negligible next to it + z, basis = (metric.band / 0.5 if metric.kind == "rate" else 0.0), "unmeasured" + else: + z, basis = (math.inf if sd == 0.0 else metric.band / sd), "measured" + needed = (cases_needed(a, b, z), cases_needed(b, a, z)) + score = [0.0 if n < MIN_N or math.isinf(k) else min(1.0, n / k) for k in needed] + return {"decidable": round(sum(score) / 2, 4), "n": n, "needed": [None if math.isinf(k) else int(k) + for k in needed], + "spread": None if sd is None else round(sd, 4), "basis": basis} + + # -- explanations ------------------------------------------------------------------------------- @@ -307,19 +389,33 @@ def check(hypotheses: list[Hypothesis], outcome_of: Outcomes) -> dict[str, dict[ return out -def disagreement(route: str, step: str, live: list[Hypothesis]) -> tuple[float, dict[str, Any]]: - """``D`` of running *step* on *route*, and which pairs of live explanations it separates.""" +Decidable = Callable[[str, str, str], dict[str, Any]] # (reading, direction a, direction b) -> decidability + + +def disagreement(route: str, step: str, live: list[Hypothesis], + decidable: "Decidable | None" = None) -> tuple[float, dict[str, Any]]: + """``D`` of running *step* on *route*, and which pairs of live explanations it separates. + + Each conflicting pair counts by how decidable its conflict is on the route's cases + (:func:`decidability`; its most decidable reading); without *decidable* every conflict + counts in full. ``conflict_share`` is the share of conflicting pairs, undiscounted.""" hyps = [h for h in live if h.route == route] if len(hyps) < 2: - return 0.0, {"n_live": len(hyps), "n_pairs": 0, "conflicting": []} + return 0.0, {"n_live": len(hyps), "n_pairs": 0, "conflicting": [], "conflict_share": 0.0} pairs = list(combinations(hyps, 2)) conflicting = [] for a, b in pairs: pa, pb = a.predictions.get(step, {}), b.predictions.get(step, {}) on = sorted(f for f in set(pa) & set(pb) if pa[f] != pb[f]) if on: - conflicting.append({"pair": [a.id, b.id], "readings": on}) - return len(conflicting) / len(pairs), {"n_live": len(hyps), "n_pairs": len(pairs), "conflicting": conflicting} + row: dict[str, Any] = {"pair": [a.id, b.id], "readings": on} + if decidable is not None: + row["by_reading"] = {f: decidable(f, pa[f], pb[f]) for f in on} + row["decidable"] = max(r["decidable"] for r in row["by_reading"].values()) + conflicting.append(row) + D = sum(c.get("decidable", 1.0) for c in conflicting) / len(pairs) + return D, {"n_live": len(hyps), "n_pairs": len(pairs), "conflicting": conflicting, + "conflict_share": len(conflicting) / len(pairs)} # -- the judge call --------------------------------------------------------------------------------- @@ -339,6 +435,9 @@ def disagreement(route: str, step: str, live: list[Hypothesis]) -> tuple[float, explanation into variants only to disagree, and propose fewer (or none) when you have no real alternative. +A tool with "alternative_to" asks a question that another tool (named there) +has already answered on the route: it runs only if it tells explanations apart. + For each explanation and each tool listed under the route's "to_run", predict for each of its readings the direction of (FAIL mean - control mean): "up" the difference is above +band diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index a82334fb..5bce3cf3 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -51,6 +51,16 @@ ROUTE_ORDER = ("H", "N", "U", "S", "X") DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} +#: Kinds of evidence (``PlanStep.evidence``) that more than one tool of a layer gives: +#: once one of them has answered the layer, another of the same kind is redundant. +MEDIA_ATTENTION_CUT = "text-to-media attention cut, gold margin" +MEDIA_NOISE = "media embeddings noised and restored, gold margin" +ATTENTION_RESCALING = "attention to the media rescaled, gold margin" +TOKEN_PROBABILITIES = "output-token probabilities" +RESAMPLING = "re-sampled answers" +RELEVANCE_MAP = "relevance map of the gold margin over the media" +LAYER_READOUT = "answer position read out layer by layer" + #: Room for a description before the answer, asked per call (the task's own cap #: is sized for the answer alone: 16 tokens on POPE). DESCRIBE_OUTPUT_TOKENS = 256 @@ -92,21 +102,21 @@ class Layer: key="termination_continue", calls_per_case={"generate": 1}),)), Layer("N1", "N", "does the media path carry a measurable effect on the gold answer", ( PlanStep("causal_trace", {"target": "gold"}, "N1", "corrupt the media, restore one site at a time", - calls_per_case={"forward": 20}),), + calls_per_case={"forward": 20}, evidence=MEDIA_NOISE),), served_by=("attention_knockout",)), Layer("N2", "N", "does reading the media with sharper or flatter attention change the gold margin", ( PlanStep("attention_temperature", {"target": "gold"}, "N2", "rescale the media attention temperature", - fidelity_check="edit", calls_per_case={"forward": 4}), + fidelity_check="edit", calls_per_case={"forward": 4}, evidence=ATTENTION_RESCALING), PlanStep("attention_sensitivity", {"target": "gold"}, "N2", "scale attention to the media down and up", - fidelity_check="edit", calls_per_case={"forward": 4}))), + fidelity_check="edit", calls_per_case={"forward": 4}, evidence=ATTENTION_RESCALING))), Layer("N3", "N", "asked to describe the media first, does the answer start to follow it", ( _describe("N3", "describe the media, then answer"),)), Layer("U1", "U", "is the answer that moves close to a tie", ( PlanStep("logprob_entropy", {}, "U1", "answer-token probabilities of the output", - calls_per_case={"logprobs": 1}, per_case=True), + calls_per_case={"logprobs": 1}, per_case=True, evidence=TOKEN_PROBABILITIES), PlanStep("self_consistency", {"n": 10}, "U1", "twice the samples: how often the answer moves", key="self_consistency_n10", calls_per_case={"generate": 10}, per_case=True, - keep_artifacts=("samples",)))), + keep_artifacts=("samples",), evidence=RESAMPLING))), Layer("U2", "U", "with the options rotated, does the answer follow content or position", ( PlanStep("format_sensitivity", {}, "U2", "rotate the options", calls_per_case={"generate": 3}, task_kinds=("multiple_choice_letter",)),)), @@ -115,15 +125,16 @@ class Layer: Layer("S1", "S", "which image regions the gold margin depends on (no reference regions: " "concentration only, not 'mislocalised')", ( PlanStep("gradcam", {"target": "gold"}, "S1", "gradient x activation map of the gold margin", - calls_per_case={"backward": 1}), + calls_per_case={"backward": 1}, evidence=RELEVANCE_MAP), PlanStep("generic_attention", {"target": "gold"}, "S1", "attention relevance of the gold margin", - fidelity_check="edit", calls_per_case={"backward": 1}))), + fidelity_check="edit", calls_per_case={"backward": 1}, evidence=RELEVANCE_MAP))), Layer("S2", "S", "is the case's own question word readable off the media tokens", (), served_by=("embed_lens",)), Layer("S3", "S", "was the gold answer readable before the output", ( PlanStep("tuned_lens", {}, "S3", "fitted per-layer readout of the answer position (translators " - "fit once on a fixed set of EXPLORE cases)", calls_per_case={"forward": 1}), + "fit once on a fixed set of EXPLORE cases)", calls_per_case={"forward": 1}, + evidence=LAYER_READOUT), PlanStep("layer_contrast", {}, "S3", "early-vs-late layer contrast at the answer position", - calls_per_case={"forward": 1})), + calls_per_case={"forward": 1}, evidence=LAYER_READOUT)), served_by=("patchscope",)), Layer("X1", "X", "with the media removed instead of swapped, does the answer change " "(a different intervention: it does not test N)", ( diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/probing/scoring.py index 6d1605c8..f9467c2f 100644 --- a/evalrx/eval_agent/probing/scoring.py +++ b/evalrx/eval_agent/probing/scoring.py @@ -7,8 +7,9 @@ axis' metering floor. The definitions are the design's first executable ones, written down so a run can show why each action won: -* **D** (prediction disagreement): with an explainer, the share of pairs of the - route's live competing explanations whose predictions for the step conflict +* **D** (prediction disagreement): with an explainer, the pairs of the route's + live competing explanations whose predictions for the step conflict, each + counted by how decidable the conflict is on the route's cases, over all pairs (:mod:`.explanations`); the explanations come once the sample has settled, and an explanation a prediction already missed on leaves the live set at the next decision. Without one, or with fewer than two live explanations, @@ -23,17 +24,22 @@ A ``reuse`` step runs one chunk per decision (a fixed number of cases, FAIL and PASS alternating), so a decision spends at most one chunk before the scheduler -sees the step's measured cost. T and D are about the step on the whole route, -so a chunk earns them in proportion to the share of the route's remaining FAIL -cases it covers, and the chunks of a step add up to what it earns unchunked; C -is counted per chunk already. +sees the step's measured cost. T, D and R are about the step on the whole +route, so a chunk earns them in proportion to the share of the route's +remaining FAIL cases it covers, and the chunks of a step add up to what it +earns unchunked; C is counted per chunk already. * **C** (coverage): units are ``layer × gold stratum`` for every route with FAIL cases there. A unit's gap is 1 untested, 0.5 measured on fewer than ``min(min_cover, route FAIL cases in the stratum)`` cases, else 0. ``C(a)`` is the gap the action is expected to remove, over the number of units. -* **R** (redundancy): an observation that already exists is filtered out (R = 1); - another tool for a layer that is already answered gets 0.5 (same purpose, - same kind of evidence); otherwise 0. +* **R** (redundancy): an observation that already exists is filtered out (R = 1). + A layer that is already answered offers its other candidates as + *alternatives*: 0.5 when the alternative gives the kind of evidence the tool + that answered the layer gave (the same question asked the same way, e.g. a + second attention rescaling), 0 when it gives another kind (a different + intervention). An alternative closes no gap and covers no unit, so it is + only worth its D: a same-kind alternative runs when it tells live + explanations apart by more than its redundancy. * **q** (execution availability): ``(successes + 1) / (attempts + 2)`` over the distinct observations of the analyzer in this run's evidence (a read-back counts once, so a resumed run decides the same way); ``ok`` and not refused @@ -46,15 +52,21 @@ models or backends, and a reusable step's first chunk shows its real cost. Candidates are each route's open or stale layers (the layer's next candidate in -its fallback order, as in the rules), the expansion, and the batch-dependent -battery steps not yet run on the current sample. No batch-dependent candidate -(battery step or follow-up) is taken while an expansion can still follow: any -expansion supersedes its reading, and no route reads it (the rules' deferral, -for the same reason); its layer waits instead of falling back. Unlike the rules, the -scored scheduler may take a later layer first, and says so when it does. Every -``explore_every``-th decision picks, with a seed, among the feasible candidates -other than the top one. A gain below ``min_gain`` is not worth an action: when -no candidate reaches it, the run stops. +its fallback order, as in the rules), the alternatives of its answered layers, +the expansion, and the batch-dependent battery steps not yet run on the +current sample. No batch-dependent candidate (battery step or follow-up) is +taken while an expansion can still follow: any expansion supersedes its +reading, and no route reads it (the rules' deferral, for the same reason); its +layer waits instead of falling back. Unlike the rules, the scored scheduler may +take a later layer first, and says so when it does. + +**Exploration** has a share of the spending, not of the decisions (a decision +may be one chunk): a feasible candidate other than the top one fits when what +exploration has spent, plus its estimated cost, stays within ``explore_share`` +of everything spent, and whenever one fits a seeded draw among them runs +instead of the top one. A gain below ``min_gain`` is not worth an action: when +no candidate reaches it, every feasible candidate is an exploration candidate, +and the run stops once none fits in the share (the minimum exploration is met). """ from __future__ import annotations @@ -66,7 +78,7 @@ from evalrx.eval_agent.probing.actions import OK, UNSUPPORTED, PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -SCORING_VERSION = "mvp3-score-3" +SCORING_VERSION = "mvp3-score-4" @dataclass(frozen=True) @@ -96,6 +108,7 @@ class Scored: gain: float = 0.0 U: float = 0.0 basis: str = "" # what the cost rests on: "own" / "typical" / "none" + alternative_to: str = "" # the step that already answered the layer (an alternative) gaps: list[str] = field(default_factory=list) units: list[str] = field(default_factory=list) d_detail: dict[str, Any] = field(default_factory=dict) # which live explanations D separates @@ -233,16 +246,21 @@ def value(s: Scored, weights: Weights, axis: str) -> Scored: return s -def choose(candidates: list[Scored], *, decision_no: int, seed: int, explore_every: int, - min_gain: float) -> "tuple[Scored | None, str]": - """The candidate to run, and why: ``best`` / ``explore`` / ``below_threshold`` / ``none``.""" +def choose(candidates: list[Scored], *, decision_no: int, seed: int, explore_share: float, explored: float, + spent: float, min_gain: float) -> "tuple[Scored | None, str]": + """The candidate to run, and why: ``best`` / ``explore`` / ``below_threshold`` / ``none``. + + *explored* and *spent* are what exploration and the whole run have spent so far, on the + candidates' cost axis: a seeded draw among the others that keep exploration within + *explore_share* of the spending runs instead of the best.""" if not candidates: return None, "none" ranked = sorted(candidates, key=lambda s: (-s.U, s.order)) - if explore_every and (decision_no + 1) % explore_every == 0 and len(ranked) > 1: - rng = random.Random(f"{seed}:{decision_no}") - return rng.choice(ranked[1:]), "explore" best = ranked[0] + others = ranked[1:] if best.gain >= min_gain else ranked + fits = [s for s in others if explored + (s.cost or 0.0) <= explore_share * (spent + (s.cost or 0.0))] + if explore_share > 0 and fits: + return random.Random(f"{seed}:{decision_no}").choice(fits), "explore" if best.gain < min_gain: return None, "below_threshold" return best, "best" diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index 2e5b30e1..df886647 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -190,3 +190,19 @@ def build(args): '--triage-scheduler', 'scored', '--triage-explanations', 'judge']) with pytest.raises(SystemExit, match='model under test'): runner._triage_explainer(same, spec) + + +def test_triage_weights_and_exploration_share_parse_and_are_checked(): + from evalrx.benchmark.run import main as run_main + from evalrx.benchmark.run import triage_weights + + assert triage_weights('d=1,t=1,c=1,r=1') == {'d': 1.0, 't': 1.0, 'c': 1.0, 'r': 1.0} + assert triage_weights('c=0, r=0.5') == {'d': 1.0, 't': 1.0, 'c': 0.0, 'r': 0.5} # left out = 1 + for bad in ('x=1', 'd', 'd=-1'): + with pytest.raises(ValueError, match='--triage-weights'): + triage_weights(bad) + args = build_parser().parse_args([]) + assert (args.triage_weights, args.triage_explore_share) == ('d=1,t=1,c=1,r=1', 0.1) + with pytest.raises(ValueError, match='--triage-explore-share'): + run_main(['--modality', 'vlm', '--model', 'qwen3.5-0.8b', '--m1-policy', 'triage_active', + '--triage-explore-share', '1.0']) diff --git a/tests/test_eval_agent/test_probing_alternatives.py b/tests/test_eval_agent/test_probing_alternatives.py new file mode 100644 index 00000000..2901e2ec --- /dev/null +++ b/tests/test_eval_agent/test_probing_alternatives.py @@ -0,0 +1,128 @@ +"""The scored scheduler's redundancy term and its exploration share. + +* an answered layer offers its other candidates as alternatives: R = 0.5 when + one gives the kind of evidence the tool that answered the layer gave, 0 when + it gives another kind; an alternative closes no gap and covers no unit, so it + only runs on a D above its R, and the judge is offered it; +* exploration spends at most its share of what the run spent, and a run whose + candidates are all below the gain floor explores until none fits the share. +""" + +from __future__ import annotations + +import json + +import pytest + +import evalrx.eval_agent.probing.controller as controller +from evalrx.eval_agent.probing import LAYERS, run_triage +from evalrx.eval_agent.probing.actions import PlanStep +from evalrx.eval_agent.probing.explanations import CARDS, Explainer, Metric +from evalrx.eval_agent.probing.rules import Layer +from evalrx.eval_agent.probing.scoring import Weights +from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table + + +def _wrapper(key, text, evidence): + return PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", key: text + " {prompt}"}}, "Z1", + f"re-ask inside the wrapper {text!r}", key=key, evidence=evidence) + + +FIRST = _wrapper("wrap_a", "Q:", "wrapper") +SAME_KIND = _wrapper("wrap_b", "Ask:", "wrapper") +OTHER_KIND = _wrapper("wrap_c", "Please answer:", "another kind") + + +@pytest.fixture +def wrappers(monkeypatch): + """An S layer with three candidates: the first answers it, the second gives the same kind + of evidence, the third another kind. The table model ignores wrappers.""" + for step in (FIRST, SAME_KIND, OTHER_KIND): + monkeypatch.setitem(CARDS, step.name, (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) + at = next(i for i, x in enumerate(LAYERS) if x.rule_id == "Sb") + return (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (FIRST, SAME_KIND, OTHER_KIND)), *LAYERS[at:]) + + +class _Judge: + """Two explanations per route that agree on every step but the alternatives: on an + alternative's first reading one predicts up, the other that it stays the same.""" + + def __init__(self): + self.prompts = [] + + def generate(self, prompt): + self.prompts.append(prompt) + ctx = json.loads(prompt[prompt.index("Evidence (JSON):") + len("Evidence (JSON):"):]) + routes = {} + for route, r in ctx["routes"].items(): + routes[route] = [{"id": f"h{i}", "claim": f"claim {i}", + "predictions": {c["step"]: {c["readings"][0]["field"]: d if c.get("alternative_to") + else "same"} for c in r["to_run"]}} + for i, d in enumerate(("up", "same"), 1)] + return json.dumps({"routes": routes}) + + +def _run(out, layers, judge=None, **over): + explainer = Explainer(judge, identity={"provider": "stub", "model": "stub"}) if judge is not None else None + return run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored", layers=layers, + explainer=explainer, **over)) + + +def _ran(report): + return {e["key"] for e in report["executions"] if e["status"] == "ok"} + + +def test_an_answered_layer_offers_alternatives_that_earn_nothing_without_D(tmp_path, wrappers): + report = _run(tmp_path / "a", wrappers) + rows = [c for d in [*report["decisions"], report["stop"]] for c in d.get("candidates") or []] + alts = {c["key"]: c for c in rows if c.get("alternative_to")} + assert set(alts) == {"wrap_b", "wrap_c"} and {c["alternative_to"] for c in alts.values()} == {"wrap_a"} + assert alts["wrap_b"]["R"] > 0 and alts["wrap_c"]["R"] == 0.0 # same kind of evidence, another kind + assert all(c["T"] == c["C"] == c["D"] == c["gain"] == 0.0 for c in alts.values()) + assert "wrap_a" in _ran(report) and not {"wrap_b", "wrap_c"} & _ran(report) + + +def test_an_alternative_runs_on_a_D_above_its_redundancy_and_the_judge_is_offered_it(tmp_path, wrappers): + judge = _Judge() + report = _run(tmp_path / "d", wrappers, judge) + # asked while Z1 was open: its other candidates are offered as alternatives to its current one + asked = [json.loads(p[p.index("Evidence (JSON):") + 16:])["routes"]["S"]["to_run"] for p in judge.prompts] + offered = {c["step"]: c.get("alternative_to") for c in asked[0]} + assert offered["wrap_a"] is None and offered["wrap_b"] == offered["wrap_c"] == "wrap_a" + # an unmeasured up-vs-same conflict is at most half decidable: enough against R = 0, not against 0.5 + assert "wrap_c" in _ran(report) and "wrap_b" not in _ran(report) + (taken,) = [d for d in report["decisions"] if d.get("key") == "wrap_c" and d["kind"] == "follow_up"] + assert taken["alternative_to"] == "wrap_a" and "alternative to wrap_a" in taken["rationale"] + assert ("S", "Z1", "wrap_c") in {(f["route"], f["rule_id"], f["key"]) for f in report["follow_ups"]} + # without the redundancy term the same-kind alternative ties and runs first; its result + # contradicts the "up" explanation, and then wrap_c has nothing left to tell apart + no_r = _run(tmp_path / "r0", wrappers, _Judge(), weights=Weights(r=0.0)) + assert "wrap_b" in _ran(no_r) and "wrap_c" not in _ran(no_r) + + +@pytest.fixture +def metered(monkeypatch): + """One second per case: the exploration share is checked on deterministic costs.""" + real = controller.execute + + def execute(action, *args, **kwargs): + obs = real(action, *args, **kwargs) + if obs.cost.get("calls"): + obs.cost["wall_sec"] = float(len(obs.planned_ids)) + return obs + + monkeypatch.setattr(controller, "execute", execute) + + +def test_exploration_spends_at_most_its_share_and_continues_below_the_gain_floor(tmp_path, wrappers, metered): + report = _run(tmp_path / "e", wrappers, explore_share=0.3, chunk=2) + explored = [d for d in report["decisions"] if d.get("choice") == "explore"] + assert explored and all("exploration" in d["rationale"] for d in explored) + assert report["explore_share"] == 0.3 + assert 0 < report["explored"]["wall_sec"] <= 0.3 * report["cost"]["charged"]["wall_sec"] + # below the gain floor only exploration runs, until no candidate fits the share + assert any(d.get("gain") == 0.0 for d in explored) + assert report["stop"]["reason"] in ("below_threshold", "no_candidate") + none = _run(tmp_path / "n", wrappers, explore_share=0.0, chunk=2) + assert not [d for d in none["decisions"] if d.get("choice") == "explore"] and not none["explored"] diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_probing_mvp2.py index 99d1f8d6..7181b928 100644 --- a/tests/test_eval_agent/test_probing_mvp2.py +++ b/tests/test_eval_agent/test_probing_mvp2.py @@ -79,7 +79,8 @@ def _yes_no(case, text): def _kw(out, **over): kw = dict(out_dir=out, model_identity={"spec": "table"}, n_fail=4, seed=0, host_assumed_finish=True, n_needs_counterfactual=True, task_kind="yes_no", answer_fn=_yes_no, min_cohort=100, - analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, progress=None) + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, progress=None, + explore_share=0.0) # the scored scheduler explores only in the tests about exploration return {**kw, **over} diff --git a/tests/test_eval_agent/test_probing_mvp3.py b/tests/test_eval_agent/test_probing_mvp3.py index 82ae5094..7a831c9c 100644 --- a/tests/test_eval_agent/test_probing_mvp3.py +++ b/tests/test_eval_agent/test_probing_mvp3.py @@ -73,19 +73,26 @@ def test_coverage_gain_is_the_gap_removed_over_all_units(): assert coverage_gain("N2", {"f"}, units) == (0.0, []) -def test_choose_takes_the_best_value_breaks_ties_by_soft_order_explores_and_stops_below_threshold(): - def s(key, U, gain, order): - return Scored(kind="follow_up", key=key, U=U, gain=gain, order=order) +def test_choose_takes_the_best_value_breaks_ties_by_soft_order_explores_within_its_share_and_stops(): + def s(key, U, gain, order, cost=10.0): + return Scored(kind="follow_up", key=key, U=U, gain=gain, order=order, cost=cost) pool = [s("late", 0.5, 0.2, (1, 2)), s("early", 0.5, 0.2, (1, 0)), s("cheap", 0.1, 0.3, (0, 0))] - best, why = choose(pool, decision_no=0, seed=0, explore_every=10, min_gain=0.01) + kw = dict(seed=0, explore_share=0.1, min_gain=0.01) + # 10 s of exploration would be 10/(50+10) of the spending: over the share, so the best runs + best, why = choose(pool, decision_no=0, explored=0.0, spent=50.0, **kw) assert (best.key, why) == ("early", "best") - picked, why = choose(pool, decision_no=9, seed=0, explore_every=10, min_gain=0.01) + # at 90 s spent it fits (10 <= 0.1 * 100): a seeded draw among the others runs instead + picked, why = choose(pool, decision_no=3, explored=0.0, spent=90.0, **kw) assert why == "explore" and picked.key != "early" - assert choose(pool, decision_no=9, seed=0, explore_every=10, min_gain=0.01)[0].key == picked.key # seeded - assert choose([s("x", 0.0, 0.0, (0, 0))], decision_no=0, seed=0, explore_every=10, min_gain=0.01) == ( - None, "below_threshold") - assert choose([], decision_no=0, seed=0, explore_every=10, min_gain=0.01) == (None, "none") + assert choose(pool, decision_no=3, explored=0.0, spent=90.0, **kw)[0].key == picked.key # seeded + assert choose(pool, decision_no=3, explored=10.0, spent=100.0, **kw)[1] == "best" # share used up + assert choose(pool, decision_no=3, explored=0.0, spent=1e6, **{**kw, "explore_share": 0.0})[1] == "best" + # below the gain floor every candidate is an exploration candidate; once none fits, the run stops + low = [s("x", 0.0, 0.0, (0, 0)), s("y", 0.0, 0.0, (0, 1), cost=100.0)] + assert choose(low, decision_no=0, explored=0.0, spent=90.0, **kw) == (low[0], "explore") + assert choose(low, decision_no=0, explored=0.0, spent=50.0, **kw) == (None, "below_threshold") + assert choose([], decision_no=0, explored=0.0, spent=0.0, **kw) == (None, "none") def test_scored_run_is_traceable_deterministic_on_resume_and_comparable_with_the_rules(tmp_path): diff --git a/tests/test_eval_agent/test_probing_mvp3b.py b/tests/test_eval_agent/test_probing_mvp3b.py index b968197d..bcece3d3 100644 --- a/tests/test_eval_agent/test_probing_mvp3b.py +++ b/tests/test_eval_agent/test_probing_mvp3b.py @@ -73,6 +73,42 @@ def test_disagreement_is_the_share_of_live_pairs_whose_predictions_conflict(): assert disagreement("S", "patchscope", [a, b, c])[0] == 0.0 assert disagreement("S", "gradcam", [a])[0] == 0.0 assert disagreement("N", "gradcam", [a, b])[0] == 0.0 # another route's explanations + # a conflict counts by how decidable it is + D, detail = disagreement("S", "gradcam", [a, b, c], lambda f, x, y: {"decidable": 0.25}) + assert D == pytest.approx(0.25 / 3) and detail["conflict_share"] == pytest.approx(1 / 3) + + +def test_decidability_asks_whether_the_routes_cases_can_settle_a_conflict(): + from evalrx.eval_agent.probing.explanations import ( + cases_needed, + decidability, + half_width, + spread, + ) + + assert half_width(9) < 1.0 < half_width(8) # under one spread from 9 cases a side + # a true "up" one spread past the band contradicts "same" from 9 cases a side, whatever the band + assert cases_needed("up", "same", 0.0) == cases_needed("up", "same", 2.0) == 9 + # a true "same" contradicts "up" only once the interval fits in the band: never with no band + assert cases_needed("same", "up", 0.0) == float("inf") + assert cases_needed("same", "up", 0.5) > cases_needed("same", "up", 1.0) == 9 # a band of one spread + assert cases_needed("up", "down", 0.5) < cases_needed("up", "same", 0.5) + mean = Metric("x", "a mean", 0.05) + # unmeasured mean: only the "up" side can settle; three cases go a third of the way there + tiny = decidability("up", "same", 3, mean, None) + assert tiny["basis"] == "unmeasured" and tiny["needed"] == [9, None] + assert tiny["decidable"] == pytest.approx(3 / 9 / 2, abs=1e-3) + assert decidability("up", "same", 16, mean, None)["decidable"] == 0.5 + assert decidability("up", "same", 16, mean, 0.1)["decidable"] == pytest.approx((1 + 16 / 32) / 2) + assert decidability("up", "same", 1, mean, 0.1)["decidable"] == 0.0 + assert decidability("up", "down", 16, mean, 0.0)["decidable"] == 1.0 # a constant reading + # a share's spread is smoothed (0/16 still has one) and taken at its largest before it is measured + assert spread([[0.0] * 16, [0.0] * 16], "rate") == pytest.approx(0.3) + assert spread([[1.0, 2.0, 3.0], [5.0]], "mean") == pytest.approx(1.0) + assert spread([[1.0]], "mean") is None + share = Metric("y", "a share", 0.1, "rate") + assert decidability("up", "same", 16, share, None)["needed"][1] > decidability( + "up", "same", 16, share, 0.3)["needed"][1] def test_check_contradicts_on_a_miss_and_calls_an_explanation_without_predictions_untestable(): @@ -176,7 +212,9 @@ def test_scored_run_asks_once_the_sample_settles_and_resumes_without_asking(tmp_ if d.get("candidates") and d["revision"] < last: assert all(c["D"] == 0.0 for c in d["candidates"]) and "explanations" not in d scored = [c for d in report["decisions"] for c in d.get("candidates") or [] if c["kind"] != "expand"] - assert any(c["D"] == 1.0 and c["d_detail"]["conflicting"] for c in scored) + assert any(c["D"] > 0 and c["d_detail"]["conflict_share"] == 1.0 for c in scored) + # each conflict counts by how decidable it is on the route's few cases: never in full here + assert all(0 < x["decidable"] < 1 for c in scored for x in c["d_detail"].get("conflicting", [])) # the judge never sees a case: no case id, no question text, no CONFIRM for p in judge.prompts: assert not any(str(c.id) in p for c in cases) and "Is there a" not in p and "confirm" not in p.lower() @@ -273,3 +311,39 @@ def metered(action, *args, **kwargs): # a second per case, so the budget binds assert [(e["key"], e["status"], e.get("n_cases")) for e in again["executions"]] == [ (e["key"], e["status"], e.get("n_cases")) for e in first["executions"]] assert again["cost"]["charged"] == first["cost"]["charged"] + + +class _SlowExplainer(Explainer): + """Every judge call is charged 100 seconds.""" + + def propose(self, root, revision, context, offered): + es = super().propose(root, revision, context, offered) + es.cost = {**es.cost, "wall_sec": 100.0} + return es + + +def test_a_judge_call_is_asked_only_while_its_estimate_fits_the_budget(tmp_path, monkeypatch): + from evalrx.eval_agent.probing import LAYERS + from evalrx.eval_agent.probing.actions import PlanStep + from evalrx.eval_agent.probing.rules import Layer + + # the re-ask scenario: two asks when nothing binds; the evidence costs milliseconds + monkeypatch.setitem(CARDS, "wrapped", (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) + step = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "w": "Q: {prompt}"}}, "Z1", + "re-ask inside a wrapper", key="wrapped") + at = next(i for i, x in enumerate(LAYERS) if x.rule_id == "Sb") + layers = (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (step,)), *LAYERS[at:]) + + def run(out, budget): + explainer = _SlowExplainer(_Judge(), identity={"provider": "stub", "model": "slow"}) + return run_triage(_Table(_pope_like()[1]), _pope_like()[0], + **_kw(tmp_path / out, max_fail=8, min_route_fail=1, scheduler="scored", layers=layers, + explainer=explainer, budget_sec=budget)) + + assert len(run("full", 0.0)["explanations"]["sets"]) == 2 + for budget, asks in ((50.0, 1), (150.0, 1), (250.0, 2)): + r = run(f"b{budget}", budget) + assert len(r["explanations"]["sets"]) == asks, budget + # the first call's cost is unknown, so it may overshoot by one call; a later one is not + # made unless the largest call so far fits + assert r["cost"]["charged"]["wall_sec"] - budget <= 100.0 if asks == 1 else r["cost"]["charged"]["wall_sec"] <= budget From 7ca47ce75707b885814cad43cf76d3c3937cfc1b Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Mon, 19 Oct 2026 00:15:42 -0700 Subject: [PATCH 09/26] triage exploration: own targets, a share of the evidence spending Exploration's share (--triage-explore-share) is of the evidence spending, not the judge's calls, and it draws only from targets the value never takes: the next candidate of a route too small to be active, and on each active route the carded representative of every other route's layer it does not own. Targets are priced at a budget check's conservative estimate; completing one on its route is paid from the share until its readings show a difference outside the band, and from then on it is completed on value (T). Alternatives run only on their D. --triage-explore-from candidates keeps the previous draw (the other candidates, alternatives included) as an ablation. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 ++ docs/agentic_benchmark.md | 2 +- evalrx/benchmark/run.py | 8 +- evalrx/benchmark/runner.py | 1 + evalrx/eval_agent/probing/controller.py | 117 ++++++++++++++++-- evalrx/eval_agent/probing/scoring.py | 44 ++++--- .../test_probing_alternatives.py | 88 ++++++++++--- tests/test_eval_agent/test_probing_mvp3.py | 7 ++ 8 files changed, 241 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cf2aee3..d1a67ca5 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed — triage exploration draws from its own targets, on the evidence spending + +Exploration's share (`--triage-explore-share`) is now of the evidence spending, +not including the judge's calls, and it draws only from targets the value never +takes: the next candidate of a route too small to be active, and on each active +route the representative of every other route's layer it does not own (steps +with readings to compare with the controls), priced at a budget check's +conservative estimate. Completing a target on its route is paid from the share +until its readings so far show a difference outside the band; from then on it +is completed on value (T, an incomplete step). Alternatives run only on +their D; `--triage-explore-from candidates` keeps the previous draw (the other +candidates, alternatives included) for ablations. + ### Changed — triage scored scheduler: decidable D, alternatives priced by R, exploration share (MVP-3) D counts each conflicting pair of live explanations by how decidable the diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 9dba08b1..594b206c 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -35,7 +35,7 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. -**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet; one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the spending, `--triage-explore-share` (default 0.1), not of the decisions: whenever a candidate other than the best fits — exploration's spending plus its estimate stays within the share of everything spent — a seeded draw among those runs instead. When no candidate's gain reaches 0.01, every feasible candidate is an exploration candidate, and the run stops once none fits. `--triage-weights` (e.g. `c=0`) sets the weights of D, T, C and R for ablations. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. +**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet; one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the evidence spending, `--triage-explore-share` (default 0.1; the judge's calls are not counted), not of the decisions, and draws from its own targets — actions the value never takes: the next candidate of a route with too few FAIL cases to be active, and on each active route the representative of every other route's layer it does not own, when that step has readings to compare with the controls. Whenever a target fits — exploration's spending plus its conservative estimate (a budget check's) within the share — a seeded draw among them runs instead of the best candidate. Completing a target on its route is exploration too, paid from the share, until the cases measured so far show a reading outside its band (the verdicts' 95% interval): the step has then found something, and its completion is an incomplete step that T values like any other. The run stops once no candidate's gain reaches 0.01 and no target fits. `--triage-explore-from candidates` (an ablation) draws from the candidates other than the best instead, alternatives included. `--triage-weights` (e.g. `c=0`) sets the weights of D, T, C and R for ablations. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. **Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 4c173f19..db0d850b 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -178,8 +178,12 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP help="triage_active with --triage-scheduler scored: the weights of D, T, C and R in U, " "as k=v pairs (keys left out keep 1; an ablation sets one to 0)") p.add_argument("--triage-explore-share", type=float, default=0.1, - help="triage_active with --triage-scheduler scored: the share of the spending exploration " - "may take, on candidates other than the best (0 = none)") + help="triage_active with --triage-scheduler scored: the share of the evidence spending " + "exploration may take (0 = none)") + p.add_argument("--triage-explore-from", choices=["targets", "candidates"], default="targets", + help="triage_active with --triage-scheduler scored: what exploration draws from: targets = " + "inactive routes' next candidates and other routes' representatives (actions the value " + "never takes); candidates = the candidates other than the best (an ablation)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 9161840e..d8da6ba7 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -456,6 +456,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, chunk=int(args.triage_chunk), weights=Weights(**triage_weights(args.triage_weights)), explore_share=float(args.triage_explore_share), + explore_from=args.triage_explore_from, partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "confirm_visible_to_controller": False}, diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index a5dce05e..ec76d666 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -558,6 +558,7 @@ def run_triage( scheduler: str = "rules", weights: "Weights | None" = None, explore_share: float = 0.1, + explore_from: str = "targets", min_gain: float = 0.01, min_cover: int = 8, budget_usd: float = 0.0, @@ -615,8 +616,11 @@ def run_triage( U = q·[D+T+C−R]₊/(c+ε), see :mod:`.scoring`). Both share the ledger; the scored report is ``triage_report.scored``. weights, explore_share, min_gain, min_cover: the scored scheduler's weights, - exploration's share of the spending, value floor and - per-unit coverage target. + exploration's share of the evidence spending, value floor + and per-unit coverage target. + explore_from: ``"targets"`` (exploration takes inactive routes' next candidates + and other routes' representatives, see :mod:`.scoring`) or + ``"candidates"`` (an ablation: the candidates other than the top). budget_usd: USD cap (0 = none), charged like ``budget_sec`` and checked with the step's earlier USD per case. chunk: cases per chunk of a ``reuse`` step (FAIL and PASS alternating; @@ -635,6 +639,8 @@ def run_triage( raise ValueError(f"scheduler must be one of {SCHEDULERS}; got {scheduler!r}") if explainer is not None and scheduler != "scored": raise ValueError("explanations give D to the scored scheduler; the rules scheduler does not read them") + if explore_from not in ("targets", "candidates"): + raise ValueError(f"explore_from must be 'targets' or 'candidates'; got {explore_from!r}") weights = weights or Weights() started = time.monotonic() say = progress or (lambda _msg: None) @@ -865,6 +871,88 @@ def runnable(states: dict[str, list[dict[str, Any]]]) -> tuple[dict[str, list[Op pool[route], offer[route] = rows, rows + extra return pool, offer + explored_on: set[tuple[str, str]] = set() # (route, step key) an exploration decision started + + def exploration_targets(records: list[dict[str, Any]], states: dict[str, list[dict[str, Any]]], growing: bool, + axis: str, readings: Readings + ) -> tuple[list[Scored], list[Scored], list[dict[str, Any]], list[dict[str, Any]]]: + """What only exploration takes (gain 0), the completions of what it found something with, and + what the budget filtered out of each. + + A target is priced at the conservative estimate a budget check uses (exploration's share + is a budget). Completing a target exploration started on a route is exploration too, and + counts against its share, until the cases measured so far show a reading outside its band + (the verdicts' 95% interval): the step has found something, and its completion is then an + incomplete step that T values like any other. + + Targets: the first open layer's candidate of every route with FAIL cases too few to be + active (a low-frequency problem the rules do not pursue), and on every active route the + representative of each other route's layer it does not own (outside its method family), + when it has readings to compare with the PASS controls (a card: the H re-ask and + continuation only mean something where their check fired) and the layer does not narrow + its cases.""" + rows = [] + for row in active_routes(records, min_route_fail): + if row["active"]: + continue + sts = route_states(row["route"], records, run.evidence, run.gate, rank_of, layers=layers, + blocked=run.blocked) + for li, st in enumerate(sts): + if st["state"] in ("open", "extend") and not st.get("battery"): + rows.append((row["route"], li, by_rule[st["rule_id"]], st["step"], st["_fail_ids"], + st["_control_ids"], f"a route too small to be active ({row['n_fail']} FAIL)")) + break + for route, sts in states.items(): + own = {n for st in sts for n in (*by_rule[st["rule_id"]].served_by, + *(c.name for c in by_rule[st["rule_id"]].candidates))} + fail_ids = route_fail_ids(records, route) + controls = matched_controls(records, fail_ids, rank_of)[0] + for layer in layers: + if layer.route != route and layer.case_filter is None and layer.candidates \ + and layer.candidates[0].name not in own and layer.candidates[0].name in CARDS: + rows.append((route, 99, layer, layer.candidates[0], fail_ids, controls, + f"outside the route's method family (the representative of {layer.rule_id})")) + targets: list[Scored] = [] + completions: list[Scored] = [] + held: list[dict[str, Any]] = [] + held_targets: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for route, li, layer, step, fail_ids, controls, why in rows: + if (route, step.name) in seen or step.name in run.blocked or not step.reuse: + continue + seen.add((route, step.name)) + target = [*fail_ids, *controls] + ev = run.evidence.get(step.name) + if ev is not None and ev.refused() is not None: + continue + todo = ev.todo(target) if ev is not None else list(target) + if not todo or run.gate(step, target) is not None: + continue + part = run.chunks(step, todo)[0] + fail_left = set(todo) & set(fail_ids) + share = len(set(part) & fail_left) / len(fail_left) if fail_left else len(part) / len(todo) + started = (route, step.name) in explored_on + found = [f"{m.field} {o['observed']}" for m in CARDS.get(step.name, ()) + if (o := readings(route, step.name, m)).get("observed") in ("up", "down")] if started else [] + if started: + why = (f"completing an exploration that found {', '.join(found)}" if found else + f"completing an exploration ({why}); no reading outside its band yet") + cost, basis = step_cost(step, len(part), run.evidence, axis, unmeasured="typical" if found else "max") + cand = Scored(kind="extend" if started else "follow_up", key=step.name, route=route, + rule_id=layer.rule_id, order=(ROUTE_ORDER.index(route), li), n_new_cases=len(part), + T=share if found else 0.0, q=availability(step.analyzer, run.evidence), cost=cost, + basis=basis, gaps=[f"incomplete:{route}:{step.name}"] if found else [], note=why, + payload=Proposal(layer=layer, step=step, kind="explore", fail_ids=fail_ids, + control_ids=controls, todo=part, tried=[], before=[], + target_override=part)) + over = run.over_budget(run.estimate_sec(step, len(part)), run.estimate_usd(step, len(part))) + if over is not None: + (held if found else held_targets).append({"key": step.name, "route": route, + "rule_id": layer.rule_id, "reason": over}) + continue + (completions if found else targets).append(value(cand, weights, axis)) + return targets, completions, held, held_targets + def route_view(records: list[dict[str, Any]], gaps: list[dict[str, Any]] ) -> tuple[dict[str, list[dict[str, Any]]], bool]: """Every active route's layer states (pending battery steps first), and whether an @@ -1105,9 +1193,16 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], current.decided_at_ask = _decided(verdicts) live = [h for h in (current.hypotheses if current is not None else []) if verdicts[h.id]["state"] == "live"] pool, filtered, axis = scored_pool(records, gaps, states, options, growing, live, outcome_of) - spent = run.charged(axis) + targets: "list[Scored] | None" = None + held_targets: list[dict[str, Any]] = [] + if explore_from == "targets": + targets, completions, held, held_targets = exploration_targets(records, states, growing, axis, + outcome_of) + pool, filtered = pool + completions, filtered + held + # exploration's share is of the evidence: the judge's calls are not an opportunity to explore + spent = run.charged(axis) - float(run.judge_cost.get(axis) or 0.0) pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_share=explore_share, - explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain) + explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain, targets=targets) if pick is None: over = [f for f in filtered if not f["reason"].startswith("batch-dependent")] # a candidate the budget filtered out binds before the gain floor does @@ -1124,12 +1219,16 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], "pending": f"{pick.route}:{pick.rule_id}:{pick.key}"} break ranked = sorted(pool, key=lambda c: (-c.U, c.order)) - skipped = [c.rule_id for c in pool if pick.route and c.route == pick.route and c.order < pick.order] + skipped = [c.rule_id for c in pool if why == "best" and pick.route and c.route == pick.route + and c.order < pick.order] extra = {"choice": why, "scoring_version": SCORING_VERSION, "axis": axis, "U": round(pick.U, 6), "gain": round(pick.gain, 6), "rationale": _scored_rationale(pick, why, explored.get(axis, 0.0), spent, explore_share), **({"alternative_to": pick.alternative_to} if pick.alternative_to else {}), + **({"explore_target": pick.note} if why == "explore" and pick.note else {}), "candidates": [c.row() for c in ranked], "filtered": filtered, + **({"explore_targets": [c.row() for c in targets], "explore_filtered": held_targets} + if targets else {}), **({"explanations": {"key": current.key, "revision": current.revision, "states": {hid: v["state"] for hid, v in verdicts.items()}}} if current is not None else {}), @@ -1160,6 +1259,8 @@ def account() -> None: # what an exploration decision spent counts against its elif record["status"] == SKIPPED: stop = {"reason": "budget", "detail": record.get("reason")} break + if why == "explore" and targets is not None and pick in targets: + explored_on.add((pick.route, pick.key)) if pick.kind != "battery" and (pick.route, pick.rule_id, pick.key) not in followed: followed.append((pick.route, pick.rule_id, pick.key)) round_no += 1 @@ -1254,6 +1355,7 @@ def account() -> None: # what an exploration decision spent counts against its "policy": POLICY_VERSION, "scheduler": scheduler, **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_share": explore_share, + "explore_from": explore_from, "explored": {a: round(v, 6) for a, v in explored.items()}, "min_gain": min_gain, "min_cover": min_cover} if scheduler == "scored" else {}), "rules_version": RULES_VERSION, @@ -1300,8 +1402,9 @@ def _scored_rationale(pick: Scored, why: str, explored: float, spent: float, sha terms = f"U {pick.U:.4g} = q {pick.q:.2f} x [D {pick.D:.3f} + T {pick.T:.3f} + C {pick.C:.3f} - R {pick.R:.3f}]" terms += f" / cost {pick.cost:.4g}" if pick.cost is not None else " / cost unknown" if why == "explore": - return (f"exploration ({explored:.4g} of {spent:.4g} spent so far went to exploration; share {share}): " - + terms) + target = f" of {pick.note}" if pick.note else "" + return (f"exploration{target} ({explored:.4g} of the {spent:.4g} spent on evidence so far went to " + f"exploration; share {share}): " + terms) alt = f"; an alternative to {pick.alternative_to}" if pick.alternative_to else "" return f"highest value: {terms}{alt}" diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/probing/scoring.py index f9467c2f..3d7d75ad 100644 --- a/evalrx/eval_agent/probing/scoring.py +++ b/evalrx/eval_agent/probing/scoring.py @@ -60,13 +60,22 @@ layer waits instead of falling back. Unlike the rules, the scored scheduler may take a later layer first, and says so when it does. -**Exploration** has a share of the spending, not of the decisions (a decision -may be one chunk): a feasible candidate other than the top one fits when what -exploration has spent, plus its estimated cost, stays within ``explore_share`` -of everything spent, and whenever one fits a seeded draw among them runs -instead of the top one. A gain below ``min_gain`` is not worth an action: when -no candidate reaches it, every feasible candidate is an exploration candidate, -and the run stops once none fits in the share (the minimum exploration is met). +**Exploration** has a share of the evidence spending (the judge's calls are not +an opportunity to explore), not of the decisions (a decision may be one +chunk). It draws from its own targets, the actions the rules and the value +never take: the next candidate of each route with FAIL cases too few to be +active (a low-frequency problem), and on each active route the representative +of every other route's layer (outside the route's method family). A target fits +when what exploration has spent, plus its conservative estimate (a budget +check's), stays within ``explore_share`` of the evidence spent; whenever one +fits, a seeded draw among them runs instead of the top candidate. Completing a +target on its route is exploration too, until the cases measured so far show a +reading outside its band: then the step has found something, and its +completion is an incomplete step that T values like any other. A gain below +``min_gain`` is not worth an action: the run stops once no candidate reaches it +and no target fits (the minimum exploration is met). ``explore_from="candidates"`` +(an ablation) draws from the candidates other than the top one instead, +alternatives included. """ from __future__ import annotations @@ -247,20 +256,25 @@ def value(s: Scored, weights: Weights, axis: str) -> Scored: def choose(candidates: list[Scored], *, decision_no: int, seed: int, explore_share: float, explored: float, - spent: float, min_gain: float) -> "tuple[Scored | None, str]": + spent: float, min_gain: float, targets: "list[Scored] | None" = None) -> "tuple[Scored | None, str]": """The candidate to run, and why: ``best`` / ``explore`` / ``below_threshold`` / ``none``. - *explored* and *spent* are what exploration and the whole run have spent so far, on the - candidates' cost axis: a seeded draw among the others that keep exploration within - *explore_share* of the spending runs instead of the best.""" - if not candidates: - return None, "none" + *explored* and *spent* are what exploration and the run's evidence have cost so far, on the + candidates' cost axis. Exploration draws from *targets*, the candidates only it takes; with + ``targets=None`` it draws from the other candidates instead (below the gain floor, from all + of them). A seeded draw among those that keep exploration within *explore_share* of the + spending runs instead of the best.""" ranked = sorted(candidates, key=lambda s: (-s.U, s.order)) - best = ranked[0] - others = ranked[1:] if best.gain >= min_gain else ranked + best = ranked[0] if ranked else None + if targets is None: + others = ranked[1:] if best is not None and best.gain >= min_gain else ranked + else: + others = sorted(targets, key=lambda s: s.order) fits = [s for s in others if explored + (s.cost or 0.0) <= explore_share * (spent + (s.cost or 0.0))] if explore_share > 0 and fits: return random.Random(f"{seed}:{decision_no}").choice(fits), "explore" + if best is None: + return None, "none" if best.gain < min_gain: return None, "below_threshold" return best, "best" diff --git a/tests/test_eval_agent/test_probing_alternatives.py b/tests/test_eval_agent/test_probing_alternatives.py index 2901e2ec..ba44ac24 100644 --- a/tests/test_eval_agent/test_probing_alternatives.py +++ b/tests/test_eval_agent/test_probing_alternatives.py @@ -4,8 +4,11 @@ one gives the kind of evidence the tool that answered the layer gave, 0 when it gives another kind; an alternative closes no gap and covers no unit, so it only runs on a D above its R, and the judge is offered it; -* exploration spends at most its share of what the run spent, and a run whose - candidates are all below the gain floor explores until none fits the share. +* exploration spends at most its share of the evidence and draws only from its + targets, the actions the value never takes (an inactive route's next + candidate, another route's representative); what it started on a route is + completed on value (T); ``explore_from="candidates"`` (ablation) draws from + the candidates other than the best instead, alternatives included. """ from __future__ import annotations @@ -62,11 +65,28 @@ def generate(self, prompt): return json.dumps({"routes": routes}) -def _run(out, layers, judge=None, **over): +class _Flipper(_Table): + """The table model, except that inside the "Q:" wrapper it answers its wrong cases right: wrap_a's + prompt_sensitivity is 1 on every FAIL case and 0 on every PASS case.""" + + def __init__(self, table, cases): + super().__init__(table) + self.gold = {(c.inputs.prompt, c.inputs.image): c.expected for c in cases} + + def generate(self, inputs, **kwargs): + if str(inputs.prompt).startswith("Q: "): + key = (str(inputs.prompt)[3:], inputs.image) + if key in self.gold: + self.n_generate += 1 + return self.gold[key] + return super().generate(inputs, **kwargs) + + +def _run(out, layers, judge=None, model=None, **over): explainer = Explainer(judge, identity={"provider": "stub", "model": "stub"}) if judge is not None else None - return run_triage(_Table(_pope_like()[1]), _pope_like()[0], - **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored", layers=layers, - explainer=explainer, **over)) + return run_triage(model or _Table(_pope_like()[1]), _pope_like()[0], + **_kw(out, **{"max_fail": 8, "min_route_fail": 1, "scheduler": "scored", "layers": layers, + "explainer": explainer, **over})) def _ran(report): @@ -115,14 +135,54 @@ def execute(action, *args, **kwargs): monkeypatch.setattr(controller, "execute", execute) -def test_exploration_spends_at_most_its_share_and_continues_below_the_gain_floor(tmp_path, wrappers, metered): - report = _run(tmp_path / "e", wrappers, explore_share=0.3, chunk=2) +def test_exploration_takes_its_targets_within_its_share_and_pays_for_completing_them(tmp_path, wrappers, metered): + # one case a chunk, so that an explored step has chunks left on the route + report = _run(tmp_path / "e", wrappers, explore_share=0.3, chunk=1) explored = [d for d in report["decisions"] if d.get("choice") == "explore"] - assert explored and all("exploration" in d["rationale"] for d in explored) - assert report["explore_share"] == 0.3 - assert 0 < report["explored"]["wall_sec"] <= 0.3 * report["cost"]["charged"]["wall_sec"] - # below the gain floor only exploration runs, until no candidate fits the share - assert any(d.get("gain") == 0.0 for d in explored) - assert report["stop"]["reason"] in ("below_threshold", "no_candidate") + assert explored and report["explore_share"] == 0.3 and report["explore_from"] == "targets" + # within the share, but for the one chunk whose estimate fell short + assert 0 < report["explored"]["wall_sec"] <= 0.3 * report["cost"]["evidence"]["wall_sec"] + 2.0 + for d in explored: # a target, never a candidate the value could take, and never an alternative + assert d["explore_target"] and "exploration of" in d["rationale"] and d["gain"] == 0.0 + assert (d["route"], d["key"]) not in {(c["route"], c["key"]) for c in d["candidates"]} + assert d["key"] not in ("wrap_b", "wrap_c") + # wrap_a is Z1's representative on S: on N it lies outside the route's method family. The + # table model ignores wrappers, so it finds nothing, and completing it stays exploration + on_n = [d for d in report["decisions"] if (d.get("route"), d.get("key")) == ("N", "wrap_a")] + assert "method family" in on_n[0]["explore_target"] + assert len(on_n) > 1 and all(d["choice"] == "explore" for d in on_n) + assert all("no reading outside its band" in d["explore_target"] for d in on_n[1:]) none = _run(tmp_path / "n", wrappers, explore_share=0.0, chunk=2) assert not [d for d in none["decisions"] if d.get("choice") == "explore"] and not none["explored"] + + +def test_an_exploration_that_finds_something_is_completed_on_value(tmp_path, monkeypatch, metered): + monkeypatch.setitem(CARDS, FIRST.name, (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) + # wrap_a answers an N question; on S (six FAIL cases) it lies outside the route's method family + at = next(i for i, x in enumerate(LAYERS) if x.rule_id == "N3") + layers = (*LAYERS[:at], Layer("Z1", "N", "does a wrapper move it", (FIRST,)), *LAYERS[at:]) + cases, table = _pope_like() + report = _run(tmp_path / "f", layers, model=_Flipper(table, cases), explore_share=0.3, chunk=1) + on_s = [d for d in report["decisions"] if (d.get("route"), d.get("key")) == ("S", "wrap_a")] + assert on_s[0]["choice"] == "explore" and "method family" in on_s[0]["explore_target"] + # once two FAIL cases and two controls show the wrapper moving FAIL answers only, it graduates + graduated = [d for d in on_s if d["choice"] == "best"] + assert graduated and all(d["kind"] == "extend" for d in graduated) + found = next(c for c in graduated[0]["candidates"] if (c["route"], c["key"]) == ("S", "wrap_a")) + assert found["T"] > 0 and "found prompt_sensitivity up" in found["note"] + assert report["outcomes"]["S"]["wrap_a"]["prompt_sensitivity"]["observed"] == "up" + + +def test_exploration_takes_a_route_too_small_to_be_active(tmp_path, wrappers, metered): + report = _run(tmp_path / "i", wrappers, explore_share=0.3, chunk=2, min_route_fail=3) + small = [r["route"] for r in report["routes"] if not r["active"]] + assert small == ["N"] + assert any(d.get("choice") == "explore" and d["route"] == "N" and "too small" in d["explore_target"] + for d in report["decisions"]) + + +def test_the_candidates_ablation_explores_the_other_candidates_alternatives_included(tmp_path, wrappers, metered): + report = _run(tmp_path / "c", wrappers, explore_share=0.3, chunk=2, explore_from="candidates") + explored = {d["key"] for d in report["decisions"] if d.get("choice") == "explore"} + assert explored & {"wrap_b", "wrap_c"} and report["explore_from"] == "candidates" + assert not any(d.get("explore_targets") for d in report["decisions"]) diff --git a/tests/test_eval_agent/test_probing_mvp3.py b/tests/test_eval_agent/test_probing_mvp3.py index 7a831c9c..c85cf8cd 100644 --- a/tests/test_eval_agent/test_probing_mvp3.py +++ b/tests/test_eval_agent/test_probing_mvp3.py @@ -93,6 +93,13 @@ def s(key, U, gain, order, cost=10.0): assert choose(low, decision_no=0, explored=0.0, spent=90.0, **kw) == (low[0], "explore") assert choose(low, decision_no=0, explored=0.0, spent=50.0, **kw) == (None, "below_threshold") assert choose([], decision_no=0, explored=0.0, spent=0.0, **kw) == (None, "none") + # with targets, exploration draws only from them, even with no candidate left + target = s("t", 0.0, 0.0, (2, 99), cost=5.0) + assert choose(pool, decision_no=3, explored=0.0, spent=90.0, targets=[target], **kw) == (target, "explore") + assert choose(pool, decision_no=3, explored=0.0, spent=10.0, targets=[target], **kw)[1] == "best" # no fit + assert choose(pool, decision_no=3, explored=0.0, spent=90.0, targets=[], **kw)[1] == "best" + assert choose([], decision_no=0, explored=0.0, spent=90.0, targets=[target], **kw) == (target, "explore") + assert choose(low, decision_no=0, explored=0.0, spent=90.0, targets=[], **kw) == (None, "below_threshold") def test_scored_run_is_traceable_deterministic_on_resume_and_comparable_with_the_rules(tmp_path): From 96c3158dc5e1fd5c5f5dbd2adb6c7b5bc487fc7b Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:42:32 -0700 Subject: [PATCH 10/26] triage MVP-4: frozen issues validated on unseen media; readings on the model's own answer - validation.py: PartitionBundle (validation = CONFIRM minus cases sharing media with EXPLORE), issues frozen from a triage report (route signals, one reading per route and step), power plan from DISCOVERY, frozen.json before the validation partition is read, Bonferroni over the union of the arms' issues, supported / refuted / inconclusive / unavailable; readings whose per-case values go together within FAIL and within controls are one phenomenon, and each arm is credited with its own issues grouped that way. - --triage-validate, --triage-validation-budget-sec; partition_bundle.json. - Steps with a target read the model's own answer (target="prediction"): a gold margin lower on FAIL restates the label. fixed_* readings are off the cards; run_triage and the validator refuse a carded gold-target step. - t quantile by exact inversion; intervals at a given level. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 31 + docs/agentic_benchmark.md | 6 +- evalrx/benchmark/run.py | 5 + evalrx/benchmark/runner.py | 46 +- evalrx/eval_agent/probing/__init__.py | 3 + evalrx/eval_agent/probing/controller.py | 61 +- evalrx/eval_agent/probing/explanations.py | 128 +++- evalrx/eval_agent/probing/rules.py | 28 +- evalrx/eval_agent/probing/triage.py | 17 +- evalrx/eval_agent/probing/validation.py | 668 ++++++++++++++++++ tests/test_eval_agent/test_probing_mvp0.py | 2 +- .../test_probing_validation.py | 201 ++++++ 12 files changed, 1109 insertions(+), 87 deletions(-) create mode 100644 evalrx/eval_agent/probing/validation.py create mode 100644 tests/test_eval_agent/test_probing_validation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d1a67ca5..a633c0ec 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,37 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — triage diagnostic validation (MVP-4, first version) + +The triage run fixes its data roles before the controller sees a case +(`/partition_bundle.json`): DISCOVERY = EXPLORE, DIAGNOSTIC_VALIDATION = +the CONFIRM cases on media DISCOVERY does not contain. `--triage-validate` +freezes the issues the report supports (route signals and reading differences +on routes, `probing/validation.py`), writes the family and a power plan from +DISCOVERY to `/validation/frozen.json`, then validates every issue once +at a Bonferroni-adjusted level: supported / refuted / inconclusive / +unavailable. Readings that go together case by case within FAIL and within the +controls (pooled within-group Spearman |rho| >= 0.5, same route) are grouped +into one phenomenon, and each arm is credited with its own issues' verdicts +grouped that way (supported phenomena is the main count). Interval helpers +take a level (`explanations.t_quantile` inverts the t distribution exactly; +`triage.difference_interval(z=...)`); `controller.analyzer_extras` gives the +validator DISCOVERY's frozen lens references and fit set; the validator +refuses a report from another rules version. + +### Changed — triage readings use the model's own answer, not gold + +Card readings compare FAIL cases with PASS controls, and a FAIL output is not +gold by definition, so a gold margin lower on FAIL restated the label. The +triage steps with a target (`attention_knockout`, `causal_trace`, +`attention_temperature`, `attention_sensitivity`, `gradcam`, +`generic_attention`, `patchscope`) now use `target="prediction"`; the +"wrong before, right after" readings (`fixed_*`) stay in the step output but +are off the cards; `run_triage` and the validator refuse a carded step whose +target, in its config or the host's analyzer kwargs, is gold +(`explanations.label_bound`). Rules version `mvp4-rules-2`, explanations +`mvp4-explain-3`. + ### Changed — triage exploration draws from its own targets, on the evidence spending Exploration's share (`--triage-explore-share`) is now of the evidence spending, diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 594b206c..b642d1b8 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -29,7 +29,7 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend --m1-policy triage_active --run-tag triage0 ``` -After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="gold", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="prediction")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="prediction", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. **Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Every step's per-case rows are independent of the batch, so steps run on the new cases alone and keep the old rows: `embed_lens` and `patchscope` tell question words (and `embed_lens` recurring media words, from the first 16 distinct images) from a fixed reference — EXPLORE in the sampler's rank order — instead of the batch, `tuned_lens` is fit once on the first 32 of those cases (cached on the model), and `causal_trace` seeds its noise from each case's content instead of its position; `self_consistency` draws each case's samples under a seed of its content too, so the U sampling check is the same in every run. No route reads `embed_lens` or `patchscope`, so they still wait until the sample stops growing. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). @@ -39,9 +39,11 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. +**Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); repair CONFIRM is not part of this protocol. With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 0.05/K` (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way, and the number of supported phenomena is the main count. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are checked where the validation measured their steps and reported apart. `--triage-validation-budget-sec` caps the validation's evidence. + The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. -U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Any readable answer that differs fires U. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the gold answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. +U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Any readable answer that differs fires U. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the model's own answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. On an API model (`--backend gemini`) the same plan runs with the white-box steps recorded as `unsupported` (nothing spent). Each action's cost carries what the provider counted — requests, retries, prompt/completion/thought tokens — and its USD at the dated listed price in `evalrx/models/backends/api/prices.py` (unknown for an unlisted model); Stage 0's usage goes into `baseline.json`. The rule-chosen follow-ups are gated on the actual model in the same way, so a run without internal state runs its behavioural follow-ups and records why the internal ones cannot run. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index db0d850b..977487db 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -184,6 +184,11 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP help="triage_active with --triage-scheduler scored: what exploration draws from: targets = " "inactive routes' next candidates and other routes' representatives (actions the value " "never takes); candidates = the candidates other than the best (an ablation)") + p.add_argument("--triage-validate", action=argparse.BooleanOptionalAction, default=False, + help="triage_active: freeze the issues the triage report supports and validate them once on " + "the CONFIRM cases whose media EXPLORE does not contain (/validation/)") + p.add_argument("--triage-validation-budget-sec", type=float, default=0.0, + help="triage_active with --triage-validate: wall-clock cap on the validation's evidence (0 = none)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index d8da6ba7..8a44e89e 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -410,13 +410,26 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: controller sees EXPLORE only and runs no M2-M5; it calls the judge only with ``--triage-explanations judge`` (scored scheduler: explanations for D, from route summaries, never a case). Outputs go to ``/probing/``. + + The data roles are fixed first (``/partition_bundle.json``): DISCOVERY is + EXPLORE, DIAGNOSTIC_VALIDATION the CONFIRM cases on media EXPLORE does not + contain. With ``--triage-validate`` the issues the report supports are frozen + and validated once on DIAGNOSTIC_VALIDATION (``/validation/``). """ from evalrx.eval_agent.probing import explore_confirm_split, run_triage from evalrx.eval_agent.probing.scoring import Weights + from evalrx.eval_agent.probing.validation import freeze_issues, partition_bundle, validate from .run import triage_weights explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED) + bundle, validation = partition_bundle(explore, confirm, seed=CONFIRM_SPLIT_SEED, + confirm_split=float(args.confirm_split), manifest=baseline.get("manifest")) + if args.triage_validate and not len(validation): + raise SystemExit("--triage-validate needs CONFIRM cases on media EXPLORE does not contain; " + "set --confirm-split above 0") + bundle_row = bundle.to_dict() + (run_dir / "partition_bundle.json").write_text(json.dumps(bundle_row, indent=2) + "\n", encoding="utf-8") runtime = getattr(model, "runtime", None) identity = { "spec": spec.key, "weights": spec.hf_repo, "backend": resolved.backend, @@ -439,29 +452,37 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: # API backends ignore per-call kwargs (their runtime samples); without # settings here the U sampling check stays untested, never trivially clear extras["self_consistency"] = {"gen_kwargs": sampling} + # what discovery and validation run with alike + shared = dict(seed=args.triage_seed, + stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", + host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), + n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), + task_kind=task.kind, answer_fn=T.answer_key, analyzer_kwargs=extras, price_fn=_price_fn(spec), + per_call_generation=sampling is not None, chunk=int(args.triage_chunk)) report = run_triage( model, explore, out_dir=run_dir / "probing", model_identity=identity, n_fail=args.triage_n_fail, max_fail=args.triage_max_fail, max_actions=args.triage_max_actions, - seed=args.triage_seed, - stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", - host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), - n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), - task_kind=task.kind, answer_fn=T.answer_key, analyzer_kwargs=extras, budget_sec=float(args.triage_budget_sec), stage0_cost={"wall_sec": baseline["seconds"], "calls": {"generate": baseline["n"]}, "n_cases": baseline["n"], **{k: baseline[k] for k in ("api_usage", "usd") if k in baseline}}, - price_fn=_price_fn(spec), - per_call_generation=sampling is not None, scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, - chunk=int(args.triage_chunk), weights=Weights(**triage_weights(args.triage_weights)), explore_share=float(args.triage_explore_share), explore_from=args.triage_explore_from, partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, + "n_validation": len(validation), "bundle_sha1": bundle_row["sha1"], "confirm_visible_to_controller": False}, - run_logger=ctx.logger, + run_logger=ctx.logger, **shared, ) + from evalrx.eval_agent.probing.controller import report_name + + name = report_name(args.triage_scheduler, explainer is not None) + checked = None + if args.triage_validate: + checked = validate(model, explore, validation, {name: freeze_issues(report)}, {name: report}, + out_dir=run_dir / "validation", model_identity=identity, bundle=bundle, + budget_sec=float(args.triage_validation_budget_sec), run_logger=ctx.logger, **shared) ctx.finalize() summary = { "model": args.model, "spec": spec.key, "dataset": task.name, "modality": task.modality, @@ -471,12 +492,11 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: for s in report["executions"]], "triage_stop": report["stop"], "triage_scheduler": report["scheduler"], "triage_explanations": args.triage_explanations, + **({"validation": {"frozen_sha1": checked["frozen_sha1"], **checked["arms"][name]}} if checked else {}), } (run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n", encoding="utf-8") - from evalrx.eval_agent.probing.controller import report_name - - name = report_name(args.triage_scheduler, explainer is not None) - print(f"Done (triage). {run_dir / 'probing' / (name + '.md')}") + print(f"Done (triage). {run_dir / 'probing' / (name + '.md')}" + + (f"; validation: {run_dir / 'validation' / 'validation_report.md'}" if checked else "")) return 0 diff --git a/evalrx/eval_agent/probing/__init__.py b/evalrx/eval_agent/probing/__init__.py index 893a3054..348d59cb 100644 --- a/evalrx/eval_agent/probing/__init__.py +++ b/evalrx/eval_agent/probing/__init__.py @@ -20,6 +20,9 @@ triage.py H/N/U/S/X route labels traced back to case, field and action rules.py route layers, follow-up choice, and the expansion rule controller.py the battery and run_triage() + scoring.py the scored scheduler's value of a candidate (MVP-3) + explanations.py competing explanations, their predictions and D (MVP-3) + validation.py the data roles, frozen issues and their one validation (MVP-4) Nothing here is imported by the default ``judge`` path. """ diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index ec76d666..87c2de7c 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -8,17 +8,21 @@ 1. ``answer_extraction_audit``: re-reads the Stage-0 outputs (no model call). 2. ``termination_audit`` without continuation: re-reads the outputs too. 3. ``modality_ablation(mode="swap")``: the N check. - 4. ``attention_knockout(target="gold")``: the first N-layer measurement. + 4. ``attention_knockout(target="prediction")``: the first N-layer measurement. 5. ``self_consistency``: re-samples each case (U). 6. ``prompt_contrast`` with the question kept verbatim in neutral wrappers (U). 7. ``prompt_contrast`` with an instruction not to default to "no" (yes/no tasks only), descriptive S. 8. ``embed_lens(layer=0.9)``: is the case's own question word near the media tokens late in the stack (S2). - 9. ``patchscope(target="gold", media_layers=3)``: was the gold answer - readable before the output, and is the question word read off the + 9. ``patchscope(target="prediction", media_layers=3)``: how early the + model's own answer was readable, and is the question word read off the media tokens (S3, S2). + Steps with a target read the model's own answer, never gold: their + readings are compared between FAIL cases and PASS controls, and a FAIL + output is not gold by definition. + 2. **Expansion.** While an evidence gap holds that more cases can close, the controller decides to expand. The sample then doubles along the sampler's rank prefixes, and the battery runs again only where it has to: @@ -92,6 +96,7 @@ check, decidability, disagreement, + label_bound, outcome, ) from evalrx.eval_agent.probing.explanations import spread as reading_spread @@ -176,8 +181,8 @@ "re-ask with media on which the same question's gold differs from the model's answer " "(else any different media); an answer that should change but does not is the N signal", calls_per_case={"generate": 2}), - PlanStep("attention_knockout", {"target": "gold"}, "N1", - "cut text-to-media attention per layer band; margin change of the gold first token", + PlanStep("attention_knockout", {"target": "prediction"}, "N1", + "cut text-to-media attention per layer band; margin change of the model's own first answer token", fidelity_check="edit", calls_per_case={"forward": 5}, evidence=MEDIA_ATTENTION_CUT), PlanStep("self_consistency", {"n": 5}, "U", "re-sample each case at the host's frozen sampling settings; an answer that differs " @@ -196,10 +201,10 @@ "nearest vocabulary words of the media tokens late in the stack: how close the " "case's own question word gets", calls_per_case={"forward": 1}, deferred=True), - PlanStep("patchscope", {"target": "gold", "media_layers": 3}, "S3", + PlanStep("patchscope", {"target": "prediction", "media_layers": 3}, "S3", "decode the answer position at every layer and the media tokens at three depths: " - "whether the gold answer was readable before the output, and whether the question " - "word is read off the media", + "how early the model's own answer was readable, and whether the question word is " + "read off the media", fidelity_check="patch", calls_per_case={"forward": 1}, deferred=True, evidence=LAYER_READOUT), ) @@ -210,6 +215,28 @@ def _write_json(path: Path, payload: Any) -> None: os.replace(tmp, path) +def analyzer_extras(analyzer_kwargs: "dict[str, dict[str, Any]] | None", discovery: "CaseBatch", seed: int, *, + donor_pool: "CaseBatch | None" = None) -> dict[str, dict[str, Any]]: + """Per-analyzer constructor extras: the host's, plus what is fixed on DISCOVERY. + + The lenses tell question words (and embed_lens recurring words) from a fixed reference, + DISCOVERY in the sampler's rank order, and the tuned lens is fit on the first ``FIT_CASES`` + of it, so a case's row never depends on the sample it is read with; a validation run on + other cases uses the same frozen artefacts. Swap donors come from the partition the cases + are drawn from (*donor_pool*, default DISCOVERY). + """ + from evalrx.core.case import CaseBatch + + extras = {k: dict(v) for k, v in (analyzer_kwargs or {}).items()} + extras.setdefault("modality_ablation", {}).setdefault("donor_pool", donor_pool if donor_pool is not None + else discovery) + ranked = CaseBatch(sorted(discovery, key=lambda c: rank(seed, str(c.id)))) + for name in ("embed_lens", "patchscope"): + extras.setdefault(name, {}).setdefault("reference", ranked) + extras.setdefault("tuned_lens", {}).setdefault("fit_cases", CaseBatch(list(ranked)[:FIT_CASES])) + return extras + + def tool_version(analyzer: Any) -> str: """Content hash of the analyzer's module and the shared ``analyzers/_internals``. @@ -646,18 +673,10 @@ def run_triage( say = progress or (lambda _msg: None) out = Path(out_dir) ledger = Ledger(out) - extras = {k: dict(v) for k, v in (analyzer_kwargs or {}).items()} - # swap donors come from the whole partition the sample was drawn from - extras.setdefault("modality_ablation", {}).setdefault("donor_pool", explore) - # Fixed references in the sampler's rank order, so a case's row never depends on the - # sample it is read with: the lenses tell question words (and embed_lens recurring - # words) from them, and the tuned lens is fit on the first FIT_CASES of them. - from evalrx.core.case import CaseBatch - - ranked = CaseBatch(sorted(explore, key=lambda c: rank(seed, str(c.id)))) - for name in ("embed_lens", "patchscope"): - extras.setdefault(name, {}).setdefault("reference", ranked) - extras.setdefault("tuned_lens", {}).setdefault("fit_cases", CaseBatch(list(ranked)[:FIT_CASES])) + extras = analyzer_extras(analyzer_kwargs, explore, seed) + if bound := label_bound((*battery, *candidate_steps(layers)), extras): + raise ValueError(f"steps {bound} read the gold answer (target='gold'): their readings are compared " + "between FAIL and PASS, where that restates the label; use target='prediction'") max_fail = max(int(n_fail), int(max_fail or n_fail)) n_available = sum(1 for c in explore if getattr(getattr(c, "label", None), "value", None) == "fail") run = _Run(model, explore, ledger, context={"policy": POLICY_VERSION, "model": model_identity}, @@ -1736,7 +1755,7 @@ def _markdown(report: dict[str, Any]) -> str: f"patchscope {_why_not(report, 'patchscope')}. Cohort sizes: {sizes}."] elif cohorts: lines += ["", "## S readings (descriptive)", "", - "| cohort | stratum | n | mean el_query_sim | gold first before last | mean peak / final prob " + "| cohort | stratum | n | mean el_query_sim | answer first before last | mean peak / final prob " "| mean late drop | question word on media |", "|---|---|---:|---:|---:|---|---:|---:|"] for name, stratum, row in cohorts: ps = row["patchscope"] diff --git a/evalrx/eval_agent/probing/explanations.py b/evalrx/eval_agent/probing/explanations.py index 547c6316..cc6b8342 100644 --- a/evalrx/eval_agent/probing/explanations.py +++ b/evalrx/eval_agent/probing/explanations.py @@ -17,7 +17,12 @@ The readings, their meaning, sign and band are fixed here, per step, in ``CARDS``: the judge picks a direction, never the metric, the comparison or -the threshold. Code, not the judge, checks the predictions against the +the threshold. A card compares FAIL with PASS, so no reading on it may be +computed from the correctness label or the gold answer: a FAIL case's output +is not gold by definition, so "the gold margin is lower on FAIL" restates the +label. Steps with a target read the model's own answer (``target="prediction"``), +and readings such as "wrong before, right after" stay in the step's output but +off the cards. Code, not the judge, checks the predictions against the evidence (``verdict``): a prediction is a hit when the 95% interval of the difference lies inside its region, a miss when it lies outside, and undetermined otherwise. An explanation with a miss is contradicted and leaves @@ -63,12 +68,12 @@ from dataclasses import dataclass, field from itertools import combinations from pathlib import Path -from typing import Any, Callable +from typing import Any, Callable, Iterable from evalrx.eval_agent.probing.metering import usage_counters, usage_delta from evalrx.eval_agent.probing.triage import difference_interval -EXPLAIN_VERSION = "mvp3-explain-2" +EXPLAIN_VERSION = "mvp4-explain-3" DIRECTIONS = ("up", "down", "same", "unknown") _ALIASES = {"↑": "up", "↓": "down", "≈": "same", "=": "same", "~": "same", "?": "unknown", "higher": "up", "lower": "down", "increase": "up", "decrease": "down", "none": "unknown"} @@ -89,11 +94,24 @@ def card(self) -> dict[str, Any]: "kind": "share of cases" if self.kind == "rate" else "mean"} +#: Analyzer targets that are the correctness label in another form. +LABEL_TARGETS = ("gold",) + + +def label_bound(steps: "Iterable[Any]", extras: "dict[str, dict[str, Any]] | None" = None) -> list[str]: + """The carded steps whose target (in the step's config or the host's constructor extras) is the + gold answer: their FAIL-vs-PASS difference would restate the label.""" + extras = extras or {} + return sorted({s.name for s in steps if s.name in CARDS and any( + (d or {}).get("target") in LABEL_TARGETS for d in (s.config, extras.get(s.analyzer)))}) + + def _rate(field_: str, meaning: str, band: float = 0.1) -> Metric: return Metric(field_, meaning, band, "rate") -_MARGIN = "the gold first-token logit margin (gold vs its strongest competitor, fixed on the clean run)" +_MARGIN = ("the answer margin: the logit of the model's own first answer token minus its strongest " + "competitor's, both fixed on the clean run") #: The readings each step's predictions may name, by step key (``PlanStep.name``). #: Bands are fixed before any run: 0.1 for shares of cases, 0.5 for logit @@ -101,27 +119,27 @@ def _rate(field_: str, meaning: str, band: float = 0.1) -> Metric: #: predictions (D = 0): the H re-ask and continuation run on FAIL cases only, #: so their readings have no PASS control to compare with. CARDS: dict[str, tuple[Metric, ...]] = { - # N: does the media path carry the gold answer + # N: does the media path carry the answer "attention_knockout": ( Metric("ko_delta_full", f"{_MARGIN}, clean minus with text-to-media attention cut in every layer; " - ">0 = the media reading supported gold", 0.5), + ">0 = the media reading supported the answer", 0.5), Metric("ko_delta_late", "the same with the cut in the last third of layers only", 0.5)), "causal_trace": ( Metric("ct_media_effect", f"{_MARGIN}, clean minus with the media embeddings noised; >0 = the media " - "supported gold", 0.5), + "supported the answer", 0.5), _rate("ct_effect_traceable", "the noising moved the margin by at least 1 logit")), "attention_temperature": ( - Metric("tt_slope", "change of the gold margin per log-unit of attention temperature over the media " - "(flat minus sharp over ln 4); <0 = sharper focus on the media helps gold", 0.25), + Metric("tt_slope", "change of the answer margin per log-unit of attention temperature over the media " + "(flat minus sharp over ln 4); <0 = sharper focus on the media strengthens the " + "answer", 0.25), Metric("tt_delta_sharp", f"{_MARGIN} with media attention sharpened (temperature 0.5) minus clean", 0.5), Metric("tt_media_entropy", "normalised entropy of text-to-media attention (1 = spread evenly)", 0.05)), "attention_sensitivity": ( - Metric("rw_slope", "change of the gold margin per log-unit of media attention scaling (x2 vs x0.5); " - ">0 = more attention to the media helps gold", 0.25), + Metric("rw_slope", "change of the answer margin per log-unit of media attention scaling (x2 vs x0.5); " + ">0 = more attention to the media strengthens the answer", 0.25), Metric("rw_delta_up", f"{_MARGIN} with media attention doubled minus clean", 0.5)), "describe_first": ( - _rate("changed_describe_first", "the answer changes when asked to describe the media first"), - _rate("fixed_describe_first", "wrong before, right after describing first")), + _rate("changed_describe_first", "the answer changes when asked to describe the media first"),), # U: is the answer near a tie, does it follow content "logprob_entropy": ( Metric("mean_top_entropy", "entropy (nats) over the top alternatives per output token, mean; " @@ -136,16 +154,15 @@ def _rate(field_: str, meaning: str, band: float = 0.1) -> Metric: "content", 0.1)), # S: where the stable error sits "prompt_threshold": ( - _rate("changed_sensitive", "the answer changes when told not to default to a negative answer"), - _rate("fixed_sensitive", "wrong before, right after that instruction")), + _rate("changed_sensitive", "the answer changes when told not to default to a negative answer"),), "gradcam": ( Metric("gc_media_grad_share", "share of gradient x activation on the media tokens (at mid depth) of " - "the gold margin; low = the margin hinges on the text", 0.05), + "the answer margin; low = the margin hinges on the text", 0.05), Metric("gc_top5_share", "share of the media map's positive mass in its top 5% of positions; " "higher = more concentrated", 0.05), Metric("gc_entropy", "normalised entropy of the media map (1 = diffuse)", 0.05)), "generic_attention": ( - Metric("rel_media_share", "share of propagated attention relevance of the gold margin on the media " + Metric("rel_media_share", "share of propagated attention relevance of the answer margin on the media " "tokens; low = built from the text", 0.05), Metric("rel_top5_share", "share of the media relevance map in its top 5% of positions", 0.05), Metric("rel_entropy", "normalised entropy of the media relevance map (1 = diffuse)", 0.05)), @@ -155,10 +172,10 @@ def _rate(field_: str, meaning: str, band: float = 0.1) -> Metric: Metric("el_frac_specific", "share of media tokens decoding to case-specific (not recurring, not " "high-norm) words", 0.05)), "patchscope": ( - Metric("ps_peak_prob", "highest probability of the gold answer read off the answer position at any " - "layer", 0.05), - Metric("ps_late_drop", "that peak minus the output's gold probability; >0 = gold was more readable " - "mid-stack than at the output", 0.05), + Metric("ps_peak_prob", "highest probability of the model's own answer read off the answer position at " + "any layer", 0.05), + Metric("ps_late_drop", "that peak minus the answer's probability at the output; >0 = the answer was " + "more readable mid-stack than at the output", 0.05), Metric("ps_media_query_share", "share of media-token readouts that are the case's question word", 0.05)), "tuned_lens": ( Metric("tl_late_drop", "peak minus final probability of the model's own final answer across fitted " @@ -190,18 +207,72 @@ def _t975(df: float) -> float: return 2.021 if k < 60 else 2.000 if k < 120 else 1.960 +def z_quantile(level: float) -> float: + """Two-sided normal quantile: ``z`` with ``P(|Z| <= z) = level``.""" + from statistics import NormalDist + + return NormalDist().inv_cdf(0.5 + level / 2) + + +def _betacf(a: float, b: float, x: float) -> float: + """Continued fraction of the regularised incomplete beta function (modified Lentz).""" + tiny, qab, qap, qam = 1e-300, a + b, a + 1.0, a - 1.0 + c, d = 1.0, 1.0 - qab * x / qap + d = 1.0 / (d if abs(d) > tiny else tiny) + h = d + for m in range(1, 300): + m2 = 2 * m + for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))): + d = 1.0 + aa * d + d = 1.0 / (d if abs(d) > tiny else tiny) + c = 1.0 + aa / c + c = c if abs(c) > tiny else tiny + h *= d * c + if abs(d * c - 1.0) < 1e-14: + break + return h + + +def _t_two_sided(t: float, k: int) -> float: + """``P(|T| <= t)`` for Student's t with *k* degrees of freedom: ``1 - I_{k/(k+t^2)}(k/2, 1/2)``.""" + x = k / (k + t * t) + a, b = k / 2.0, 0.5 + front = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)) + ibeta = front * _betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1.0 - front * _betacf(b, a, 1 - x) / b + return 1.0 - ibeta + + +def t_quantile(level: float, df: float) -> float: + """Two-sided Student-t quantile at ``floor(df)`` degrees of freedom (conservative): the table + above at 95%, else the CDF (incomplete beta) inverted by bisection, e.g. for a family-wise + adjusted interval.""" + if abs(level - 0.95) < 1e-12: + return _t975(df) + k = max(1, int(math.floor(df))) + lo, hi = 0.0, 1.0 + while _t_two_sided(hi, k) < level: + hi *= 2.0 + for _ in range(200): + mid = (lo + hi) / 2 + lo, hi = (mid, hi) if _t_two_sided(mid, k) < level else (lo, mid) + if hi - lo < 1e-10: + break + return hi + + def _mean(xs: list[float]) -> float: return sum(xs) / len(xs) -def difference(fail: list[float], control: list[float], kind: str) -> "tuple[float, list[float]] | None": - """``(FAIL mean - control mean, 95% interval)``; ``None`` below ``MIN_N`` cases a side.""" +def difference(fail: list[float], control: list[float], kind: str, + level: float = 0.95) -> "tuple[float, list[float]] | None": + """``(FAIL mean - control mean, interval at *level*)``; ``None`` below ``MIN_N`` cases a side.""" if len(fail) < MIN_N or len(control) < MIN_N: return None diff = _mean(fail) - _mean(control) if kind == "rate": ci = difference_interval(sum(1 for x in fail if x >= 0.5), len(fail), - sum(1 for x in control if x >= 0.5), len(control)) + sum(1 for x in control if x >= 0.5), len(control), z=z_quantile(level)) return diff, list(ci or [diff, diff]) vf = sum((x - _mean(fail)) ** 2 for x in fail) / (len(fail) - 1) / len(fail) vc = sum((x - _mean(control)) ** 2 for x in control) / (len(control) - 1) / len(control) @@ -209,7 +280,7 @@ def difference(fail: list[float], control: list[float], kind: str) -> "tuple[flo if se == 0.0: return diff, [diff, diff] df = (vf + vc) ** 2 / ((vf ** 2 / (len(fail) - 1) if vf else 0.0) + (vc ** 2 / (len(control) - 1) if vc else 0.0)) - half = _t975(df) * se + half = t_quantile(level, df) * se return diff, [diff - half, diff + half] @@ -238,8 +309,9 @@ def verdict(direction: str, ci: "list[float] | None", band: float) -> str: def outcome(values: "dict[str, dict[str, Any]]", fail_ids: list[str], control_ids: list[str], - metric: Metric) -> dict[str, Any]: - """The reading's FAIL-vs-control difference on these cases, from per-case ``follow_up_values``.""" + metric: Metric, level: float = 0.95) -> dict[str, Any]: + """The reading's FAIL-vs-control difference on these cases, from per-case ``follow_up_values``, + with its interval at *level*.""" def take(ids: list[str]) -> list[float]: return [float(values[c]["values"][metric.field]) for c in ids if values.get(c, {}).get("state") == "measured" and metric.field in values[c]["values"]] @@ -250,7 +322,7 @@ def take(ids: list[str]) -> list[float]: out["fail_mean"] = round(_mean(f), 4) if c: out["control_mean"] = round(_mean(c), 4) - res = difference(f, c, metric.kind) + res = difference(f, c, metric.kind, level) if res is None: out["observed"] = "not_measured" if not f and not c else "undetermined" return out diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index 5bce3cf3..2b9fa2d3 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -47,18 +47,18 @@ from evalrx.eval_agent.probing.actions import PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -RULES_VERSION = "mvp2-rules-1" +RULES_VERSION = "mvp4-rules-2" ROUTE_ORDER = ("H", "N", "U", "S", "X") DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} #: Kinds of evidence (``PlanStep.evidence``) that more than one tool of a layer gives: #: once one of them has answered the layer, another of the same kind is redundant. -MEDIA_ATTENTION_CUT = "text-to-media attention cut, gold margin" -MEDIA_NOISE = "media embeddings noised and restored, gold margin" -ATTENTION_RESCALING = "attention to the media rescaled, gold margin" +MEDIA_ATTENTION_CUT = "text-to-media attention cut, answer margin" +MEDIA_NOISE = "media embeddings noised and restored, answer margin" +ATTENTION_RESCALING = "attention to the media rescaled, answer margin" TOKEN_PROBABILITIES = "output-token probabilities" RESAMPLING = "re-sampled answers" -RELEVANCE_MAP = "relevance map of the gold margin over the media" +RELEVANCE_MAP = "relevance map of the answer margin over the media" LAYER_READOUT = "answer position read out layer by layer" #: Room for a description before the answer, asked per call (the task's own cap @@ -100,14 +100,14 @@ class Layer: Layer("H2", "H", "continued past where it stopped, does the output reach an answer", ( PlanStep("termination_audit", {"continue_non_clean": True}, "H2", "continue the outputs that did not end cleanly", key="termination_continue", calls_per_case={"generate": 1}),)), - Layer("N1", "N", "does the media path carry a measurable effect on the gold answer", ( - PlanStep("causal_trace", {"target": "gold"}, "N1", "corrupt the media, restore one site at a time", + Layer("N1", "N", "does the media path carry a measurable effect on the answer", ( + PlanStep("causal_trace", {"target": "prediction"}, "N1", "corrupt the media, restore one site at a time", calls_per_case={"forward": 20}, evidence=MEDIA_NOISE),), served_by=("attention_knockout",)), - Layer("N2", "N", "does reading the media with sharper or flatter attention change the gold margin", ( - PlanStep("attention_temperature", {"target": "gold"}, "N2", "rescale the media attention temperature", + Layer("N2", "N", "does reading the media with sharper or flatter attention change the answer margin", ( + PlanStep("attention_temperature", {"target": "prediction"}, "N2", "rescale the media attention temperature", fidelity_check="edit", calls_per_case={"forward": 4}, evidence=ATTENTION_RESCALING), - PlanStep("attention_sensitivity", {"target": "gold"}, "N2", "scale attention to the media down and up", + PlanStep("attention_sensitivity", {"target": "prediction"}, "N2", "scale attention to the media down and up", fidelity_check="edit", calls_per_case={"forward": 4}, evidence=ATTENTION_RESCALING))), Layer("N3", "N", "asked to describe the media first, does the answer start to follow it", ( _describe("N3", "describe the media, then answer"),)), @@ -122,14 +122,14 @@ class Layer: task_kinds=("multiple_choice_letter",)),)), Layer("Sb", "S", "does a stable error survive when the model first states what it sees", ( _describe("Sb", "describe the media, then answer"),)), - Layer("S1", "S", "which image regions the gold margin depends on (no reference regions: " + Layer("S1", "S", "which image regions the answer margin depends on (no reference regions: " "concentration only, not 'mislocalised')", ( - PlanStep("gradcam", {"target": "gold"}, "S1", "gradient x activation map of the gold margin", + PlanStep("gradcam", {"target": "prediction"}, "S1", "gradient x activation map of the answer margin", calls_per_case={"backward": 1}, evidence=RELEVANCE_MAP), - PlanStep("generic_attention", {"target": "gold"}, "S1", "attention relevance of the gold margin", + PlanStep("generic_attention", {"target": "prediction"}, "S1", "attention relevance of the answer margin", fidelity_check="edit", calls_per_case={"backward": 1}, evidence=RELEVANCE_MAP))), Layer("S2", "S", "is the case's own question word readable off the media tokens", (), served_by=("embed_lens",)), - Layer("S3", "S", "was the gold answer readable before the output", ( + Layer("S3", "S", "how early in the stack the answer was readable", ( PlanStep("tuned_lens", {}, "S3", "fitted per-layer readout of the answer position (translators " "fit once on a fixed set of EXPLORE cases)", calls_per_case={"forward": 1}, evidence=LAYER_READOUT), diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index 1da6f6a0..cda76b95 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -24,8 +24,8 @@ * **S** (a stable failure): a FAIL case on which every required check ran and none fired — H, N (cases with media) and both U parts. S is an investigation route, not a cause; the S readings attached to every case - (the threshold instruction, the question word on the media tokens, whether - the gold answer was readable before the output) are descriptive. + (the threshold instruction, the question word on the media tokens, how early + the model's own answer was readable) are descriptive. * **X**: no route fired and a required check is missing, with the reasons. A missing check never makes a case S. A PASS case with every check clear has no route (it is a stable control). @@ -518,8 +518,8 @@ def _s_readings(records: list[dict[str, Any]]) -> dict[str, Any]: }, } out["_note"] = ("descriptive only, no test: el_query_sim = the case's own question word against the media " - "tokens; target_first_before_last = the patchscope target (gold) ranked first at some layer " - "before the last; media_query_hit = the question word decoded off some media token") + "tokens; target_first_before_last = the patchscope target (the model's own answer) ranked first at " + "some layer before the last; media_query_hit = the question word decoded off some media token") return out @@ -530,12 +530,13 @@ def _wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]: return max(0.0, centre - half), min(1.0, centre + half) -def difference_interval(k1: int, n1: int, k2: int, n2: int) -> "list[float] | None": - """95% interval of ``k1/n1 - k2/n2`` (Newcombe's hybrid score method), ``None`` if a side is empty.""" +def difference_interval(k1: int, n1: int, k2: int, n2: int, z: float = 1.96) -> "list[float] | None": + """Interval of ``k1/n1 - k2/n2`` (Newcombe's hybrid score method; 95% at the default *z*), + ``None`` if a side is empty.""" if not n1 or not n2: return None p1, p2 = k1 / n1, k2 / n2 - (l1, u1), (l2, u2) = _wilson(k1, n1), _wilson(k2, n2) + (l1, u1), (l2, u2) = _wilson(k1, n1, z), _wilson(k2, n2, z) d = p1 - p2 return [round(d - math.sqrt((p1 - l1) ** 2 + (u2 - p2) ** 2), 4), round(d + math.sqrt((u1 - p1) ** 2 + (p2 - l2) ** 2), 4)] @@ -585,7 +586,7 @@ def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: "mean_ko_delta_full": _mean([float(r["ko_delta_full"]) for r in rows if "ko_delta_full" in r]), "mean_ko_delta_late": _mean([float(r["ko_delta_late"]) for r in rows if "ko_delta_late" in r])} ko["fidelity"] = sorted({str(r["knockout"].get("fidelity")) for r in records}) - ko["_note"] = "descriptive only: margin deltas of the gold first token, no test, no mechanism claim" + ko["_note"] = "descriptive only: margin deltas of the model's own first answer token, no test, no mechanism claim" out["attention_knockout"] = ko return out diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py new file mode 100644 index 00000000..3b307700 --- /dev/null +++ b/evalrx/eval_agent/probing/validation.py @@ -0,0 +1,668 @@ +"""MVP-4: issues frozen from a diagnosis, validated once on cases the diagnosis never saw. + +**Partition.** :func:`partition_bundle` fixes the data roles before the +controller sees any case. DISCOVERY is the EXPLORE partition the controller +works on; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case that +shares a source with DISCOVERY (a source is the media content: a question about +an image the diagnosis saw is not a new image). Repair CONFIRM is not part of +this protocol (repair is out of scope), so the bundle says so. + +**Issues.** :func:`freeze_issues` turns a triage report into issue versions +whose cohort, signal, direction, band and test can be applied to new cases: + +* ``route_signal``: a label-free check (H, N or U) fires more on FAIL than on + stratum-matched PASS cases by more than ``ROUTE_BAND`` (discovery: the whole + 95% interval of the difference above it); +* ``reading``: on a route's FAIL cases (its layer's filter applied) a step's + reading differs from the matched PASS controls in a direction, beyond the + reading's band (discovery: the whole 95% interval outside it). One issue per + route and step: the reading furthest outside its band, in band units; the + step's other readings outside their bands are listed, not tested. A step that + re-measures the check that defines the route (``DEFINITIONAL``) is not an + issue: the route was cut on it. + +No reading reads the label: the controller refuses a carded step whose target is +the gold answer (a FAIL output is not gold by definition, so a gold margin lower +on FAIL restates the label), and the validator refuses a report from another +rules version (it re-runs the steps as they are defined now). + +The judge's explanations are not issues: their predictions are checked on the +validation evidence and reported apart (mechanism claims, not counted). + +**Plan.** :func:`plan_validation` estimates, from DISCOVERY alone (before any +validation output is read), the validation cases each issue will have and the +cases it would need for its interval to clear the band at the discovery effect, +and the cost. + +**Validation.** :func:`validate` runs once, on the union of the frozen families +of the given arms: the route checks on the validation FAIL cases and their +matched PASS controls, then each reading issue's step on its route. The family +is written to ``frozen.json`` before anything runs. Every issue's interval is +taken at ``1 - ALPHA / K`` (Bonferroni over the K issues of the family), and +its verdict is ``supported`` (inside the predicted region), ``refuted`` +(outside it), ``inconclusive`` (neither) or ``unavailable`` (the step could not +run, or too few cases). + +**Phenomena.** Several readings can say one thing (an attention cut and a noised +image both measuring how much the media carries the answer). Two reading issues +of one route are one phenomenon when their per-case values on the validation +cases go together within the FAIL cases and within the controls (pooled +within-group Spearman, ``|rho| >= SAME_PHENOMENON_RHO``; a difference between +the two groups does not count, since every issue has one); phenomena are the +connected groups. The rule is frozen with the family. Each arm is credited with +its own issues, grouped into phenomena: a phenomenon is supported for an arm +when one of the arm's own issues in it is. The main metric is the number of +supported phenomena; the per-issue tally is kept beside it. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +from collections import Counter +from dataclasses import asdict, dataclass, field +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable + +from evalrx.eval_agent.probing.actions import PlanStep +from evalrx.eval_agent.probing.explanations import ( + CARDS, + MIN_N, + Metric, + label_bound, + outcome, + t_quantile, + verdict, + z_quantile, +) +from evalrx.eval_agent.probing.ledger import Ledger +from evalrx.eval_agent.probing.rules import ( + LAYERS, + RULES_VERSION, + Layer, + candidate_steps, + matched_controls, + route_fail_ids, +) +from evalrx.eval_agent.probing.sampler import matched_sample, rank +from evalrx.eval_agent.probing.triage import ( + ROUTE_STEPS, + difference_interval, + follow_up_values, + triage_cases, +) + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + +VALIDATION_VERSION = "mvp4-validate-2" +ALPHA = 0.05 +#: A route signal is a difference of shares of cases: the band the CARDS use for shares. +ROUTE_BAND = 0.1 +ROUTE_CHECKS = {"H_label_free": "H", "N": "N", "U": "U"} +#: Steps that re-measure the check a route is cut on: their difference on that route is the cut. +DEFINITIONAL = {"self_consistency_n10": ("U", "S")} +#: Two reading issues of one route are one phenomenon at this pooled within-group |Spearman rho|. +SAME_PHENOMENON_RHO = 0.5 +#: Paired cases a group needs before it enters that correlation. +MIN_PAIRED = 5 +VERDICT_ORDER = ("supported", "refuted", "inconclusive", "unavailable") + + +# -- partition -------------------------------------------------------------------------------------- + + +def source_key(case: Any) -> str: + """The case's source: a hash of its media content (two cases on the same image share it), + or the case itself when it has no media.""" + inputs = getattr(case, "inputs", None) + h = hashlib.sha1() + found = False + for name in ("image", "audio", "video"): + media = getattr(inputs, name, None) + if media is None: + continue + found = True + if isinstance(media, (str, os.PathLike)) and Path(media).is_file(): + h.update(Path(media).read_bytes()) + elif hasattr(media, "tobytes"): + h.update(media.tobytes()) + else: + h.update(str(media).encode()) + return f"media:{h.hexdigest()[:16]}" if found else f"case:{getattr(case, 'id', '')}" + + +@dataclass +class PartitionBundle: + """The data roles of one protocol, fixed before the controller sees a case.""" + + diagnostic_val_source: str # "internal" (from the main manifest) | "external" + generalisation_unit: str # what a validated issue generalises to + discovery_ids: list[str] + validation_ids: list[str] + excluded: dict[str, int] # validation candidates left out, by reason + n_sources: dict[str, int] + rule: str + seed: int + confirm_split: float + manifest: dict[str, Any] = field(default_factory=dict) + roles: dict[str, Any] = field(default_factory=lambda: { + "controller": "DISCOVERY", "judge": "DISCOVERY (route summaries only)", + "validator": "DIAGNOSTIC_VALIDATION", "repair_confirm": None}) + + def to_dict(self) -> dict[str, Any]: + out = asdict(self) + out["sha1"] = hashlib.sha1(json.dumps({k: v for k, v in out.items() if k != "sha1"}, sort_keys=True, + default=str).encode()).hexdigest()[:16] + return out + + +def partition_bundle(discovery: "CaseBatch", confirm: "CaseBatch | None", *, seed: int, confirm_split: float, + manifest: "str | Path | None" = None) -> "tuple[PartitionBundle, CaseBatch]": + """DIAGNOSTIC_VALIDATION = CONFIRM minus the cases sharing a source with DISCOVERY.""" + from evalrx.core.case import CaseBatch + + seen = {source_key(c) for c in discovery} + kept, shared = [], 0 + for c in confirm or []: + if source_key(c) in seen: + shared += 1 + else: + kept.append(c) + info: dict[str, Any] = {} + if manifest is not None and Path(manifest).is_file(): + info = {"path": str(manifest), "sha1": hashlib.sha1(Path(manifest).read_bytes()).hexdigest()[:16]} + bundle = PartitionBundle( + diagnostic_val_source="internal", generalisation_unit="new media (no source shared with DISCOVERY)", + discovery_ids=[str(c.id) for c in discovery], validation_ids=[str(c.id) for c in kept], + excluded={"shares_a_source_with_discovery": shared}, + n_sources={"discovery": len(seen), "validation": len({source_key(c) for c in kept})}, + rule=("DISCOVERY = EXPLORE; DIAGNOSTIC_VALIDATION = CONFIRM minus every case whose media content " + "also appears in DISCOVERY; repair CONFIRM: none (repair is out of scope)"), + seed=int(seed), confirm_split=float(confirm_split), manifest=info) + return bundle, CaseBatch(kept) + + +# -- issues -------------------------------------------------------------------------------------------- + + +@dataclass +class IssueRecord: + """One frozen issue version: what is claimed, on which cases, and how it is tested.""" + + kind: str # "route_signal" | "reading" + route: str + direction: str # "up" | "down" + band: float + metric_kind: str # "rate" | "mean" + claim: str + check: str = "" # route_signal: the summary tag (H_label_free, N, U) + step: str = "" # reading: the step key + reading: str = "" # reading: the field + rule_id: "str | None" = None # the layer whose case filter narrows the route's FAIL cases + secondary: list[str] = field(default_factory=list) + discovery: dict[str, Any] = field(default_factory=dict) + spread: "float | None" = None # a mean reading's within-group spread in DISCOVERY (for the plan) + + @property + def issue_id(self) -> str: + key = {"version": VALIDATION_VERSION, "kind": self.kind, "route": self.route, "direction": self.direction, + "band": self.band, "check": self.check, "step": self.step, "reading": self.reading, + "rule_id": self.rule_id} + return hashlib.sha1(json.dumps(key, sort_keys=True).encode()).hexdigest()[:12] + + def to_dict(self) -> dict[str, Any]: + return {"issue_id": self.issue_id, **asdict(self)} + + +def _layer_for(route: str, key: str, layers: "tuple[Layer, ...]") -> "Layer | None": + for x in layers: + if x.route == route and (key in x.served_by or key in {c.name for c in x.candidates}): + return x + return None + + +def _margin(direction: str, ci: list[float], band: float) -> float: + """How far the interval lies outside the band in the claimed direction, in band units.""" + return ((ci[0] - band) if direction == "up" else (-ci[1] - band)) / band + + +def _spread_from(o: dict[str, Any]) -> "float | None": + """A mean reading's pooled spread, recovered from its Welch interval (approximate df).""" + nf, nc = o["n"] + if nf < MIN_N or nc < MIN_N or "ci95" not in o: + return None + se = (o["ci95"][1] - o["ci95"][0]) / 2 / t_quantile(0.95, nf + nc - 2) + return se / math.sqrt(1 / nf + 1 / nc) + + +def freeze_issues(report: dict[str, Any], layers: "tuple[Layer, ...]" = LAYERS) -> list[IssueRecord]: + """The issue versions a triage report supports on DISCOVERY (see the module docstring).""" + issues: list[IssueRecord] = [] + summary = report.get("summary") or {} + for tag, route in ROUTE_CHECKS.items(): + row = summary.get(tag) or {} + ci = row.get("signal_ci95") + if ci is None or ci[0] <= ROUTE_BAND: + continue + f, p = row["fail"], row["pass"] + issues.append(IssueRecord( + kind="route_signal", route=route, direction="up", band=ROUTE_BAND, metric_kind="rate", check=tag, + claim=(f"the {route} check fires more often on FAIL cases than on stratum-matched PASS cases, by more " + f"than {ROUTE_BAND}"), + discovery={"fail": f"{f['n_fired']}/{f['n_tested']}", "pass": f"{p['n_fired']}/{p['n_tested']}", + "rates": [f["rate"], p["rate"]], "n": [f["n_tested"], p["n_tested"]], + "diff": round((f["rate"] or 0.0) - (p["rate"] or 0.0), 4), "ci95": ci})) + for route, by_key in sorted((report.get("outcomes") or {}).items()): + for key, by_field in sorted(by_key.items()): + if route in DEFINITIONAL.get(key, ()) or key not in CARDS: + continue + bands = {m.field: m for m in CARDS[key]} + outside = [(f, o) for f, o in sorted(by_field.items()) + if f in bands and o.get("observed") in ("up", "down")] + if not outside: + continue + f, o = max(outside, key=lambda fo: _margin(fo[1]["observed"], fo[1]["ci95"], bands[fo[0]].band)) + metric, layer = bands[f], _layer_for(route, key, layers) + issues.append(IssueRecord( + kind="reading", route=route, direction=o["observed"], band=metric.band, metric_kind=metric.kind, + step=key, reading=f, + rule_id=layer.rule_id if layer is not None and layer.case_filter is not None else None, + claim=(f"on route {route}'s FAIL cases, {key}.{f} ({metric.meaning}) is " + f"{'higher' if o['observed'] == 'up' else 'lower'} than on stratum-matched PASS controls " + f"by more than {metric.band}"), + secondary=[f"{f2}: {o2['observed']}" for f2, o2 in outside if f2 != f], + discovery={k: o[k] for k in ("n", "fail_mean", "control_mean", "diff", "ci95") if k in o}, + spread=_spread_from(o) if metric.kind == "mean" else None)) + return issues + + +# -- plan ----------------------------------------------------------------------------------------------- + + +def _cases_needed(issue: IssueRecord, level: float) -> float: + """Fewest cases a side for the interval at *level* around the discovery difference to clear the + band in the claimed direction; ``inf`` when the discovery difference does not clear it.""" + d = abs(float(issue.discovery.get("diff") or 0.0)) + if d <= issue.band: + return math.inf + room = d - issue.band + if issue.metric_kind == "rate": + if issue.kind == "route_signal": + pf, pc = issue.discovery["rates"] + else: + pf, pc = issue.discovery.get("fail_mean", 0.5), issue.discovery.get("control_mean", 0.5) + var = (pf or 0.0) * (1 - (pf or 0.0)) + (pc or 0.0) * (1 - (pc or 0.0)) + if var <= 0: + return float(MIN_N) + return float(max(MIN_N, math.ceil(var * (z_quantile(level) / room) ** 2))) + s = issue.spread + if s is None: + return math.inf + if s == 0: + return float(MIN_N) + n = MIN_N + while t_quantile(level, 2 * n - 2) * s * math.sqrt(2 / n) >= room: + n += 1 if n < 64 else n // 8 + if n > 100000: + return math.inf + return float(n) + + +def _per_case_cost(report: dict[str, Any], key: str) -> "float | None": + rows = [(float((e.get("cost") or {}).get("wall_sec") or 0.0), int(e.get("n_cases") or 0)) + for e in report.get("executions") or [] if e.get("key") == key and (e.get("cost") or {}).get("calls")] + n = sum(k for _, k in rows) + return sum(s for s, _ in rows) / n if n else None + + +def plan_validation(issues: list[IssueRecord], reports: list[dict[str, Any]], *, n_validation: int, + discovery_fail_rate: float, level: float) -> list[dict[str, Any]]: + """Per issue, from DISCOVERY only: the validation cases it should have, the cases it needs, and the + estimated seconds; nothing here reads a validation output.""" + expected_fail = n_validation * discovery_fail_rate + rows = [] + for issue in issues: + shares = [] + for r in reports: + routes = (r.get("revisions") or [{}])[-1].get("fail_routes") or {} + n_fail = len((r.get("sample") or {}).get("fail_ids") or []) + if n_fail: + shares.append(routes.get(issue.route, 0) / n_fail if issue.kind == "reading" else 1.0) + share = max(shares) if shares else 0.0 + n_expected = int(round(expected_fail * share)) + needed = _cases_needed(issue, level) + costs = [c for r in reports if (c := _per_case_cost(r, issue.step)) is not None] if issue.step else [] + rows.append({"issue_id": issue.issue_id, "n_expected": n_expected, + "n_needed": None if math.isinf(needed) else int(needed), + "expected_decidable": n_expected >= needed, + "est_sec": round(2 * n_expected * max(costs), 1) if costs else None}) + return rows + + +# -- validation --------------------------------------------------------------------------------------------- + + +def _verdict(direction: str, ci: "list[float] | None", band: float) -> str: + return {"hit": "supported", "miss": "refuted", "undetermined": "inconclusive"}[verdict(direction, ci, band)] + + +def _route_signal(records: list[dict[str, Any]], tag: str, level: float) -> dict[str, Any]: + state = {"H_label_free": lambda r: r["H"]["state_label_free"], "N": lambda r: r["N"]["state"], + "U": lambda r: r["U"]["state"]}[tag] + counts = {} + for label in ("fail", "pass"): + tested = [r for r in records if r["label"] == label and state(r) in ("fired", "clear")] + counts[label] = (sum(1 for r in tested if state(r) == "fired"), len(tested)) + (kf, nf), (kp, np_) = counts["fail"], counts["pass"] + out: dict[str, Any] = {"fail": f"{kf}/{nf}", "pass": f"{kp}/{np_}", "n": [nf, np_]} + if nf < MIN_N or np_ < MIN_N: + return {**out, "verdict": "unavailable", "reason": f"fewer than {MIN_N} tested cases a side"} + ci = difference_interval(kf, nf, kp, np_, z=z_quantile(level)) + ci95 = difference_interval(kf, nf, kp, np_) + return {**out, "diff": round(kf / nf - kp / np_, 4), "ci": ci, "ci95": ci95, + "verdict": _verdict("up", ci, ROUTE_BAND)} + + +# -- phenomena ------------------------------------------------------------------------------------------ + + +def _ranks(xs: list[float]) -> list[float]: + """Ranks with ties averaged.""" + order = sorted(range(len(xs)), key=lambda i: xs[i]) + out = [0.0] * len(xs) + i = 0 + while i < len(order): + j = i + while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]: + j += 1 + for k in range(i, j + 1): + out[order[k]] = (i + j) / 2 + i = j + 1 + return out + + +def within_group_rho(a: dict[str, float], b: dict[str, float], groups: list[list[str]]) -> "float | None": + """Spearman correlation of two per-case readings inside each group of cases, pooled: ranks are + taken and centred within a group, so a shift between the groups does not count. ``None`` when no + group has ``MIN_PAIRED`` cases with both readings, or a reading is constant within every group.""" + sxy = sxx = syy = 0.0 + for ids in groups: + both = [c for c in ids if c in a and c in b] + if len(both) < MIN_PAIRED: + continue + ra, rb = _ranks([a[c] for c in both]), _ranks([b[c] for c in both]) + ma, mb = sum(ra) / len(ra), sum(rb) / len(rb) + sxy += sum((x - ma) * (y - mb) for x, y in zip(ra, rb)) + sxx += sum((x - ma) ** 2 for x in ra) + syy += sum((y - mb) ** 2 for y in rb) + if sxx <= 0 or syy <= 0: + return None + return sxy / math.sqrt(sxx * syy) + + +def group_phenomena(family: list[IssueRecord], results: dict[str, dict[str, Any]], + per_case: dict[str, tuple[dict[str, float], list[str], list[str]]] + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Connected groups of a route's reading issues whose validation values go together (see the module + docstring); a route signal, or a reading without validation values, is a phenomenon of its own. + Returns the phenomena and every within-route correlation computed (joined or not).""" + parent = {i.issue_id: i.issue_id for i in family} + + def root(x: str) -> str: + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + links = [] + readings = [i for i in family if i.kind == "reading" and i.issue_id in per_case] + for n, a in enumerate(readings): + for b in readings[n + 1:]: + if a.route != b.route: + continue + va, fail_ids, controls = per_case[a.issue_id] + rho = within_group_rho(va, per_case[b.issue_id][0], [fail_ids, controls]) + if rho is None: + continue + links.append({"issues": [a.issue_id, b.issue_id], "rho": round(rho, 3)}) + if abs(rho) >= SAME_PHENOMENON_RHO: + parent[root(b.issue_id)] = root(a.issue_id) + groups: dict[str, list[IssueRecord]] = {} + for i in family: + groups.setdefault(root(i.issue_id), []).append(i) + out = [] + for n, members in enumerate(groups.values(), 1): + ids = {i.issue_id for i in members} + out.append({"id": f"P{n}", "route": members[0].route, "issues": sorted(ids), + "label": "; ".join(i.check or f"{i.step}.{i.reading}" for i in members), + "verdict": _best(results[i.issue_id]["verdict"] for i in members), + "links": [lk for lk in links if set(lk["issues"]) <= ids]}) + return out, links + + +def credit_arms(families: dict[str, list[IssueRecord]], results: dict[str, dict[str, Any]], + phenomenon_of: dict[str, str], reports: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: + """Each arm's own issues, grouped into phenomena: a phenomenon takes the best verdict among the + arm's own issues in it (another arm's issue in the same phenomenon lends it nothing).""" + credit = {} + for arm, issues in families.items(): + tally = Counter(results[i.issue_id]["verdict"] for i in issues) + own: dict[str, list[str]] = {} + for i in issues: + own.setdefault(phenomenon_of[i.issue_id], []).append(results[i.issue_id]["verdict"]) + by_phenomenon = Counter(_best(v) for v in own.values()) + credit[arm] = {"n_phenomena": len(own), **{f"phenomena_{v}": by_phenomenon.get(v, 0) for v in VERDICT_ORDER}, + "n_issues": len(issues), **{v: tally.get(v, 0) for v in VERDICT_ORDER}, + "charged_sec": ((reports.get(arm) or {}).get("cost") or {}).get("charged", {}).get("wall_sec")} + return credit + + +def _best(verdicts: Any) -> str: + """A group's verdict: supported if any member is, else refuted if any is, and so on.""" + found = set(verdicts) + return next((v for v in VERDICT_ORDER if v in found), "unavailable") + + +def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", families: dict[str, list[IssueRecord]], + reports: dict[str, dict[str, Any]], *, out_dir: "str | Path", model_identity: dict[str, Any], + bundle: "PartitionBundle | None" = None, seed: int = 0, stratum: str = "gold", + host_assumed_finish: bool = False, answer_contract: bool = False, n_needs_counterfactual: bool = False, + task_kind: "str | None" = None, answer_fn: Any = None, + analyzer_kwargs: "dict[str, dict[str, Any]] | None" = None, price_fn: Any = None, + per_call_generation: bool = True, chunk: int = 8, budget_sec: float = 0.0, + battery: "tuple[PlanStep, ...] | None" = None, layers: "tuple[Layer, ...]" = LAYERS, + run_logger: Any = None, progress: "Callable[[str], None] | None" = print) -> dict[str, Any]: + """Validate the union of the arms' frozen *families* once on *validation*; credit every arm.""" + from evalrx.eval_agent.probing.controller import BATTERY, POLICY_VERSION, _Run, analyzer_extras + + battery = battery or BATTERY + stale = sorted(arm for arm, r in reports.items() if r.get("rules_version") != RULES_VERSION) + if stale: + raise ValueError(f"reports {stale} come from another rules version than {RULES_VERSION}: the " + "validator re-runs the steps as they are defined now") + if bound := label_bound((*battery, *candidate_steps(layers)), analyzer_kwargs): + raise ValueError(f"steps {bound} read the gold answer (target='gold'); use target='prediction'") + say = progress or (lambda _msg: None) + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + union: dict[str, IssueRecord] = {} + for issues in families.values(): + for issue in issues: + union.setdefault(issue.issue_id, issue) + family = sorted(union.values(), key=lambda i: (i.kind != "route_signal", i.route, i.step, i.reading)) + k = max(1, len(family)) + level = 1 - ALPHA / k + n_disc = len(discovery) + fail_rate = sum(1 for c in discovery if getattr(getattr(c, "label", None), "value", None) == "fail") / max(1, n_disc) + plan = plan_validation(family, list(reports.values()), n_validation=len(validation), + discovery_fail_rate=fail_rate, level=level) + frozen = {"version": VALIDATION_VERSION, "alpha": ALPHA, "k": k, "level": level, + "family": [i.to_dict() for i in family], "plan": plan, + "arms": {arm: [i.issue_id for i in issues] for arm, issues in families.items()}, + "phenomenon_rule": {"statistic": "pooled within-group Spearman rho of the per-case values on the " + "validation FAIL cases and on their controls, same route", + "threshold": SAME_PHENOMENON_RHO, "min_paired_per_group": MIN_PAIRED}, + "partition": bundle.to_dict() if bundle is not None else None} + frozen["sha1"] = hashlib.sha1(json.dumps(frozen, sort_keys=True, default=str).encode()).hexdigest()[:16] + (out / "frozen.json").write_text(json.dumps(frozen, indent=2, default=str) + "\n", encoding="utf-8") + say(f"[validate] froze {k} issue(s) from {len(families)} arm(s) (sha1 {frozen['sha1']}); level {level:.4f}") + + # -- from here on the validation partition is read -------------------------------------------------- + extras = analyzer_extras(analyzer_kwargs, discovery, seed, donor_pool=validation) + run = _Run(model, validation, Ledger(out), context={"policy": POLICY_VERSION, "model": model_identity, + "role": "validation"}, + extras=extras, task_kind=task_kind, budget_sec=budget_sec, price_fn=price_fn, + run_logger=run_logger, say=say, per_call_generation=per_call_generation, chunk=chunk) + n_fail = sum(1 for c in validation if getattr(getattr(c, "label", None), "value", None) == "fail") + sample, draw = matched_sample(validation, n_fail, seed=seed, stratum=stratum) + for step in battery: + if step.name in ROUTE_STEPS: + run.run_step(step, list(draw.case_ids), kind="validation", revision=0) + records = triage_cases(sample, run.evidence, host_assumed_finish=host_assumed_finish, + answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, + answer_fn=answer_fn) + rank_of = partial(rank, seed) + by_rule = {x.rule_id: x for x in layers} + steps = {s.name: s for s in (*battery, *candidate_steps(layers))} + results: dict[str, dict[str, Any]] = {} + measured: dict[tuple[str, str], tuple[list[str], list[str]]] = {} + per_case: dict[str, tuple[dict[str, float], list[str], list[str]]] = {} + for issue in family: + if issue.kind == "route_signal": + results[issue.issue_id] = _route_signal(records, issue.check, level) + continue + layer = by_rule.get(issue.rule_id) if issue.rule_id else None + fail_ids = route_fail_ids(records, issue.route, layer.case_filter if layer is not None else None) + controls = matched_controls(records, fail_ids, rank_of)[0] + row: dict[str, Any] = {"n_route_fail": len(fail_ids), "n_controls": len(controls)} + step = steps.get(issue.step) + if step is None: + results[issue.issue_id] = {**row, "verdict": "unavailable", "reason": f"no step {issue.step!r}"} + continue + if len(fail_ids) < MIN_N or len(controls) < MIN_N: + results[issue.issue_id] = {**row, "verdict": "unavailable", + "reason": f"fewer than {MIN_N} route FAIL cases or controls"} + continue + record = run.run_step(step, [*fail_ids, *controls], kind="validation", revision=0, route=issue.route) + ev = run.evidence.get(step.name) + if ev is None or not ev.chunks or ev.refused() is not None: + why = ("refused by its own fidelity check" if ev is not None and ev.refused() is not None else + (record or {}).get("reason") or (record or {}).get("error") or "not run") + results[issue.issue_id] = {**row, "verdict": "unavailable", "reason": str(why)} + continue + measured[(issue.route, step.name)] = (fail_ids, controls) + metric = Metric(issue.reading, "", issue.band, issue.metric_kind) + values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn) for cid in (*fail_ids, *controls)} + o = outcome(values, fail_ids, controls, metric, level=level) + o95 = outcome(values, fail_ids, controls, metric) + per_case[issue.issue_id] = ({cid: float(v["values"][issue.reading]) for cid, v in values.items() + if v.get("state") == "measured" and issue.reading in v["values"]}, + fail_ids, controls) + if "ci95" not in o: + results[issue.issue_id] = {**row, **o, "verdict": "unavailable", + "reason": f"fewer than {MIN_N} measured cases a side"} + continue + results[issue.issue_id] = {**row, "n": o["n"], "fail_mean": o.get("fail_mean"), + "control_mean": o.get("control_mean"), "diff": o["diff"], "ci": o["ci95"], + "ci95": o95.get("ci95"), "verdict": _verdict(issue.direction, o["ci95"], issue.band)} + say(f"[validate] verdicts: {dict(Counter(r['verdict'] for r in results.values()))}") + + phenomena, links = group_phenomena(family, results, per_case) + phenomenon_of = {i: ph["id"] for ph in phenomena for i in ph["issues"]} + say(f"[validate] {len(phenomena)} phenomena: {dict(Counter(ph['verdict'] for ph in phenomena))}") + credit = credit_arms(families, results, phenomenon_of, reports) + report = { + "version": VALIDATION_VERSION, "frozen_sha1": frozen["sha1"], "alpha": ALPHA, "k": k, "level": level, + "partition": frozen["partition"], + "sample": draw.to_dict(), + "issues": [{**i.to_dict(), "plan": next(p for p in plan if p["issue_id"] == i.issue_id), + "validation": results[i.issue_id], "phenomenon": phenomenon_of[i.issue_id]} for i in family], + "phenomena": phenomena, + "phenomenon_links": links, + "arms": credit, + "explanations": _check_explanations(reports, run, measured, answer_fn), + "cost": {"charged_sec": round(run.charged("wall_sec"), 3), "executions": len(run.executions)}, + "_note": ("each issue's interval is at 1 - alpha/K (Bonferroni over the K issues of the family); ci95 " + "is the unadjusted interval, for reference. Verdicts: supported = inside the claimed region, " + "refuted = outside it, inconclusive = neither, unavailable = the step or the cases were missing. " + "A phenomenon is supported for an arm when one of the arm's own issues in it is"), + } + (out / "validation_report.json").write_text(json.dumps(report, indent=2, default=str) + "\n", encoding="utf-8") + (out / "validation_report.md").write_text(markdown(report), encoding="utf-8") + return report + + +def _check_explanations(reports: dict[str, dict[str, Any]], run: Any, measured: dict[tuple[str, str], Any], + answer_fn: Any) -> dict[str, Any]: + """The predictions of each arm's explanations live at its stop, checked on the validation evidence + where it exists (mechanism claims: reported, not counted).""" + out: dict[str, Any] = {} + for arm, r in reports.items(): + sets = ((r.get("explanations") or {}).get("sets")) or [] + if not sets or not sets[-1]["hypotheses"]: + continue + last = sets[-1] + rows = [] + for h in last["hypotheses"]: + if last["final"][h["id"]]["state"] != "live": + continue + preds = [] + for step, by in sorted(h["predictions"].items()): + for f, d in sorted(by.items()): + if (h["route"], step) not in measured: + preds.append({"step": step, "reading": f, "predicted": d, "verdict": "not measured"}) + continue + fail_ids, controls = measured[(h["route"], step)] + metric = next(m for m in CARDS[step] if m.field == f) + ev = run.evidence[step] + values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn) for cid in (*fail_ids, *controls)} + o = outcome(values, fail_ids, controls, metric) + preds.append({"step": step, "reading": f, "predicted": d, "observed": o.get("observed"), + "verdict": verdict(d, o.get("ci95"), metric.band)}) + rows.append({"id": h["id"], "claim": h["claim"], "predictions": preds, + "state": ("contradicted" if any(p["verdict"] == "miss" for p in preds) else + "consistent" if any(p["verdict"] == "hit" for p in preds) else "untested")}) + out[arm] = rows + return out + + +def markdown(report: dict[str, Any]) -> str: + part = report.get("partition") or {} + lines = [f"# Diagnostic validation ({report['version']})", "", + f"Frozen family sha1 `{report['frozen_sha1']}`: {report['k']} issue(s), intervals at " + f"{report['level']:.4f} (Bonferroni, alpha {report['alpha']}).", + f"Partition: {part.get('rule', '-')}; {len(part.get('validation_ids') or [])} validation cases " + f"({(part.get('excluded') or {})}); sample {len(report['sample']['fail_ids'])} FAIL + " + f"{len(report['sample']['pass_ids'])} PASS. Validation cost {report['cost']['charged_sec']} s.", "", + "## Issues", "", "| issue | phenomenon | claim | discovery | plan: expected / needed | validation " + "| verdict |", "|---|---|---|---|---|---|---|"] + for i in report["issues"]: + d, v, p = i["discovery"], i["validation"], i["plan"] + disc = f"diff {d.get('diff')} CI {d.get('ci95')} n {d.get('n')}" + val = (f"diff {v.get('diff')} CI {v.get('ci')} n {v.get('n')}" if "diff" in v else v.get("reason", "-")) + lines.append(f"| {i['issue_id']} | {i['phenomenon']} | {i['claim']} | {disc} | {p['n_expected']} / " + f"{p['n_needed']} | {val} | **{v['verdict']}** |") + lines += ["", "## Phenomena", "", "| phenomenon | route | issues | within-group rho | verdict |", + "|---|---|---|---|---|"] + for ph in report["phenomena"]: + rho = ", ".join(str(lk["rho"]) for lk in ph["links"]) or "-" + lines.append(f"| {ph['id']} | {ph['route']} | {ph['label']} | {rho} | **{ph['verdict']}** |") + lines += ["", "## Arms", "", "| arm | phenomena | supported | refuted | inconclusive | unavailable " + "| issues | supported | charged s |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|"] + for arm, c in report["arms"].items(): + lines.append(f"| {arm} | {c['n_phenomena']} | {c['phenomena_supported']} | {c['phenomena_refuted']} " + f"| {c['phenomena_inconclusive']} | {c['phenomena_unavailable']} | {c['n_issues']} " + f"| {c['supported']} | {c['charged_sec']} |") + if report.get("explanations"): + lines += ["", "## Explanations (mechanism claims: reported, not counted)", ""] + for arm, rows in report["explanations"].items(): + for h in rows: + checked = [f"{p['step']}.{p['reading']} {p['predicted']} -> {p['verdict']}" for p in h["predictions"] + if p["verdict"] != "not measured"] + lines.append(f"- {arm} {h['id']} [{h['state']}]: {h['claim']} ({'; '.join(checked) or 'unmeasured'})") + lines += ["", f"_{report['_note']}._", ""] + return "\n".join(lines) diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index 1e49799a..d55d5251 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -499,7 +499,7 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): assert rec["routes"] == ["N", "U"] and not rec["stable"] assert rec["S_readings"]["threshold"]["state"] == "measured" assert rec["S_readings"]["patchscope"]["state"] == "measured" - assert rec["S_readings"]["patchscope"]["target"] == "gold" + assert rec["S_readings"]["patchscope"]["target"] == "prediction" assert report["summary"]["N_donors"]["fail"]["counterfactual"] == 2 assert report["summary"]["S"] == {"fail": 0, "stable_pass": 0} diff --git a/tests/test_eval_agent/test_probing_validation.py b/tests/test_eval_agent/test_probing_validation.py new file mode 100644 index 00000000..d855d37d --- /dev/null +++ b/tests/test_eval_agent/test_probing_validation.py @@ -0,0 +1,201 @@ +"""MVP-4: issues frozen from a diagnosis and validated once on cases it never saw. + +* the partition keeps every validation case off the media DISCOVERY saw; +* freezing keeps route signals and readings whose discovery interval clears the + band, one issue per route and step (its reading furthest outside the band), + and drops a step that re-measures the check its route is cut on; +* the family is written before the validation partition is read, every issue is + tested at 1 - alpha/K, and each arm is credited with its own issues' verdicts: + an effect that holds on new cases is supported, one that held only on the + discovery cases is refuted; +* no carded reading reads the label (a step targeting the gold answer is + refused), and the validator refuses a report from another rules version; +* readings whose per-case values go together within FAIL and within the + controls are one phenomenon (a FAIL-vs-control shift alone does not join + them), and an arm's phenomenon takes the verdicts of its own issues only. +""" + +from __future__ import annotations + +import json + +import pytest + +from evalrx.eval_agent.probing import LAYERS, explore_confirm_split, run_triage +from evalrx.eval_agent.probing.controller import BATTERY +from evalrx.eval_agent.probing.explanations import CARDS, Metric, label_bound +from evalrx.eval_agent.probing.rules import Layer, candidate_steps +from evalrx.eval_agent.probing.validation import ( + ALPHA, + IssueRecord, + credit_arms, + freeze_issues, + group_phenomena, + partition_bundle, + source_key, + validate, + within_group_rho, +) +from tests.test_eval_agent.test_probing_alternatives import FIRST, _Flipper +from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _yes_no + +SEED = 7 + + +def _split(n_images=96): + cases, table = _pope_like(n_images) + explore, confirm = explore_confirm_split(cases, 0.5, SEED) + return cases, table, explore, confirm + + +def test_the_partition_keeps_every_validation_case_off_the_media_discovery_saw(): + cases, _, explore, confirm = _split() + bundle, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) + seen = {source_key(c) for c in explore} + assert validation and not {source_key(c) for c in validation} & seen + assert set(bundle.validation_ids) <= {str(c.id) for c in confirm} + assert len(bundle.validation_ids) + bundle.excluded["shares_a_source_with_discovery"] == len(confirm) + assert bundle.excluded["shares_a_source_with_discovery"] > 0 # a POPE image has a yes and a no question + assert bundle.roles["repair_confirm"] is None and bundle.to_dict()["sha1"] == bundle.to_dict()["sha1"] + + +def _outcome(observed, ci, n=(8, 8), diff=None): + return {"n": list(n), "observed": observed, "ci95": ci, "diff": diff if diff is not None else sum(ci) / 2, + "fail_mean": 0.5, "control_mean": 0.2} + + +def test_freezing_keeps_what_clears_the_band_one_issue_per_route_and_step(): + report = { + "summary": {"U": {"signal_ci95": [0.2, 0.5], "fail": {"n_fired": 5, "n_tested": 10, "rate": 0.5}, + "pass": {"n_fired": 1, "n_tested": 10, "rate": 0.1}}, + "N": {"signal_ci95": [0.05, 0.3], "fail": {"n_fired": 3, "n_tested": 10, "rate": 0.3}, + "pass": {"n_fired": 1, "n_tested": 10, "rate": 0.1}}}, + "outcomes": { + "S": {"gradcam": {"gc_entropy": _outcome("down", [-0.4, -0.2]), + "gc_top5_share": _outcome("up", [0.1, 0.4]), + "gc_media_grad_share": _outcome("undetermined", [-0.1, 0.2])}, + "self_consistency_n10": {"consistency": _outcome("up", [0.2, 0.4])}}, + "U": {"logprob_entropy": {"mean_top_entropy": _outcome("up", [0.1, 0.25])}}, + "X": {"media_drop": {"grounded_in_image": _outcome("up", [0.3, 0.9])}}, + "N": {"patchscope": {"ps_peak_prob": _outcome("undetermined", [-0.2, 0.1])}}, + }, + } + issues = {(i.kind, i.route, i.check or i.step): i for i in freeze_issues(report)} + assert set(issues) == {("route_signal", "U", "U"), ("reading", "S", "gradcam"), + ("reading", "U", "logprob_entropy"), ("reading", "X", "media_drop")} + gc = issues[("reading", "S", "gradcam")] + # the reading furthest outside its band (0.15 past 0.05) is tested, the other is listed + assert (gc.reading, gc.direction, gc.secondary) == ("gc_entropy", "down", ["gc_top5_share: up"]) + assert gc.spread is not None and gc.rule_id is None + assert issues[("reading", "X", "media_drop")].rule_id == "X1" # X1 narrows its cases + assert len({i.issue_id for i in issues.values()}) == 4 + + +@pytest.fixture +def wrapper_on_s(monkeypatch): + monkeypatch.setitem(CARDS, FIRST.name, (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) + at = next(i for i, x in enumerate(LAYERS) if x.rule_id == "Sb") + return (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (FIRST,)), *LAYERS[at:]) + + +class _DiscoveryOnly(_Flipper): + """Wrong cases come out right inside the wrapper only on the discovery cases: an effect that + does not hold on new cases.""" + + def __init__(self, table, cases, only): + super().__init__(table, [c for c in cases if str(c.id) in only]) + + +def _diagnose_and_validate(tmp_path, model, layers, explore, validation, bundle, name): + report = run_triage(model, explore, **_kw(tmp_path / "probing", max_fail=8, min_route_fail=1, layers=layers)) + issues = freeze_issues(report, layers) + out = validate(model, explore, validation, {name: issues}, {name: report}, out_dir=tmp_path / "validation", + model_identity={"spec": "table"}, bundle=bundle, seed=0, host_assumed_finish=True, + n_needs_counterfactual=True, task_kind="yes_no", answer_fn=_yes_no, layers=layers, + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, progress=None) + return report, issues, out + + +def test_an_effect_that_holds_on_new_cases_is_supported_and_frozen_before_validation(tmp_path, wrapper_on_s): + cases, table, explore, confirm = _split() + bundle, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) + report, issues, out = _diagnose_and_validate(tmp_path, _Flipper(table, cases), wrapper_on_s, explore, + validation, bundle, "rules") + (wrap,) = [i for i in issues if i.step == "wrap_a"] + assert (wrap.route, wrap.direction) == ("S", "up") + row = next(r for r in out["issues"] if r["issue_id"] == wrap.issue_id) + assert row["validation"]["verdict"] == "supported" + assert out["level"] == pytest.approx(1 - ALPHA / out["k"]) and out["arms"]["rules"]["supported"] >= 1 + frozen = json.loads((tmp_path / "validation" / "frozen.json").read_text()) + assert frozen["sha1"] == out["frozen_sha1"] and wrap.issue_id in frozen["arms"]["rules"] + # the diagnosis never touched a validation case; the validator wrote to its own directory + val_ids = set(bundle.validation_ids) + planned = [json.loads(line) for line in (tmp_path / "probing" / "selection_trace.jsonl").read_text().splitlines() + if '"planned"' in line] + ran_on = {cid for e in planned for cid in e["action"]["case_ids"]} + assert planned and ran_on and not val_ids & ran_on + assert not val_ids & set(report["sample"]["case_ids"]) + assert set(out["sample"]["case_ids"]) <= val_ids + assert (tmp_path / "validation" / "selection_trace.jsonl").is_file() + assert "## Arms" in (tmp_path / "validation" / "validation_report.md").read_text() + + +def test_an_effect_that_held_only_on_the_discovery_cases_is_refuted(tmp_path, wrapper_on_s): + cases, table, explore, confirm = _split() + bundle, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) + model = _DiscoveryOnly(table, cases, {str(c.id) for c in explore}) + _, issues, out = _diagnose_and_validate(tmp_path, model, wrapper_on_s, explore, validation, bundle, "rules") + (wrap,) = [i for i in issues if i.step == "wrap_a"] + row = next(r for r in out["issues"] if r["issue_id"] == wrap.issue_id) + assert row["validation"]["verdict"] == "refuted" and row["validation"]["diff"] == 0.0 + + +def test_no_carded_reading_reads_the_label_and_a_gold_target_is_refused(tmp_path): + assert not label_bound((*BATTERY, *candidate_steps(LAYERS))) + assert not any(m.field.startswith("fixed_") for ms in CARDS.values() for m in ms) + cases, table, explore, _ = _split(16) + with pytest.raises(ValueError, match="read the gold answer"): + run_triage(_Flipper(table, cases), explore, + **_kw(tmp_path, analyzer_kwargs={"attention_knockout": {"target": "gold"}})) + + +def test_the_validator_refuses_a_report_from_another_rules_version(tmp_path): + _, _, explore, confirm = _split(16) + _, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) + with pytest.raises(ValueError, match="another rules version"): + validate(None, explore, validation, {"old": []}, {"old": {"rules_version": "mvp2-rules-1"}}, + out_dir=tmp_path, model_identity={}, progress=None) + + +def _reading(route, step): + return IssueRecord(kind="reading", route=route, direction="up", band=0.1, metric_kind="mean", claim="-", + step=step, reading="r") + + +def test_readings_that_go_together_within_groups_are_one_phenomenon_and_a_shift_is_not(): + fail, ctrl = [f"f{i}" for i in range(6)], [f"c{i}" for i in range(6)] + base = dict(zip(fail + ctrl, [1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16])) + same = {c: 2 * v + 10 for c, v in base.items()} # the same order inside each group + order = [3, 6, 1, 5, 2, 4] # FAIL and controls far apart, order unrelated + shifted = {**dict(zip(fail, order)), **{c: 100 + v for c, v in zip(ctrl, order)}} + a, b, c, d = (_reading("S", "knockout"), _reading("S", "causal_trace"), _reading("S", "gradcam"), + _reading("U", "knockout")) + signal = IssueRecord(kind="route_signal", route="U", direction="up", band=0.1, metric_kind="rate", claim="-", + check="U") + per_case = {a.issue_id: (base, fail, ctrl), b.issue_id: (same, fail, ctrl), c.issue_id: (shifted, fail, ctrl), + d.issue_id: (base, fail, ctrl)} + assert within_group_rho(base, same, [fail, ctrl]) == pytest.approx(1.0) + assert within_group_rho(base, shifted, [fail, ctrl]) == pytest.approx(-3 / 35) + results = {signal.issue_id: {"verdict": "inconclusive"}, a.issue_id: {"verdict": "supported"}, + b.issue_id: {"verdict": "inconclusive"}, c.issue_id: {"verdict": "supported"}, + d.issue_id: {"verdict": "refuted"}} + phenomena, links = group_phenomena([signal, a, b, c, d], results, per_case) + assert len(links) == 3 # every pair on route S; d is alone on U + assert {frozenset(ph["issues"]): ph["verdict"] for ph in phenomena} == { + frozenset({signal.issue_id}): "inconclusive", frozenset({a.issue_id, b.issue_id}): "supported", + frozenset({c.issue_id}): "supported", frozenset({d.issue_id}): "refuted"} # d: same values, other route + of = {i: ph["id"] for ph in phenomena for i in ph["issues"]} + credit = credit_arms({"both": [a, b], "twin_only": [b]}, results, of, {}) + assert (credit["both"]["n_phenomena"], credit["both"]["phenomena_supported"], credit["both"]["n_issues"]) == (1, 1, 2) + # the twin's phenomenon is supported through the knockout, which this arm did not freeze + assert (credit["twin_only"]["phenomena_supported"], credit["twin_only"]["phenomena_inconclusive"]) == (0, 1) From b80b46d8620cbbf489ef90009555447cb33d47b6 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:04:23 -0700 Subject: [PATCH 11/26] triage validation on ChartQA at scale: explanations tested on new cases, a validation-only source, gradient passes that fit Six increments since MVP-4 (96c3158), developed on ChartQA with Qwen3.5-2B (runs triage12-17): - Fixed: triage_cases gave every record its gold answer as stratum whatever rule the sample was drawn with, so open-answer tasks had almost no matched controls (ChartQA: 5 for 30 U FAIL cases); it now takes the sampler's rule. Rules mvp4-rules-3. - Changed: the U re-sampling check fires only when another answer is sampled more often than the Stage-0 answer (a tie stays clear), not on any one of 5 samples differing. Rules mvp4-rules-4. - Changed: the main validation metric is each arm's supported phenomena at every grouping threshold of RHO_GRID (0.3-0.7), an arm ahead only where it has more at every threshold; one-sided tests at alpha/K on the claimed side; the live explanations are frozen with the family, each naming one or two primary predictions that the validator tests on new cases as one Bonferroni family (supported / refuted / undecided / untestable); a reading a route is cut on (DEFINITIONAL) is neither asked nor measured; a re-ask keeps the live explanations and adds competing ones (carry_over). Explanations mvp4-explain-5, validation mvp4-validate-4. - Changed: the judge is also offered the tools already run on a route (already_run, readings in view: a fit in the triage, tested on new cases, no D), the first ask needs no tool left to run, and a re-ask fires only for a route with tools it can be asked about; logprob_entropy on U is definitional. Explanations mvp4-explain-6, validation mvp4-validate-5. - Added: --triage-validation-source MANIFEST, cases used only for DIAGNOSTIC_VALIDATION, labelled by their own Stage 0 (/baseline_validation_source.json) and never seen by the controller or the judge; partition_bundle keeps them off DISCOVERY media and off pool ids and records where the validation cases came from; python -m evalrx.benchmark.tasks.chartqa freezes the human rows the pool left (rest of the test split, the val split). ChartQA validation grew from 293 cases (100 FAIL, N 7) to 1398 (450 FAIL, N 36): the first N decision (N.h1 supported). - Fixed: hf_local ran the whole model under autograd for CaptureSpec(with_grad=True), so a vision tower's attention over a large image was kept for backward (Qwen3.5-2B, a 918x1811 chart: 6400 patches, 75 GB, out of memory). The media encoders now run without a graph (media_encoders_without_grad; CaptureSpec(media_grad=True) opts out), readings unchanged, that chunk at 19 GB and 4x faster; gradcam and generic_attention skip a case whose graph still does not fit (skip_reasons: out_of_memory) instead of failing the chunk. Suite: 2826 passed, 16 skipped; ruff clean. --- CHANGELOG.md | 109 +++++++ docs/agentic_benchmark.md | 4 +- docs/analyzers.md | 9 +- evalrx/analyzers/attribution/generic_attn.py | 17 +- evalrx/analyzers/attribution/gradcam.py | 19 +- evalrx/benchmark/run.py | 6 + evalrx/benchmark/runner.py | 58 +++- evalrx/benchmark/tasks/chartqa.py | 110 +++++-- evalrx/core/model.py | 4 + evalrx/eval_agent/probing/compare.py | 5 +- evalrx/eval_agent/probing/controller.py | 61 ++-- evalrx/eval_agent/probing/explanations.py | 174 ++++++++-- evalrx/eval_agent/probing/rules.py | 2 +- evalrx/eval_agent/probing/triage.py | 22 +- evalrx/eval_agent/probing/validation.py | 297 +++++++++++++----- evalrx/models/backends/hf/_util.py | 59 ++++ evalrx/models/backends/hf/model.py | 10 +- .../test_intervention_analyzers.py | 30 ++ .../test_probing_alternatives.py | 7 +- tests/test_eval_agent/test_probing_mvp0.py | 40 ++- tests/test_eval_agent/test_probing_mvp3b.py | 168 ++++++++-- .../test_probing_validation.py | 81 ++++- tests/test_examples/test_benchmark_common.py | 46 +++ .../test_media_encoders_no_grad.py | 95 ++++++ tests/tiny_whitebox.py | 5 +- 25 files changed, 1218 insertions(+), 220 deletions(-) create mode 100644 tests/test_models/test_media_encoders_no_grad.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a633c0ec..8969ff50 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,115 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed — a gradient pass keeps no graph through the media encoders; a case that does not fit is skipped + +`hf_local` ran the whole model under autograd when `CaptureSpec(with_grad=True)` +was asked, so a vision tower's attention over a large image was kept for the +backward pass: on Qwen3.5-2B (24 full-attention vision layers, no window, a +16.7 MP pixel cap) a 918x1811 chart is 6400 patches and the process peaked at +75 GB, out of memory on an 80 GB card, where other images took 16-20 GB. The +decoder analyzers (`gradcam`, `generic_attention`, `attribution_patching`) +differentiate towards decoder activations only, so the media encoders now run +without a graph (`media_encoders_without_grad`, found by the towers' names and +the spec's audio hint; `CaptureSpec(media_grad=True)` keeps the old behaviour). +Readings are unchanged; the pixel cap is the model's own and stays. `gradcam` +and `generic_attention` also skip a case whose graph still does not fit +(`skip_reasons: out_of_memory`) instead of failing the chunk: in the ChartQA +validation (`triage17`) the failed chunk stopped both steps on the S route at +12 of 135 cases. + +### Added — a validation-only source for the diagnostic validation + +`--triage-validation-source MANIFEST` (with `--triage-validate`) adds cases used +only for DIAGNOSTIC_VALIDATION: labelled by their own Stage 0 pass +(`/baseline_validation_source.json`), never seen by the controller or the +judge, and joining the CONFIRM cases under the same rule (a case on media +DISCOVERY contains is left out; a source row repeating an id of the pool is +left out too). The partition bundle records where the validation cases came +from and the source manifest's hash. On ChartQA (1000-case pool) the validation +cases were 293 with 100 FAILs, 7 of them on the N route: nothing there could be +decided. `python -m evalrx.benchmark.tasks.chartqa --exclude +/manifest.json` freezes the human-authored rows the pool left (the rest +of the test split, then the val split) as such a source. + +### Changed — the judge explains what already ran, and is re-asked only about what it can predict + +A re-ask fired when a route with carded tools left had fewer than two live +explanations. It counted the steps a route is cut on, which are never offered +to the judge, so a route whose only tools left were such steps asked a question +that could not include it (ChartQA, Qwen3.5-2B: the full-budget D arm's second +ask, for U with only `self_consistency_n10` left). The trigger now counts the +steps the request offers. `logprob_entropy` on U joins `DEFINITIONAL`: an +answer another one out-samples has a close-call token, so U's low confidence is +its cut read off the output distribution, neither an issue nor a prediction on +U. + +That left U on ChartQA with no tool the judge could predict: its rule layers +hold only those two (the option rotation is for letter answers), and the judge +was offered only tools still to run on a route. The tools that already ran on +a route's cases (knockout, patchscope, tuned_lens, ...) are now offered too, +under `already_run`, with their readings in view: a prediction on one is +checked against them during the triage (a fit, not a test), tested on new cases +by the validator, and gives no D, as the tool is not run again. The first ask +no longer needs a tool left to run; a re-ask still does, as only such a tool +brings new evidence. Explanations `mvp4-explain-6`, validation +`mvp4-validate-5`. + +### Changed — triage validation: supported phenomena over a grid of thresholds; explanations met on new cases + +Whether two readings are one phenomenon was decided at one threshold (|rho| >= +0.5), and correlations near it decided which arm found more. The main metric is +now each arm's supported phenomena at every threshold of `RHO_GRID` (0.3 to 0.7 +by 0.05, `validation.supported_curve`, report `phenomenon_curve`). An arm found +more than another only where it has more at every threshold. The live +explanations at each arm's stop are frozen with the family, and the validator +runs the steps their predictions name that no issue ran on that route, so each +prediction is checked on new cases unless its step cannot run there. A +reading a route is cut on (`DEFINITIONAL`, now in `explanations.py`; e.g. +`self_consistency_n10` on U) is neither offered to the judge for that route +nor measured for an explanation: the validator labels such a prediction +`definitional`, neither support nor contradiction. + +Verdicts are one-sided: every issue claims a direction, so it is tested at +alpha/K on its claimed side (its interval at 1 - 2 alpha/K) rather than at +alpha/2K; a false `supported` anywhere in the family still has probability at +most alpha. Each explanation the judge proposes now names one or two primary +predictions, the readings it stands or falls on; competing explanations of a +route must differ on one, and an explanation without one, or that cannot be told +apart from an earlier one, is dropped when the reply is read. Only primary +predictions keep an explanation live during the triage and enter D. The +validator runs the steps of the frozen explanations' primary predictions, tests +the distinct primary predictions as one family (one-sided Bonferroni), and calls +an explanation `supported` (every primary prediction hits), `refuted` (one +misses), `undecided` or `untestable`; other predictions are reported at 95%. An +explanation from an earlier version, without primaries, stands on all its +predictions. A re-ask of the judge keeps the explanations still live and adds +the new ones that compete with them (`explanations.carry_over`; a new one that +cannot be told apart from a kept one is dropped, a reused id is renumbered), so +an explanation live at the stop is frozen however many asks came after it, and +a failed re-ask loses nothing. Validation version `mvp4-validate-4`, +explanations `mvp4-explain-5`. + +### Changed — the U re-sampling check needs another answer to be the most frequent + +The re-sampling part of U fired when any one of the 5 samples differed from +the Stage-0 answer. At temperature 1.0 that is ordinary noise on open answers +(ChartQA, Qwen3.5-0.8B: 16/32 PASS cases fired). It now fires when another +answer was sampled more often than the Stage-0 answer; a tie stays clear. The +check also records `base_is_modal`. The rewording part is unchanged. Rules +version `mvp4-rules-4`. + +### Fixed — triage controls on open-answer tasks + +`triage_cases` gave every record its gold answer as stratum, whatever rule the +sample was drawn with, and controls are matched within a stratum. On an +open-answer task (sampled with `stratum="none"`) almost no PASS case shares a +FAIL case's gold, so route readings had few controls (ChartQA: 5 for 30 U +FAIL cases) and the follow-up steps ran on those few. `triage_cases` takes the +sampler's rule (`stratum=`), passed by `run_triage` and the validator; yes/no +and letter tasks are unchanged. Rules version `mvp4-rules-3`; the judge +context's `fail_by_gold` is now `fail_by_stratum`. + ### Added — triage diagnostic validation (MVP-4, first version) The triage run fixes its data roles before the controller sees a case diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index b642d1b8..424d6804 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -39,11 +39,11 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. -**Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); repair CONFIRM is not part of this protocol. With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 0.05/K` (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way, and the number of supported phenomena is the main count. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are checked where the validation measured their steps and reported apart. `--triage-validation-budget-sec` caps the validation's evidence. +**Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. -U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Any readable answer that differs fires U. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the model's own answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. +U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Re-sampling fires U when another answer was sampled more often than the Stage-0 answer (a tie does not; one differing sample is ordinary noise at temperature 1.0, most of all on open answers); a wrapper fires it when its readable answer differs. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the model's own answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. On an API model (`--backend gemini`) the same plan runs with the white-box steps recorded as `unsupported` (nothing spent). Each action's cost carries what the provider counted — requests, retries, prompt/completion/thought tokens — and its USD at the dated listed price in `evalrx/models/backends/api/prices.py` (unknown for an unlisted model); Stage 0's usage goes into `baseline.json`. The rule-chosen follow-ups are gated on the actual model in the same way, so a run without internal state runs its behavioural follow-ups and records why the internal ones cannot run. diff --git a/docs/analyzers.md b/docs/analyzers.md index 4d2c4703..aed12949 100644 --- a/docs/analyzers.md +++ b/docs/analyzers.md @@ -117,9 +117,12 @@ on the light (API-only) install it is skipped and these analyzers are not offere `evalrx/analyzers/attribution/`: gradient-based saliency (`GRADIENTS`, a backward pass through a white-box model: `hf_local` keeps the autograd graph when asked with -`CaptureSpec(with_grad=True)`). Both explain the next-token logit margin and map the -result back onto the image's patch grid, with overlays on the case photo. Grad-CAM -reads the decoder's image-token states rather than the vision tower. +`CaptureSpec(with_grad=True)`; the graph starts at the decoder, the media encoders run +without one unless `media_grad=True` asks for it, since a vision tower's attention over a +large image kept for backward is tens of GB). Both explain the next-token logit margin and +map the result back onto the image's patch grid, with overlays on the case photo. Grad-CAM +reads the decoder's image-token states rather than the vision tower. A case whose graph +does not fit in memory is skipped (`skip_reasons: out_of_memory`); the others are measured. | Analyzer | Key | Requires | Modality | Paper | Status | diff --git a/evalrx/analyzers/attribution/generic_attn.py b/evalrx/analyzers/attribution/generic_attn.py index cf734add..8d511f1f 100755 --- a/evalrx/analyzers/attribution/generic_attn.py +++ b/evalrx/analyzers/attribution/generic_attn.py @@ -122,7 +122,8 @@ def _run(self, model: "Model", cases: "CaseBatch"): # the tap only records here; the linear layers' relevance has no media re-run to check gate = FidelityGate(model, rtol=self.fidelity_rtol, analyzer=self.name, linear=False) first: "dict[str, Any] | None" = None - for case in cases.stratified_head(self.max_cases): + def measure(case: Any) -> None: + nonlocal first gate.check(case.id, case.inputs) abar: dict[int, Any] = {} recorded: dict[int, Any] = {} @@ -150,7 +151,7 @@ def hook(grad: Any, layer: int = layer, held: Any = held) -> None: margin, why = build_margin(self.target, logits, model=model, case=case) if margin is None: skipped[why] += 1 - continue + return if not recorded: raise RuntimeError( f"{self.name}: the forward pass kept no autograd graph through attention — " @@ -199,6 +200,18 @@ def hook(grad: Any, layer: int = layer, held: Any = held) -> None: per_case.append(row) del trace + for case in cases.stratified_head(self.max_cases): + try: + measure(case) + except torch.cuda.OutOfMemoryError: + # one case's graph did not fit (a long media sequence); the rest still get their reading + skipped["out_of_memory"] += 1 + oom = True + else: + oom = False + if oom: # the case's tensors went with the except clause's traceback; now the cache can go + torch.cuda.empty_cache() + if not per_case: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") n = len(per_case) diff --git a/evalrx/analyzers/attribution/gradcam.py b/evalrx/analyzers/attribution/gradcam.py index 33b0c83f..8eb2657f 100755 --- a/evalrx/analyzers/attribution/gradcam.py +++ b/evalrx/analyzers/attribution/gradcam.py @@ -101,19 +101,20 @@ def _run(self, model: "Model", cases: "CaseBatch"): per_case_maps: dict[str, Any] = {} skipped: Counter = Counter() first_id: "str | None" = None - for case in cases.stratified_head(self.max_cases): + def measure(case: Any) -> None: + nonlocal first_id with residual_hooks(model, capture={layer: None}, keep_grad=True, analyzer=self.name) as hooks: trace = model.forward(case.inputs, capture={Capability.LOGITS}, spec=spec) slot, media = media_positions(trace) if slot != "image": skipped["no_image_tokens"] += 1 - continue + return logits = trace.require(Capability.LOGITS)[-1:] margin, why = build_margin(self.target, logits, model=model, case=case) if margin is None: skipped[why] += 1 - continue + return hidden = hooks.captured[layer] if not hidden.requires_grad: raise RuntimeError( @@ -142,6 +143,18 @@ def _run(self, model: "Model", cases: "CaseBatch"): if first_id is None: first_id = case.id + for case in cases.stratified_head(self.max_cases): + try: + measure(case) + except torch.cuda.OutOfMemoryError: + # one case's graph did not fit (a long media sequence); the rest still get their reading + skipped["out_of_memory"] += 1 + oom = True + else: + oom = False + if oom: # the case's tensors went with the except clause's traceback; now the cache can go + torch.cuda.empty_cache() + if not per_case: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") artifacts: dict[str, Any] = { diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 977487db..567a11e7 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -189,6 +189,12 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "the CONFIRM cases whose media EXPLORE does not contain (/validation/)") p.add_argument("--triage-validation-budget-sec", type=float, default=0.0, help="triage_active with --triage-validate: wall-clock cap on the validation's evidence (0 = none)") + p.add_argument("--triage-validation-source", default=None, metavar="MANIFEST", + help="triage_active with --triage-validate: a manifest of cases used only for DIAGNOSTIC_VALIDATION, " + "beside the CONFIRM cases: labelled by their own Stage 0 pass " + "(/baseline_validation_source.json), never seen by the controller or the judge, and left " + "out where their media DISCOVERY contains (ChartQA: python -m evalrx.benchmark.tasks.chartqa " + " --exclude /manifest.json freezes the human rows the pool left)") p.add_argument("--triage-seed", type=int, default=0, help="triage_active: rank seed of the nested sampler") p.add_argument("--triage-budget-sec", type=float, default=0.0, diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 8a44e89e..5650349d 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -401,8 +401,43 @@ def _triage_explainer(args, spec): return Explainer(judge, identity=identity, price_fn=(lambda u: usd(name, u)) if name else None) +def _validation_source(args, task: T.Task, model, gen_kwargs: dict, protocol, run_dir: Path, ctx): + """``--triage-validation-source``: cases used only for DIAGNOSTIC_VALIDATION, labelled by + their own Stage 0 pass (``/baseline_validation_source.json``). The controller and the + judge never see them; the partition leaves out those on media DISCOVERY contains.""" + from evalrx.eval_agent import CaseDiscoveryAgent + + manifest = Path(args.triage_validation_source) + if not manifest.is_file(): + raise SystemExit(f"--triage-validation-source: {manifest} is missing") + candidates, _ = T.build_cases(task, manifest) + t0 = time.monotonic() + found = CaseDiscoveryAgent( + scorer=T.label_case, generation_kwargs=gen_kwargs, include_unknown=False, + concurrency=getattr(args, "concurrency", 1), + ).discover(model, candidates, protocol=protocol) + elapsed = time.monotonic() - t0 + source = found.cases + if task.short_answer: + for case in source: + case.metadata["finish_reason"] = "stop" + (run_dir / "baseline_validation_source.json").write_text(json.dumps({ + "model": args.model, "dataset": task.name, "role": "validation source", "manifest": str(manifest), + "n": len(source), "n_pass": found.n_pass, "n_fail": found.n_fail, "n_unknown": found.n_unknown, + "accuracy": round(found.n_pass / max(1, len(source)), 4), "seconds": round(elapsed, 1), + "cases": [{ + "id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value, + } for c in source], + }, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"Validation source: PASS={found.n_pass}, FAIL={found.n_fail}, n={len(source)} " + f"({elapsed:.0f}s) from {manifest}") + if ctx is not None: + ctx.config.update(triage_validation_source=str(manifest), n_validation_source_cases=len(source)) + return source, manifest + + def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, - cases, ctx, run_dir: Path, baseline: dict) -> int: + cases, ctx, run_dir: Path, baseline: dict, source=None) -> int: """``--m1-policy triage_active``: the triage battery, rule-chosen expansions and follow-ups on EXPLORE, then stop. @@ -413,8 +448,10 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: The data roles are fixed first (``/partition_bundle.json``): DISCOVERY is EXPLORE, DIAGNOSTIC_VALIDATION the CONFIRM cases on media EXPLORE does not - contain. With ``--triage-validate`` the issues the report supports are frozen - and validated once on DIAGNOSTIC_VALIDATION (``/validation/``). + contain, plus the cases of a validation-only *source* (``(cases, manifest)`` + from :func:`_validation_source`) under the same rule. With ``--triage-validate`` + the issues the report supports are frozen and validated once on + DIAGNOSTIC_VALIDATION (``/validation/``). """ from evalrx.eval_agent.probing import explore_confirm_split, run_triage from evalrx.eval_agent.probing.scoring import Weights @@ -424,10 +461,12 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED) bundle, validation = partition_bundle(explore, confirm, seed=CONFIRM_SPLIT_SEED, - confirm_split=float(args.confirm_split), manifest=baseline.get("manifest")) + confirm_split=float(args.confirm_split), manifest=baseline.get("manifest"), + source=source[0] if source else None, + source_manifest=source[1] if source else None) if args.triage_validate and not len(validation): raise SystemExit("--triage-validate needs CONFIRM cases on media EXPLORE does not contain; " - "set --confirm-split above 0") + "set --confirm-split above 0 or give a --triage-validation-source") bundle_row = bundle.to_dict() (run_dir / "partition_bundle.json").write_text(json.dumps(bundle_row, indent=2) + "\n", encoding="utf-8") runtime = getattr(model, "runtime", None) @@ -471,7 +510,8 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: explore_from=args.triage_explore_from, partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, - "n_validation": len(validation), "bundle_sha1": bundle_row["sha1"], + "n_validation": len(validation), "n_validation_source": len(source[0]) if source else 0, + "bundle_sha1": bundle_row["sha1"], "confirm_visible_to_controller": False}, run_logger=ctx.logger, **shared, ) @@ -650,7 +690,11 @@ def run(args, task: T.Task, resolved: Resolved) -> int: if not discovery.has_m4_groups: raise SystemExit("M4 needs both PASS and FAIL cases; adjust --limit / --seed") if triage: - return _run_triage(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline) + source = None + if getattr(args, "triage_validation_source", None): + source = _validation_source(args, task, model, gen_kwargs, protocol, run_dir, ctx) + return _run_triage(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline, + source=source) # Held-out validation set (--held-out): a SEPARATE frozen sample, labeled # by its own Stage-0 pass. It takes the M4-holdout + fix-development roles; diff --git a/evalrx/benchmark/tasks/chartqa.py b/evalrx/benchmark/tasks/chartqa.py index be785db7..475b4548 100644 --- a/evalrx/benchmark/tasks/chartqa.py +++ b/evalrx/benchmark/tasks/chartqa.py @@ -3,6 +3,12 @@ Port of examples/m1_m5/chartqa_qwen3_5_2b/download_chartqa.py: same parquet, same human-only filter, same seeded sample, same prompt suffix and relaxed 5 % numeric tolerance; the manifest now follows the benchmark protocol (image/audio slots). + +:func:`validation_source` freezes a validation-only manifest: every human-authored +row a discovery pool left (the rest of the test split, then the whole val split), +for ``--triage-validation-source``:: + + python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json """ from __future__ import annotations @@ -11,49 +17,62 @@ import random from pathlib import Path -from .base import Task, _protocol, write_manifest +from .base import Task, _protocol, load_rows, write_manifest REPO = "HuggingFaceM4/ChartQA" REVISION = "b605b6e08b57faf4359aeb2fe6a3ca595f99b6c5" TEST_PARQUET = "data/test-00000-of-00001-e2cd0b7a0f9eb20d.parquet" +VAL_PARQUET = "data/val-00000-of-00001-0f11003c77497969.parquet" +#: per parquet: the subset label, the case id prefix and the image file prefix of its rows +SPLITS = {TEST_PARQUET: ("test_human", "chartqa-human-", "chartqa-"), + VAL_PARQUET: ("val_human", "chartqa-val-human-", "chartqa-val-")} -def download(out_dir: Path, limit: int = 256, seed: int = 5022, exclude_ids: set | None = None, - val_limit: int = 0) -> dict: +def _table(parquet: str): import pyarrow.parquet as pq from huggingface_hub import hf_hub_download + + return pq.read_table(hf_hub_download(REPO, parquet, repo_type="dataset", revision=REVISION)) + + +def _human(table) -> list[int]: + return [i for i, v in enumerate(table.column("human_or_machine").to_pylist()) if v == 0] + + +def _rows(table, indices: list[int], images: Path, *, parquet: str, sample_seed: int | None) -> list[dict]: from PIL import Image + subset, id_prefix, file_prefix = SPLITS[parquet] + rows = [] + for source_index in indices: + item = table.slice(source_index, 1).to_pylist()[0] + filename = f"{file_prefix}{source_index:05d}.png" + destination = images / filename + if not destination.exists(): + Image.open(io.BytesIO(item["image"]["bytes"])).convert("RGB").save(destination) + rows.append({ + "id": f"{id_prefix}{source_index}", + "dataset": REPO, "revision": REVISION, "subset": subset, "source_index": source_index, + "sample_seed": sample_seed, + "image": f"images/{filename}", "audio": None, + "prompt": item["query"] + " Answer with only the short answer.", + "answers": [str(a) for a in item["label"]], + "task": "exact_or_numeric", "numeric_tolerance": 0.05, + "metadata": {"human_or_machine": "human"}, + }) + return rows + + +def download(out_dir: Path, limit: int = 256, seed: int = 5022, exclude_ids: set | None = None, + val_limit: int = 0) -> dict: out_dir = Path(out_dir) images = out_dir / "images" images.mkdir(parents=True, exist_ok=True) - table = pq.read_table(hf_hub_download(REPO, TEST_PARQUET, repo_type="dataset", revision=REVISION)) - human = [i for i, v in enumerate(table.column("human_or_machine").to_pylist()) if v == 0] + table = _table(TEST_PARQUET) excluded = set(exclude_ids or ()) - human = [i for i in human if f"chartqa-human-{i}" not in excluded] + human = [i for i in _human(table) if f"chartqa-human-{i}" not in excluded] selected = random.Random(seed).sample(human, min(limit, len(human))) - - def rows_for(indices: list[int], sample_seed: int) -> list[dict]: - rows = [] - for source_index in indices: - item = table.slice(source_index, 1).to_pylist()[0] - filename = f"chartqa-{source_index:05d}.png" - destination = images / filename - if not destination.exists(): - Image.open(io.BytesIO(item["image"]["bytes"])).convert("RGB").save(destination) - rows.append({ - "id": f"chartqa-human-{source_index}", - "dataset": REPO, "revision": REVISION, "subset": "test_human", "source_index": source_index, - "sample_seed": sample_seed, - "image": f"images/{filename}", "audio": None, - "prompt": item["query"] + " Answer with only the short answer.", - "answers": [str(a) for a in item["label"]], - "task": "exact_or_numeric", "numeric_tolerance": 0.05, - "metadata": {"human_or_machine": "human"}, - }) - return rows - - write_manifest(out_dir / "manifest.json", rows_for(selected, seed)) + write_manifest(out_dir / "manifest.json", _rows(table, selected, images, parquet=TEST_PARQUET, sample_seed=seed)) summary = {"kept": len(selected), "excluded": len(excluded), "manifest": str(out_dir / "manifest.json")} if val_limit and val_limit > 0: @@ -61,13 +80,35 @@ def rows_for(indices: list[int], sample_seed: int) -> list[dict]: # rows the main sample did not take — disjoint by construction. leftover = [i for i in human if i not in set(selected)] val_selected = random.Random(seed + 1).sample(leftover, min(val_limit, len(leftover))) - val_rows = rows_for(val_selected, seed + 1) + val_rows = _rows(table, val_selected, images, parquet=TEST_PARQUET, sample_seed=seed + 1) write_manifest(out_dir / "manifest_val.json", val_rows) summary.update(kept_val=len(val_rows), manifest_val=str(out_dir / "manifest_val.json")) return summary +def validation_source(out_dir: Path, exclude: "list[str | Path] | tuple[str | Path, ...]" = ()) -> dict: + """Freeze ``/manifest.json`` with every human-authored row whose id is in none of the + *exclude* manifests: the rest of the test split, then the whole val split, in source order (no + sampling: this is the data the pool left). Validation only (``--triage-validation-source``); the + partition, not this, leaves out what shares a chart with DISCOVERY.""" + out_dir = Path(out_dir) + images = out_dir / "images" + images.mkdir(parents=True, exist_ok=True) + excluded = {str(r["id"]) for path in exclude for r in load_rows(Path(path))} + rows: list[dict] = [] + by_subset: dict[str, int] = {} + for parquet in (TEST_PARQUET, VAL_PARQUET): + table = _table(parquet) + subset, id_prefix, _ = SPLITS[parquet] + indices = [i for i in _human(table) if f"{id_prefix}{i}" not in excluded] + rows.extend(_rows(table, indices, images, parquet=parquet, sample_seed=None)) + by_subset[subset] = len(indices) + write_manifest(out_dir / "manifest.json", rows) + return {"kept": len(rows), "by_subset": by_subset, "excluded": len(excluded), + "manifest": str(out_dir / "manifest.json")} + + def protocol(model_label: str): return _protocol( description=( @@ -93,3 +134,14 @@ def protocol(model_label: str): default_limit=256, val_limit=128, default_seed=5022, max_new_tokens=64, source="HuggingFaceM4/ChartQA (test, human-authored)", ) + + +if __name__ == "__main__": # pragma: no cover + import argparse + import json + + ap = argparse.ArgumentParser(description="freeze ChartQA's validation-only source (see validation_source)") + ap.add_argument("out_dir", type=Path) + ap.add_argument("--exclude", nargs="*", default=[], help="manifests whose rows are left out (the discovery pool)") + ns = ap.parse_args() + print(json.dumps(validation_source(ns.out_dir, ns.exclude))) diff --git a/evalrx/core/model.py b/evalrx/core/model.py index b1097a93..240cc7a0 100755 --- a/evalrx/core/model.py +++ b/evalrx/core/model.py @@ -43,6 +43,10 @@ class CaptureSpec: heads: "list[int] | None" = None # which attention heads to keep (None = all) to_cpu: bool = True # move captured tensors to CPU (frees GPU mem) with_grad: bool = False # keep the graph for GRADIENTS (else no_grad) + # with_grad: also keep the media encoders' graph (gradients towards pixels or audio). Off, their + # outputs enter the decoder as constants: a vision tower's attention over a 6000-patch image + # kept for backward is tens of GB, and the decoder analyzers never differentiate through it. + media_grad: bool = False @dataclass diff --git a/evalrx/eval_agent/probing/compare.py b/evalrx/eval_agent/probing/compare.py index 035a8fdf..4f578fd2 100644 --- a/evalrx/eval_agent/probing/compare.py +++ b/evalrx/eval_agent/probing/compare.py @@ -11,7 +11,7 @@ from itertools import combinations from typing import Any -from evalrx.eval_agent.probing.explanations import CARDS, verdict +from evalrx.eval_agent.probing.explanations import CARDS, primary_readings, verdict def discrimination(explained: dict[str, Any], report: dict[str, Any]) -> dict[str, Any]: @@ -29,9 +29,10 @@ def discrimination(explained: dict[str, Any], report: dict[str, Any]) -> dict[st for a, b in combinations(last["hypotheses"], 2): if a["route"] != b["route"]: continue + decisive = primary_readings(a) | primary_readings(b) on = [(step, f) for step in sorted(set(a["predictions"]) & set(b["predictions"])) for f in sorted(set(a["predictions"][step]) & set(b["predictions"][step])) - if a["predictions"][step][f] != b["predictions"][step][f]] + if a["predictions"][step][f] != b["predictions"][step][f] and (step, f) in decisive] if not on: continue resolved = [f"{step}.{f}" for step, f in on diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 87c2de7c..5d9efa15 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -93,11 +93,13 @@ ExplanationSet, Hypothesis, Metric, + carry_over, check, decidability, disagreement, label_bound, outcome, + restates_route, ) from evalrx.eval_agent.probing.explanations import spread as reading_spread from evalrx.eval_agent.probing.ledger import Ledger @@ -167,7 +169,7 @@ ROUTE_MEANING = { "H": "the output lost the answer: an extraction, truncation or format check fired", "N": "the answer did not change when the media was swapped for media on which the correct answer differs", - "U": "the answer moved under re-sampling at the host's settings or under a neutral rewording", + "U": "re-sampling at the host's settings mostly gave another answer, or a neutral rewording moved it", "S": "a stable error: the output, media-swap and stability checks all ran and none fired", "X": "a required check could not run on the case", } @@ -185,8 +187,8 @@ "cut text-to-media attention per layer band; margin change of the model's own first answer token", fidelity_check="edit", calls_per_case={"forward": 5}, evidence=MEDIA_ATTENTION_CUT), PlanStep("self_consistency", {"n": 5}, "U", - "re-sample each case at the host's frozen sampling settings; an answer that differs " - "from the Stage-0 answer is the U signal", + "re-sample each case at the host's frozen sampling settings; another answer sampled " + "more often than the Stage-0 answer is the U signal", calls_per_case={"generate": 5}, per_case=True, keep_artifacts=("samples",)), PlanStep("prompt_contrast", {"strategies": REWORD_STRATEGIES}, "U", "re-ask with the question verbatim inside two neutral wrappers; an answer that " @@ -685,7 +687,7 @@ def run_triage( chunk=chunk) rank_of = partial(rank, seed) triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, - n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn) + n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn, stratum=stratum) sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) draws = [draw] @@ -998,34 +1000,39 @@ def explanation_request(records: list[dict[str, Any]], options: dict[str, list[A seeded order: each open layer's current candidate, and every layer's other candidates as alternatives (to the tool that answered it, or to its current candidate). An alternative runs once its layer is answered if its D beats its redundancy, so its predictions are - asked for up front.""" + asked for up front. Then every other carded step measured on the route (``already_run``): + a prediction on it is checked on new cases by the validator, and gives no D.""" offered: dict[str, dict[str, list[str]]] = {} routes: dict[str, Any] = {} for route, rows in options.items(): to_run: list[dict[str, Any]] = [] for _, st, step, _, alternative_to in rows: layer = by_rule[st["rule_id"]] - if step.name in CARDS and all(c["step"] != step.name for c in to_run): + # a reading the route is cut on cannot tell explanations of that route apart + if (step.name in CARDS and not restates_route(route, step.name) + and all(c["step"] != step.name for c in to_run)): to_run.append({"step": step.name, "tool": step.analyzer, "layer": layer.rule_id, "question": layer.question, "what": step.purpose, **({"alternative_to": alternative_to} if alternative_to else {}), **({"caveat": step.caveat} if step.caveat else {}), "readings": [m.card() for m in CARDS[step.name]]}) - if not to_run: - continue - random.Random(f"{seed}:{revision}:{route}").shuffle(to_run) - offered[route] = {c["step"]: [r["field"] for r in c["readings"]] for c in to_run} measured: dict[str, Any] = {} for key in sorted(CARDS): rows = {m.field: {k: v for k, v in o.items() if k != "observed" or v != "not_measured"} for m in CARDS[key] if (o := outcome_of(route, key, m))["n"] != [0, 0]} if rows: measured[key] = rows + ran = [{"step": key, "readings": [m.card() for m in CARDS[key]]} for key in measured + if not restates_route(route, key) and all(c["step"] != key for c in to_run)] + if not to_run and not ran: + continue + random.Random(f"{seed}:{revision}:{route}").shuffle(to_run) + offered[route] = {c["step"]: [r["field"] for r in c["readings"]] for c in [*to_run, *ran]} fail_ids = route_fail_ids(records, route) by_id = {r["case_id"]: r for r in records} routes[route] = {"meaning": ROUTE_MEANING.get(route, ""), "n_fail": len(fail_ids), - "fail_by_gold": dict(sorted(Counter(by_id[c]["stratum"] for c in fail_ids).items())), - "measured": measured, "to_run": to_run} + "fail_by_stratum": dict(sorted(Counter(by_id[c]["stratum"] for c in fail_ids).items())), + "measured": measured, "to_run": to_run, "already_run": ran} previous = [] if explanation_sets and explanation_sets[-1].hypotheses: prev = explanation_sets[-1] @@ -1061,20 +1068,23 @@ def ask_reason(options: dict[str, list[Any]], growing: bool, verdicts: dict[str, Explanations are about the routes, and an expansion revises the routes: the judge is first asked once no expansion can follow (the sample has settled, - or the next one is over budget). It is asked again when the evidence has - decided a prediction since the last ask and a route with tools left has - fewer than two live explanations.""" + or the next one is over budget), whatever is left to run: the tools already + run on a route are explained too. It is asked again when the evidence has + decided a prediction since the last ask and a route with tools left that the + judge can be asked about (as ``explanation_request`` offers them) has fewer + than two live explanations: only a tool still to run brings evidence.""" if growing: plan = expansion_plan() if plan is not None and run.over_budget(plan[3]) is None: return None - with_cards = sorted(route for route, rows in options.items() if any(row[2].name in CARDS for row in rows)) # a judge call is charged like an action: asked only while its estimate fits, the # largest call so far (the first is unknown: a run overshoots by at most one call) - if not with_cards or run.over_budget(judge_estimate("wall_sec"), judge_estimate("usd")) is not None: + if run.over_budget(judge_estimate("wall_sec"), judge_estimate("usd")) is not None: return None if current is None: return "the sample has settled: no expansion can follow" + with_cards = sorted(route for route, rows in options.items() + if any(row[2].name in CARDS and not restates_route(route, row[2].name) for row in rows)) new = _decided(verdicts) - current.decided_at_ask thin = [route for route in with_cards if sum(1 for h in current.hypotheses if h.route == route and verdicts[h.id]["state"] == "live") < 2] @@ -1100,6 +1110,14 @@ def explain(records: list[dict[str, Any]], options: dict[str, list[Any]], ledger.cost({"kind": "judge", "key": es.key, "revision": revision, "source": es.source, **es.cost}) es.reason = reason + if explanation_sets: + # what is still live stays: a re-ask (or a failed one) adds explanations, it does not replace them + prev = explanation_sets[-1] + states = check(prev.hypotheses, outcome_of) + kept = [h for h in prev.hypotheses if states[h.id]["state"] == "live"] + taken = {h.id for x in explanation_sets for h in x.hypotheses} + es.hypotheses, extra = carry_over(kept, es.hypotheses, taken) + es.dropped, es.carried = es.dropped + extra, [h.id for h in kept] ledger.trace({"event": "explanations", "revision": revision, "key": es.key, "source": es.source, "reason": reason, "error": es.error, "by_route": dict(Counter(h.route for h in es.hypotheses)), "dropped": es.dropped, "cost": es.cost}) @@ -1477,9 +1495,9 @@ def _evidence_cost(run: _Run) -> dict[str, Any]: def _decided(verdicts: dict[str, Any]) -> set[tuple[str, str, str]]: - """The predictions the evidence has decided (hit or miss), as (explanation, step, reading).""" + """The primary predictions the evidence has decided (hit or miss), as (explanation, step, reading).""" return {(hid, p["step"], p["reading"]) for hid, row in verdicts.items() for p in row["predictions"] - if p["verdict"] in ("hit", "miss")} + if p["verdict"] in ("hit", "miss") and p.get("primary", True)} def _judge_cost(sets: list[ExplanationSet]) -> dict[str, Any]: @@ -1806,11 +1824,14 @@ def _markdown(report: dict[str, Any]) -> str: if not es["hypotheses"]: lines.append("No explanation." + (f" Dropped: {es['dropped']}." if es["dropped"] else "")) continue + if es.get("carried"): + lines += [f"Kept from the last ask (still live): {', '.join(es['carried'])}.", ""] lines += ["| explanation | claim | state | predictions: predicted -> observed (verdict) |", "|---|---|---|---|"] for h in es["hypotheses"]: final = es["final"][h["id"]] - preds = "; ".join(f"{p['step']}.{p['reading']}: {p['predicted']} -> " + preds = "; ".join(("**primary** " if p.get("primary") else "") + + f"{p['step']}.{p['reading']}: {p['predicted']} -> " f"{p['outcome'].get('observed')} ({p['verdict']}" + (", seen" if p.get("seen_when_predicted") else "") + ")" for p in final["predictions"]) or "none explicit" diff --git a/evalrx/eval_agent/probing/explanations.py b/evalrx/eval_agent/probing/explanations.py index cc6b8342..6306d3c9 100644 --- a/evalrx/eval_agent/probing/explanations.py +++ b/evalrx/eval_agent/probing/explanations.py @@ -5,10 +5,13 @@ that route's FAIL cases fail. It is asked once the sample has settled (an expansion revises the routes, as it supersedes batch-dependent readings), and again, up to ``max_asks`` times in all, when the evidence has decided a -prediction and a route with tools left has fewer than two live explanations; -each ask sees the previous explanations' verdicts. For each tool still to run -on the route, every explanation predicts the direction of the tool's readings -on the route's FAIL cases against their PASS controls: +prediction and a route with tools left that it can be asked about has fewer +than two live explanations; each ask sees the previous explanations' verdicts, +and the ones still live are kept: an ask adds explanations that compete with +them, it never replaces them (``carry_over``), so a failed ask loses nothing +either. For each tool still to run on the route, and each tool that has already +run there, every explanation predicts the direction of the tool's readings on +the route's FAIL cases against their PASS controls: * ``up``: FAIL mean - control mean > the reading's band; * ``down``: < -band; @@ -17,7 +20,11 @@ The readings, their meaning, sign and band are fixed here, per step, in ``CARDS``: the judge picks a direction, never the metric, the comparison or -the threshold. A card compares FAIL with PASS, so no reading on it may be +the threshold. A prediction on a tool that has already run is made with its +readings in view: it is checked against them here (a fit, not a test) and on +new cases by the validator, and it gives no D, as the tool is not run again. A +route whose own tools have all run (or are all ones it is cut on) is still +explained that way. A card compares FAIL with PASS, so no reading on it may be computed from the correctness label or the gold answer: a FAIL case's output is not gold by definition, so "the gold margin is lower on FAIL" restates the label. Steps with a target read the model's own answer (``target="prediction"``), @@ -25,12 +32,18 @@ off the cards. Code, not the judge, checks the predictions against the evidence (``verdict``): a prediction is a hit when the 95% interval of the difference lies inside its region, a miss when it lies outside, and -undetermined otherwise. An explanation with a miss is contradicted and leaves -the live set; one without any explicit prediction is untestable and is not in -it either. +undetermined otherwise. Each explanation names one or two of its predictions as +primary, the ones it stands or falls on, and only those decide: an explanation +with a miss on a primary prediction is contradicted and leaves the live set, +and one without a primary prediction is dropped when the reply is read. The +other predictions are reported only. Competing explanations of a route must +differ on a primary prediction (see ``parse``). A reading the route is cut on, +or one the cut implies (``DEFINITIONAL``), is not offered for that route: it +cannot tell explanations of the route apart. ``D(a)`` for a candidate on route r sums, over the pairs of r's live -explanations whose explicit predictions for that step conflict, how decidable +explanations whose explicit predictions for that step conflict on a reading +primary for one of the two, how decidable the conflict is on the route's cases, and divides by the number of pairs; a pair with an ``unknown`` counts in the denominator only. Zero or one live explanation gives ``D = 0``. Confidence the judge states is not asked for and @@ -65,7 +78,7 @@ import os import re import time -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from itertools import combinations from pathlib import Path from typing import Any, Callable, Iterable @@ -73,7 +86,7 @@ from evalrx.eval_agent.probing.metering import usage_counters, usage_delta from evalrx.eval_agent.probing.triage import difference_interval -EXPLAIN_VERSION = "mvp4-explain-3" +EXPLAIN_VERSION = "mvp4-explain-6" DIRECTIONS = ("up", "down", "same", "unknown") _ALIASES = {"↑": "up", "↓": "down", "≈": "same", "=": "same", "~": "same", "?": "unknown", "higher": "up", "lower": "down", "increase": "up", "decrease": "down", "none": "unknown"} @@ -96,6 +109,15 @@ def card(self) -> dict[str, Any]: #: Analyzer targets that are the correctness label in another form. LABEL_TARGETS = ("gold",) +#: Steps that re-measure the check a route is cut on (U: another answer sampled more often; S: none +#: was), on that route, or read it off the output distribution (an answer another one out-samples has +#: a close-call token): their difference there is the cut, so neither an issue nor a prediction. +DEFINITIONAL = {"self_consistency_n10": ("U", "S"), "logprob_entropy": ("U",)} + + +def restates_route(route: str, step: str) -> bool: + """Whether *step*'s readings on *route* re-measure the check the route is cut on.""" + return route in DEFINITIONAL.get(step, ()) def label_bound(steps: "Iterable[Any]", extras: "dict[str, dict[str, Any]] | None" = None) -> list[str]: @@ -409,13 +431,27 @@ class Hypothesis: claim: str predictions: dict[str, dict[str, str]] # step key -> reading -> direction (explicit ones only) basis: str = "" + primary: tuple[tuple[str, str], ...] = () # (step, reading): the predictions it stands or falls on def explicit(self) -> list[tuple[str, str, str]]: return [(step, f, d) for step, by in sorted(self.predictions.items()) for f, d in sorted(by.items())] + def primaries(self) -> set[tuple[str, str]]: + return primary_readings(self.to_dict()) + def to_dict(self) -> dict[str, Any]: return {"id": self.id, "route": self.route, "claim": self.claim, "basis": self.basis, - "predictions": self.predictions} + "predictions": self.predictions, "primary": [list(x) for x in self.primary]} + + +def primary_readings(h: dict[str, Any]) -> set[tuple[str, str]]: + """The (step, reading) pairs an explanation (as a dict) stands or falls on. One written before + explanations named them (``mvp4-explain-3`` and earlier) stands on every explicit prediction.""" + preds = h.get("predictions") or {} + named = h.get("primary") + if not named: + return {(step, f) for step, by in preds.items() for f in by} + return {(str(step), str(f)) for step, f in named if f in (preds.get(step) or {})} @dataclass @@ -433,10 +469,11 @@ class ExplanationSet: source: str = "judge" # "judge" | "read_back" | "failed" cost: dict[str, Any] = field(default_factory=dict) error: "str | None" = None + carried: list[str] = field(default_factory=list) # live explanations kept from the last ask def to_dict(self) -> dict[str, Any]: return {"revision": self.revision, "key": self.key, "source": self.source, "reason": self.reason, - "error": self.error, + "error": self.error, "carried": self.carried, "cost": self.cost, "offered": self.offered, "seen": self.seen, "dropped": self.dropped, "hypotheses": [h.to_dict() for h in self.hypotheses]} @@ -446,17 +483,21 @@ def to_dict(self) -> dict[str, Any]: def check(hypotheses: list[Hypothesis], outcome_of: Outcomes) -> dict[str, dict[str, Any]]: """Every hypothesis' state on the current evidence: ``live`` / ``contradicted`` / ``untestable``, - with each explicit prediction's verdict.""" + with each explicit prediction's verdict. Only the primary predictions decide the state: a miss on + one contradicts the explanation; the others are reported.""" out = {} for h in hypotheses: rows = [] + primary = h.primaries() for step, name, direction in h.explicit(): metric = next(m for m in CARDS[step] if m.field == name) o = outcome_of(h.route, step, metric) rows.append({"step": step, "reading": name, "predicted": direction, "band": metric.band, + "primary": (step, name) in primary, "outcome": o, "verdict": verdict(direction, o.get("ci95"), metric.band)}) - state = ("untestable" if not rows else - "contradicted" if any(r["verdict"] == "miss" for r in rows) else "live") + decisive = [r for r in rows if r["primary"]] + state = ("untestable" if not decisive else + "contradicted" if any(r["verdict"] == "miss" for r in decisive) else "live") out[h.id] = {"state": state, "predictions": rows} return out @@ -466,7 +507,8 @@ def check(hypotheses: list[Hypothesis], outcome_of: Outcomes) -> dict[str, dict[ def disagreement(route: str, step: str, live: list[Hypothesis], decidable: "Decidable | None" = None) -> tuple[float, dict[str, Any]]: - """``D`` of running *step* on *route*, and which pairs of live explanations it separates. + """``D`` of running *step* on *route*, and which pairs of live explanations it separates: a pair + conflicts on a reading both predict differently that is primary for one of them. Each conflicting pair counts by how decidable its conflict is on the route's cases (:func:`decidability`; its most decidable reading); without *decidable* every conflict @@ -478,7 +520,8 @@ def disagreement(route: str, step: str, live: list[Hypothesis], conflicting = [] for a, b in pairs: pa, pb = a.predictions.get(step, {}), b.predictions.get(step, {}) - on = sorted(f for f in set(pa) & set(pb) if pa[f] != pb[f]) + decisive = {f for s, f in a.primaries() | b.primaries() if s == step} + on = sorted(f for f in set(pa) & set(pb) if pa[f] != pb[f] and f in decisive) if on: row: dict[str, Any] = {"pair": [a.id, b.id], "readings": on} if decidable is not None: @@ -498,7 +541,8 @@ def disagreement(route: str, step: str, live: list[Hypothesis], the wrong (FAIL) cases into routes; each route's FAIL cases are compared with correct (PASS) cases of the same gold answer (its controls). Some tools have not run on a route yet. The controller will run them one at a time and wants to run -first the ones whose result would tell competing explanations apart. +first the ones whose result would tell competing explanations apart. Every +explanation is later checked on new cases, on the readings it predicts. For every route listed under "routes", propose at most {max_per_route} competing local explanations of why that route's FAIL cases fail. Local: about these cases @@ -510,20 +554,39 @@ def disagreement(route: str, step: str, live: list[Hypothesis], A tool with "alternative_to" asks a question that another tool (named there) has already answered on the route: it runs only if it tells explanations apart. -For each explanation and each tool listed under the route's "to_run", predict -for each of its readings the direction of (FAIL mean - control mean): +For each explanation and each tool listed under the route's "to_run" or +"already_run", predict for each of its readings the direction of +(FAIL mean - control mean): "up" the difference is above +band "down" the difference is below -band "same" the difference is within +-band "unknown" the explanation does not imply a direction (the default) -Only predict a direction the explanation implies; a wrong confident prediction -counts against it. Readings measured so far are under "measured"; use them, and -the previous explanations' verdicts under "previous", to revise. +Only predict a direction the explanation implies. Readings measured so far are +under "measured"; use them, and the previous explanations' verdicts under +"previous", to revise. A tool under "already_run" has run on the route: its +readings under "measured" are what a prediction on it is checked against now, +and new cases are the test that counts; it will not run again here, so it +cannot decide which tool runs next. The previous explanations whose state is "live" are kept +as they are: propose only new ones, each told apart from the kept ones of its +route on a primary prediction (one that is not is dropped), and none for a route +whose kept explanations already cover the alternatives you see. + +Name one or two of each explanation's predictions as "primary": the readings it +stands or falls on, the ones that would show it wrong if they came out otherwise. +Only primary predictions decide whether an explanation is kept or rejected, here +and later on new cases; the others are reported only, so leave a reading +"unknown" rather than guess. Competing explanations of a route must be told +apart on a primary prediction: on at least one reading that is primary for one +of the two, both predict a direction and the directions differ (so also predict +the readings that are the other explanations' primary ones). An explanation +that cannot be told apart from an earlier one this way is dropped. Make "same" +primary only when the explanation says the FAIL cases do not differ there. Answer with JSON only, no prose, in this shape: {{"routes": {{"": [{{"id": "h1", "claim": "", "basis": "", - "predictions": {{"": {{"": "up|down|same|unknown"}}}}}}]}}}} + "predictions": {{"": {{"": "up|down|same|unknown"}}}}, + "primary": [["", ""]]}}]}}}} Evidence (JSON): """ @@ -550,9 +613,12 @@ def parse(reply: str, offered: dict[str, dict[str, list[str]]], """The valid explanations in *reply*, and what was dropped and why. Kept: routes and steps that were offered, readings on the step's card, - the four directions (arrows accepted). A second explanation with the same - explicit predictions as an earlier one is a duplicate (it can never be told - apart from it); explanations beyond *max_per_route* are dropped. + the four directions (arrows accepted), and one or two primary predictions + among the explicit ones (an explanation without one is dropped; beyond two, + the first two are kept). An explanation that cannot be told apart from an + earlier one of its route on a primary prediction (one of the two names it, + both predict it, and they differ) does not compete with it and is dropped, + as are explanations beyond *max_per_route*. """ dropped: list[dict[str, Any]] = [] try: @@ -592,10 +658,24 @@ def parse(reply: str, offered: dict[str, dict[str, list[str]]], dropped.append({"what": f"{hid} {step}.{reading}", "reason": f"direction {raw!r}"}) elif d != "unknown": preds.setdefault(step, {})[reading] = d + primary: list[tuple[str, str]] = [] + for pair in item.get("primary") or []: + step, reading = (list(pair) + [None, None])[:2] if isinstance(pair, (list, tuple)) else (None, None) + if reading not in (preds.get(step) or {}): + dropped.append({"what": f"{hid} primary {pair!r}", "reason": "not one of its explicit predictions"}) + elif (step, reading) not in primary: + primary.append((step, reading)) + if len(primary) > 2: + dropped.append({"what": f"{hid} primary {primary[2:]}", "reason": "more than two primary predictions"}) + primary = primary[:2] + if not primary: + dropped.append({"what": hid, "reason": "no primary prediction among its explicit predictions"}) + continue h = Hypothesis(id=hid, route=route, claim=str(item["claim"]).strip(), predictions=preds, - basis=str(item.get("basis") or "").strip()) - if preds and any(k.predictions == preds for k in kept): - dropped.append({"what": hid, "reason": "same explicit predictions as an earlier explanation"}) + basis=str(item.get("basis") or "").strip(), primary=tuple(primary)) + same = next((k for k in kept if not _told_apart(h, k)), None) + if same is not None: + dropped.append({"what": hid, "reason": f"cannot be told apart from {same.id} on a primary prediction"}) continue if len(kept) >= max_per_route: dropped.append({"what": hid, "reason": f"more than {max_per_route} explanations"}) @@ -605,6 +685,38 @@ def parse(reply: str, offered: dict[str, dict[str, list[str]]], return out, dropped +def _told_apart(a: Hypothesis, b: Hypothesis) -> bool: + """Whether a reading primary for *a* or *b* has a direction from both, and they differ.""" + return any(f in a.predictions.get(step, {}) and f in b.predictions.get(step, {}) + and a.predictions[step][f] != b.predictions[step][f] for step, f in a.primaries() | b.primaries()) + + +def carry_over(kept: list[Hypothesis], new: list[Hypothesis], + taken: "Iterable[str]" = ()) -> tuple[list[Hypothesis], list[dict[str, Any]]]: + """The explanations still live at a new ask, then the new ones that compete with them. + + A new explanation that cannot be told apart from a kept one of its route on a primary + prediction is dropped; one whose id an explanation already had (kept, or in an earlier + set: *taken*) is renumbered, so an id names one explanation for the whole run. + """ + out, dropped = list(kept), [] + used = {*taken, *(h.id for h in kept)} + for h in new: + same = next((k for k in kept if k.route == h.route and not _told_apart(h, k)), None) + if same is not None: + dropped.append({"what": h.id, "reason": f"cannot be told apart from {same.id} (kept from the last " + "ask) on a primary prediction"}) + continue + if h.id in used: + n = 1 + while f"{h.route}.h{n}" in used: + n += 1 + h = replace(h, id=f"{h.route}.h{n}") + used.add(h.id) + out.append(h) + return out, dropped + + class Explainer: """Asks a text judge (``generate(prompt) -> str``) for explanations, through the run's store. diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index 2b9fa2d3..2d9652c4 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -47,7 +47,7 @@ from evalrx.eval_agent.probing.actions import PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -RULES_VERSION = "mvp4-rules-2" +RULES_VERSION = "mvp4-rules-4" ROUTE_ORDER = ("H", "N", "U", "S", "X") DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index cda76b95..37d651d5 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -214,6 +214,11 @@ def _samples_vary(gen: dict[str, Any]) -> bool: def _u_sampling(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: + """Fires when another answer was sampled more often than the Stage-0 answer (a tie stays clear). + + One differing sample is ordinary sampling noise at temperature 1.0, most of all on open answers; + the signal is that the model's greedy answer is not what it usually says. + """ why = _unavailable(obs, "self_consistency") if why is not None: return {"part": "sampling", "state": UNTESTED, "reason": why} @@ -237,8 +242,10 @@ def _u_sampling(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> di answers=dict(Counter(readable))) if not readable: return {**out, "state": UNTESTED, "reason": "no sample commits to a readable answer"} - out["agreement"] = round(sum(a == base for a in readable) / len(readable), 4) - return {**out, "state": FIRED if out["agreement"] < 1.0 else CLEAR} + counts = Counter(readable) + out["agreement"] = round(counts[base] / len(readable), 4) + out["base_is_modal"] = counts[base] == max(counts.values()) + return {**out, "state": CLEAR if out["base_is_modal"] else FIRED} def _outputs(obs: Observation) -> dict[str, dict[str, str]]: @@ -326,7 +333,7 @@ def _s_patchscope(obs: "Observation | None", cid: str) -> dict[str, Any]: def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence]", *, host_assumed_finish: bool, answer_contract: bool, n_needs_counterfactual: bool = False, - answer_fn: "AnswerFn | None" = None) -> list[dict[str, Any]]: + answer_fn: "AnswerFn | None" = None, stratum: str = "gold") -> list[dict[str, Any]]: """One record per case: label, stratum, every H/N/U check, routes, knockout and S readings. *observations* are keyed by plan step (``prompt_reword`` and @@ -342,10 +349,15 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence *answer_fn* ``(case, output) -> key`` reads the answer an output commits to (``""``: none; ``None``: the task has no categorical answer); default :func:`default_answer`. + + *stratum* is the sampler's rule (``"gold"`` or ``"none"``): controls are matched within a record's + stratum, so it must be the rule the sample was drawn with. Open-answer tasks draw with ``"none"``; + a gold stratum there leaves almost no PASS case with a FAIL case's gold to serve as its control. """ - from evalrx.eval_agent.probing.sampler import gold_stratum + from evalrx.eval_agent.probing.sampler import STRATA answer = answer_fn or default_answer + stratum_of = STRATA[stratum] records = [] for case in cases: cid = str(case.id) @@ -390,7 +402,7 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence records.append({ "case_id": cid, "label": label, - "stratum": gold_stratum(case), + "stratum": stratum_of(case), "routes": routes, "stable": stable, "x_reasons": x_reasons, diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py index 3b307700..ac5adb0f 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/probing/validation.py @@ -4,8 +4,11 @@ controller sees any case. DISCOVERY is the EXPLORE partition the controller works on; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case that shares a source with DISCOVERY (a source is the media content: a question about -an image the diagnosis saw is not a new image). Repair CONFIRM is not part of -this protocol (repair is out of scope), so the bundle says so. +an image the diagnosis saw is not a new image), plus, when a validation-only +source is given (``--triage-validation-source``: cases labelled by their own +Stage 0 pass, never seen by the controller or the judge), its cases under the +same rule. Repair CONFIRM is not part of this protocol (repair is out of +scope), so the bundle says so. **Issues.** :func:`freeze_issues` turns a triage report into issue versions whose cohort, signal, direction, band and test can be applied to new cases: @@ -18,16 +21,18 @@ reading's band (discovery: the whole 95% interval outside it). One issue per route and step: the reading furthest outside its band, in band units; the step's other readings outside their bands are listed, not tested. A step that - re-measures the check that defines the route (``DEFINITIONAL``) is not an - issue: the route was cut on it. + re-measures the check that defines the route, or reads what that check + implies (``DEFINITIONAL``), is not an issue: the route was cut on it. No reading reads the label: the controller refuses a carded step whose target is the gold answer (a FAIL output is not gold by definition, so a gold margin lower on FAIL restates the label), and the validator refuses a report from another rules version (it re-runs the steps as they are defined now). -The judge's explanations are not issues: their predictions are checked on the -validation evidence and reported apart (mechanism claims, not counted). +The judge's explanations are not issues: the ones live at an arm's stop are +frozen with the family, and their predictions are checked on the validation +cases of their route, the validator running the steps they name that no issue +ran there (mechanism claims: reported apart, not counted). **Plan.** :func:`plan_validation` estimates, from DISCOVERY alone (before any validation output is read), the validation cases each issue will have and the @@ -37,11 +42,15 @@ **Validation.** :func:`validate` runs once, on the union of the frozen families of the given arms: the route checks on the validation FAIL cases and their matched PASS controls, then each reading issue's step on its route. The family -is written to ``frozen.json`` before anything runs. Every issue's interval is -taken at ``1 - ALPHA / K`` (Bonferroni over the K issues of the family), and -its verdict is ``supported`` (inside the predicted region), ``refuted`` -(outside it), ``inconclusive`` (neither) or ``unavailable`` (the step could not -run, or too few cases). +is written to ``frozen.json`` before anything runs. Every issue claims a +direction, so its verdict is a one-sided test at ``ALPHA / K`` on each side +(Bonferroni over the K issues of the family): its interval is taken at +``1 - 2 * ALPHA / K``, and the verdict is ``supported`` (inside the predicted +region), ``refuted`` (outside it), ``inconclusive`` (neither) or +``unavailable`` (the step could not run, or too few cases). A false +``supported`` anywhere in the family then has probability at most ALPHA, and so +does a false ``refuted``: the side that can only refute no longer spends half of +the error the supported side may. **Phenomena.** Several readings can say one thing (an attention cut and a noised image both measuring how much the media carries the answer). Two reading issues @@ -51,8 +60,13 @@ the two groups does not count, since every issue has one); phenomena are the connected groups. The rule is frozen with the family. Each arm is credited with its own issues, grouped into phenomena: a phenomenon is supported for an arm -when one of the arm's own issues in it is. The main metric is the number of -supported phenomena; the per-issue tally is kept beside it. +when one of the arm's own issues in it is; the per-issue tally is kept beside it. + +**Main metric.** The number of supported phenomena depends on where the +threshold sits when a correlation lies near it, so it is reported over a grid +of thresholds (:data:`RHO_GRID`, :func:`supported_curve`), and an arm found +more than another only where it has more supported phenomena at every +threshold of the grid. The reference threshold only names the phenomena table. """ from __future__ import annotations @@ -74,6 +88,8 @@ Metric, label_bound, outcome, + primary_readings, + restates_route, t_quantile, verdict, z_quantile, @@ -98,15 +114,16 @@ if TYPE_CHECKING: from evalrx.core.case import CaseBatch -VALIDATION_VERSION = "mvp4-validate-2" +VALIDATION_VERSION = "mvp4-validate-5" ALPHA = 0.05 #: A route signal is a difference of shares of cases: the band the CARDS use for shares. ROUTE_BAND = 0.1 ROUTE_CHECKS = {"H_label_free": "H", "N": "N", "U": "U"} -#: Steps that re-measure the check a route is cut on: their difference on that route is the cut. -DEFINITIONAL = {"self_consistency_n10": ("U", "S")} -#: Two reading issues of one route are one phenomenon at this pooled within-group |Spearman rho|. +#: Two reading issues of one route are one phenomenon at this pooled within-group |Spearman rho| (the +#: reference grouping, which names the phenomena table). SAME_PHENOMENON_RHO = 0.5 +#: The grouping thresholds the main metric is reported over. +RHO_GRID = (0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7) #: Paired cases a group needs before it enters that correlation. MIN_PAIRED = 5 VERDICT_ORDER = ("supported", "refuted", "inconclusive", "unavailable") @@ -139,7 +156,7 @@ def source_key(case: Any) -> str: class PartitionBundle: """The data roles of one protocol, fixed before the controller sees a case.""" - diagnostic_val_source: str # "internal" (from the main manifest) | "external" + diagnostic_val_source: str # "internal" (CONFIRM) | "internal+source" (plus a validation-only manifest) generalisation_unit: str # what a validated issue generalises to discovery_ids: list[str] validation_ids: list[str] @@ -149,6 +166,8 @@ class PartitionBundle: seed: int confirm_split: float manifest: dict[str, Any] = field(default_factory=dict) + validation_from: dict[str, int] = field(default_factory=dict) # validation cases by origin (confirm, source) + source_manifest: dict[str, Any] = field(default_factory=dict) # the validation-only manifest, when given roles: dict[str, Any] = field(default_factory=lambda: { "controller": "DISCOVERY", "judge": "DISCOVERY (route summaries only)", "validator": "DIAGNOSTIC_VALIDATION", "repair_confirm": None}) @@ -160,29 +179,53 @@ def to_dict(self) -> dict[str, Any]: return out +def _file_info(path: "str | Path | None") -> dict[str, Any]: + if path is None or not Path(path).is_file(): + return {} + return {"path": str(path), "sha1": hashlib.sha1(Path(path).read_bytes()).hexdigest()[:16]} + + def partition_bundle(discovery: "CaseBatch", confirm: "CaseBatch | None", *, seed: int, confirm_split: float, - manifest: "str | Path | None" = None) -> "tuple[PartitionBundle, CaseBatch]": - """DIAGNOSTIC_VALIDATION = CONFIRM minus the cases sharing a source with DISCOVERY.""" + manifest: "str | Path | None" = None, source: "CaseBatch | None" = None, + source_manifest: "str | Path | None" = None) -> "tuple[PartitionBundle, CaseBatch]": + """DIAGNOSTIC_VALIDATION = CONFIRM minus the cases sharing a source with DISCOVERY, plus the cases of + a validation-only *source* (a manifest the controller never sees) that share none with it either.""" from evalrx.core.case import CaseBatch seen = {source_key(c) for c in discovery} - kept, shared = [], 0 - for c in confirm or []: - if source_key(c) in seen: - shared += 1 - else: - kept.append(c) - info: dict[str, Any] = {} - if manifest is not None and Path(manifest).is_file(): - info = {"path": str(manifest), "sha1": hashlib.sha1(Path(manifest).read_bytes()).hexdigest()[:16]} + taken = {str(c.id) for c in discovery} | {str(c.id) for c in confirm or []} + kept: list = [] + excluded: dict[str, int] = {} + origin: dict[str, int] = {} + for name, batch in (("confirm", confirm), ("source", source)): + if batch is None: + continue + origin[name] = 0 + shared = "shares_a_source_with_discovery" if name == "confirm" else "source_shares_a_source_with_discovery" + excluded[shared] = 0 + for c in batch: + if source_key(c) in seen: + excluded[shared] += 1 + elif name == "source" and str(c.id) in taken: # a row the pool already holds, or a repeat: one id, one case + excluded["source_repeats_an_id"] = excluded.get("source_repeats_an_id", 0) + 1 + else: + kept.append(c) + origin[name] += 1 + if name == "source": + taken.add(str(c.id)) bundle = PartitionBundle( - diagnostic_val_source="internal", generalisation_unit="new media (no source shared with DISCOVERY)", + diagnostic_val_source="internal" if source is None else "internal+source", + generalisation_unit="new media (no source shared with DISCOVERY)", discovery_ids=[str(c.id) for c in discovery], validation_ids=[str(c.id) for c in kept], - excluded={"shares_a_source_with_discovery": shared}, + excluded=excluded, n_sources={"discovery": len(seen), "validation": len({source_key(c) for c in kept})}, rule=("DISCOVERY = EXPLORE; DIAGNOSTIC_VALIDATION = CONFIRM minus every case whose media content " - "also appears in DISCOVERY; repair CONFIRM: none (repair is out of scope)"), - seed=int(seed), confirm_split=float(confirm_split), manifest=info) + "also appears in DISCOVERY" + + ("; plus every case of the validation-only source whose media content does not" + if source is not None else "") + + "; repair CONFIRM: none (repair is out of scope)"), + seed=int(seed), confirm_split=float(confirm_split), manifest=_file_info(manifest), + validation_from=origin, source_manifest=_file_info(source_manifest)) return bundle, CaseBatch(kept) @@ -258,7 +301,7 @@ def freeze_issues(report: dict[str, Any], layers: "tuple[Layer, ...]" = LAYERS) "diff": round((f["rate"] or 0.0) - (p["rate"] or 0.0), 4), "ci95": ci})) for route, by_key in sorted((report.get("outcomes") or {}).items()): for key, by_field in sorted(by_key.items()): - if route in DEFINITIONAL.get(key, ()) or key not in CARDS: + if restates_route(route, key) or key not in CARDS: continue bands = {m.field: m for m in CARDS[key]} outside = [(f, o) for f, o in sorted(by_field.items()) @@ -410,14 +453,6 @@ def group_phenomena(family: list[IssueRecord], results: dict[str, dict[str, Any] """Connected groups of a route's reading issues whose validation values go together (see the module docstring); a route signal, or a reading without validation values, is a phenomenon of its own. Returns the phenomena and every within-route correlation computed (joined or not).""" - parent = {i.issue_id: i.issue_id for i in family} - - def root(x: str) -> str: - while parent[x] != x: - parent[x] = parent[parent[x]] - x = parent[x] - return x - links = [] readings = [i for i in family if i.kind == "reading" and i.issue_id in per_case] for n, a in enumerate(readings): @@ -426,14 +461,12 @@ def root(x: str) -> str: continue va, fail_ids, controls = per_case[a.issue_id] rho = within_group_rho(va, per_case[b.issue_id][0], [fail_ids, controls]) - if rho is None: - continue - links.append({"issues": [a.issue_id, b.issue_id], "rho": round(rho, 3)}) - if abs(rho) >= SAME_PHENOMENON_RHO: - parent[root(b.issue_id)] = root(a.issue_id) + if rho is not None: + links.append({"issues": [a.issue_id, b.issue_id], "rho": round(rho, 3)}) + root = _components([i.issue_id for i in family], links, SAME_PHENOMENON_RHO) groups: dict[str, list[IssueRecord]] = {} for i in family: - groups.setdefault(root(i.issue_id), []).append(i) + groups.setdefault(root[i.issue_id], []).append(i) out = [] for n, members in enumerate(groups.values(), 1): ids = {i.issue_id for i in members} @@ -444,6 +477,43 @@ def root(x: str) -> str: return out, links +def _components(ids: list[str], links: list[dict[str, Any]], threshold: float) -> dict[str, str]: + """Each issue's connected group, joining the issues of every link with ``|rho| >= threshold``.""" + parent = {i: i for i in ids} + + def root(x: str) -> str: + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + for lk in links: + if abs(lk["rho"]) >= threshold: + a, b = lk["issues"] + parent[root(b)] = root(a) + return {i: root(i) for i in ids} + + +def supported_curve(arms: dict[str, list[str]], verdicts: dict[str, str], links: list[dict[str, Any]], + grid: tuple[float, ...] = RHO_GRID) -> dict[str, Any]: + """Each arm's supported phenomena at every grouping threshold of *grid*, and the differences between + arms that hold at all of them (*arms*: issue ids per arm; *verdicts*: per issue of the family; + *links*: the within-route correlations). A difference that appears at some thresholds only says how + readings were grouped, not which arm found more.""" + curves: dict[str, list[int]] = {arm: [] for arm in arms} + for t in grid: + root = _components(list(verdicts), links, t) + for arm, ids in arms.items(): + own: dict[str, list[str]] = {} + for i in ids: + own.setdefault(root[i], []).append(verdicts[i]) + curves[arm].append(sum(1 for v in own.values() if "supported" in v)) + names = sorted(arms) + holds = [{"higher": a, "lower": b, "by": [x - y for x, y in zip(curves[a], curves[b])]} + for a in names for b in names if a != b and all(x > y for x, y in zip(curves[a], curves[b]))] + return {"grid": list(grid), "supported": curves, "differences": holds} + + def credit_arms(families: dict[str, list[IssueRecord]], results: dict[str, dict[str, Any]], phenomenon_of: dict[str, str], reports: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: """Each arm's own issues, grouped into phenomena: a phenomenon takes the best verdict among the @@ -495,18 +565,23 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili union.setdefault(issue.issue_id, issue) family = sorted(union.values(), key=lambda i: (i.kind != "route_signal", i.route, i.step, i.reading)) k = max(1, len(family)) - level = 1 - ALPHA / k + level = 1 - 2 * ALPHA / k # one-sided at ALPHA / K on the claimed side n_disc = len(discovery) fail_rate = sum(1 for c in discovery if getattr(getattr(c, "label", None), "value", None) == "fail") / max(1, n_disc) plan = plan_validation(family, list(reports.values()), n_validation=len(validation), discovery_fail_rate=fail_rate, level=level) frozen = {"version": VALIDATION_VERSION, "alpha": ALPHA, "k": k, "level": level, + "test": "one-sided at alpha/K on the claimed side of each issue (and of each primary prediction)", "family": [i.to_dict() for i in family], "plan": plan, "arms": {arm: [i.issue_id for i in issues] for arm, issues in families.items()}, "phenomenon_rule": {"statistic": "pooled within-group Spearman rho of the per-case values on the " "validation FAIL cases and on their controls, same route", - "threshold": SAME_PHENOMENON_RHO, "min_paired_per_group": MIN_PAIRED}, - "partition": bundle.to_dict() if bundle is not None else None} + "threshold": SAME_PHENOMENON_RHO, "min_paired_per_group": MIN_PAIRED, + "grid": list(RHO_GRID), + "comparison": "an arm found more than another only where its supported " + "phenomena are more at every threshold of the grid"}, + "partition": bundle.to_dict() if bundle is not None else None, + "explanations": live_explanations(reports)} frozen["sha1"] = hashlib.sha1(json.dumps(frozen, sort_keys=True, default=str).encode()).hexdigest()[:16] (out / "frozen.json").write_text(json.dumps(frozen, indent=2, default=str) + "\n", encoding="utf-8") say(f"[validate] froze {k} issue(s) from {len(families)} arm(s) (sha1 {frozen['sha1']}); level {level:.4f}") @@ -524,7 +599,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili run.run_step(step, list(draw.case_ids), kind="validation", revision=0) records = triage_cases(sample, run.evidence, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, - answer_fn=answer_fn) + answer_fn=answer_fn, stratum=stratum) rank_of = partial(rank, seed) by_rule = {x.rule_id: x for x in layers} steps = {s.name: s for s in (*battery, *candidate_steps(layers))} @@ -571,10 +646,27 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili "ci95": o95.get("ci95"), "verdict": _verdict(issue.direction, o["ci95"], issue.band)} say(f"[validate] verdicts: {dict(Counter(r['verdict'] for r in results.values()))}") + # a live explanation's primary predictions can name steps no issue ran on its route: run those too, + # on the route's validation FAIL cases and controls, so every mechanism claim meets new cases + for route, key in sorted({(h["route"], step) for rows in frozen["explanations"].values() for h in rows + for step, _ in h["primary"]}): + if (route, key) in measured or key not in steps or restates_route(route, key): + continue + layer = _layer_for(route, key, layers) + fail_ids = route_fail_ids(records, route, layer.case_filter if layer is not None else None) + controls = matched_controls(records, fail_ids, rank_of)[0] + if len(fail_ids) < MIN_N or len(controls) < MIN_N: + continue + run.run_step(steps[key], [*fail_ids, *controls], kind="validation", revision=0, route=route) + ev = run.evidence.get(key) + if ev is not None and ev.chunks and ev.refused() is None: + measured[(route, key)] = (fail_ids, controls) + phenomena, links = group_phenomena(family, results, per_case) phenomenon_of = {i: ph["id"] for ph in phenomena for i in ph["issues"]} say(f"[validate] {len(phenomena)} phenomena: {dict(Counter(ph['verdict'] for ph in phenomena))}") credit = credit_arms(families, results, phenomenon_of, reports) + curve = supported_curve(frozen["arms"], {i: r["verdict"] for i, r in results.items()}, links) report = { "version": VALIDATION_VERSION, "frozen_sha1": frozen["sha1"], "alpha": ALPHA, "k": k, "level": level, "partition": frozen["partition"], @@ -584,9 +676,11 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili "phenomena": phenomena, "phenomenon_links": links, "arms": credit, - "explanations": _check_explanations(reports, run, measured, answer_fn), + "phenomenon_curve": curve, + "explanations": _check_explanations(frozen["explanations"], run, measured, answer_fn), "cost": {"charged_sec": round(run.charged("wall_sec"), 3), "executions": len(run.executions)}, - "_note": ("each issue's interval is at 1 - alpha/K (Bonferroni over the K issues of the family); ci95 " + "_note": ("each issue's interval is at 1 - 2 alpha/K: a one-sided test at alpha/K on its claimed side " + "(Bonferroni over the K issues of the family); ci95 " "is the unadjusted interval, for reference. Verdicts: supported = inside the claimed region, " "refuted = outside it, inconclusive = neither, unavailable = the step or the cases were missing. " "A phenomenon is supported for an arm when one of the arm's own issues in it is"), @@ -596,47 +690,79 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili return report -def _check_explanations(reports: dict[str, dict[str, Any]], run: Any, measured: dict[tuple[str, str], Any], - answer_fn: Any) -> dict[str, Any]: - """The predictions of each arm's explanations live at its stop, checked on the validation evidence - where it exists (mechanism claims: reported, not counted).""" - out: dict[str, Any] = {} +def live_explanations(reports: dict[str, dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: + """Each arm's explanations still live at its stop, with their predictions (frozen with the family).""" + out: dict[str, list[dict[str, Any]]] = {} for arm, r in reports.items(): sets = ((r.get("explanations") or {}).get("sets")) or [] if not sets or not sets[-1]["hypotheses"]: continue last = sets[-1] + out[arm] = [{**{k: h[k] for k in ("id", "route", "claim", "predictions")}, + "primary": sorted(primary_readings(h))} for h in last["hypotheses"] + if last["final"][h["id"]]["state"] == "live"] + return out + + +def _check_explanations(explanations: dict[str, list[dict[str, Any]]], run: Any, + measured: dict[tuple[str, str], Any], answer_fn: Any) -> dict[str, Any]: + """The frozen live explanations, judged on the validation evidence of their route by their primary + predictions (mechanism claims: reported, not counted). + + The distinct primary predictions of all arms are one family: each is a one-sided test at + ``ALPHA / K_e`` (its interval at ``1 - 2 * ALPHA / K_e``). An explanation is ``supported`` when + every primary prediction hits, ``refuted`` when one misses, else ``undecided``; ``untestable`` + without a primary prediction off its route's cut. Other predictions are reported at 95%, + unadjusted, where their step ran anyway. A prediction on a reading the route is cut on is + ``definitional`` (never measured, neither support nor contradiction); any other stays ``not + measured`` only where its step could not run there (too few cases, the budget, or a refused + fidelity check).""" + tests = sorted({(h["route"], step, f, h["predictions"][step][f]) for hyps in explanations.values() + for h in hyps for step, f in h["primary"] if not restates_route(h["route"], step)}) + k_e = max(1, len(tests)) + level = 1 - 2 * ALPHA / k_e + arms: dict[str, Any] = {} + for arm, hyps in explanations.items(): rows = [] - for h in last["hypotheses"]: - if last["final"][h["id"]]["state"] != "live": - continue + for h in hyps: + primary = {tuple(x) for x in h["primary"]} preds = [] for step, by in sorted(h["predictions"].items()): for f, d in sorted(by.items()): + row = {"step": step, "reading": f, "predicted": d, "primary": (step, f) in primary} + if restates_route(h["route"], step): + # the route is cut on this reading: it can neither support nor contradict + preds.append({**row, "verdict": "definitional"}) + continue if (h["route"], step) not in measured: - preds.append({"step": step, "reading": f, "predicted": d, "verdict": "not measured"}) + preds.append({**row, "verdict": "not measured"}) continue fail_ids, controls = measured[(h["route"], step)] metric = next(m for m in CARDS[step] if m.field == f) ev = run.evidence[step] values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn) for cid in (*fail_ids, *controls)} - o = outcome(values, fail_ids, controls, metric) - preds.append({"step": step, "reading": f, "predicted": d, "observed": o.get("observed"), - "verdict": verdict(d, o.get("ci95"), metric.band)}) - rows.append({"id": h["id"], "claim": h["claim"], "predictions": preds, - "state": ("contradicted" if any(p["verdict"] == "miss" for p in preds) else - "consistent" if any(p["verdict"] == "hit" for p in preds) else "untested")}) - out[arm] = rows - return out + o = outcome(values, fail_ids, controls, metric, level=level if row["primary"] else 0.95) + preds.append({**row, "observed": o.get("observed"), "n": o.get("n"), "diff": o.get("diff"), + "ci": o.get("ci95"), "verdict": verdict(d, o.get("ci95"), metric.band)}) + decisive = [p for p in preds if p["primary"] and p["verdict"] != "definitional"] + state = ("untestable" if not decisive else + "refuted" if any(p["verdict"] == "miss" for p in decisive) else + "supported" if all(p["verdict"] == "hit" for p in decisive) else "undecided") + rows.append({"id": h["id"], "route": h["route"], "claim": h["claim"], "predictions": preds, + "state": state}) + arms[arm] = rows + return {"k": k_e, "level": level, "arms": arms} def markdown(report: dict[str, Any]) -> str: part = report.get("partition") or {} lines = [f"# Diagnostic validation ({report['version']})", "", f"Frozen family sha1 `{report['frozen_sha1']}`: {report['k']} issue(s), intervals at " - f"{report['level']:.4f} (Bonferroni, alpha {report['alpha']}).", + f"{report['level']:.4f} (one-sided Bonferroni, alpha {report['alpha']}).", f"Partition: {part.get('rule', '-')}; {len(part.get('validation_ids') or [])} validation cases " - f"({(part.get('excluded') or {})}); sample {len(report['sample']['fail_ids'])} FAIL + " + f"({(part.get('excluded') or {})}" + + (f"; from {part['validation_from']}" if part.get("validation_from") else "") + + f"); sample {len(report['sample']['fail_ids'])} FAIL + " f"{len(report['sample']['pass_ids'])} PASS. Validation cost {report['cost']['charged_sec']} s.", "", "## Issues", "", "| issue | phenomenon | claim | discovery | plan: expected / needed | validation " "| verdict |", "|---|---|---|---|---|---|---|"] @@ -657,12 +783,27 @@ def markdown(report: dict[str, Any]) -> str: lines.append(f"| {arm} | {c['n_phenomena']} | {c['phenomena_supported']} | {c['phenomena_refuted']} " f"| {c['phenomena_inconclusive']} | {c['phenomena_unavailable']} | {c['n_issues']} " f"| {c['supported']} | {c['charged_sec']} |") - if report.get("explanations"): - lines += ["", "## Explanations (mechanism claims: reported, not counted)", ""] - for arm, rows in report["explanations"].items(): + curve = report.get("phenomenon_curve") + if curve: + lines += ["", "## Supported phenomena over the grouping threshold (main metric)", "", + "| arm | " + " | ".join(f"{t:g}" for t in curve["grid"]) + " |", + "|---|" + "---:|" * len(curve["grid"])] + lines += [f"| {arm} | " + " | ".join(map(str, counts)) + " |" for arm, counts in curve["supported"].items()] + higher: dict[str, list[str]] = {} + for d in curve["differences"]: + higher.setdefault(d["higher"], []).append(d["lower"]) + lines += ["", "Differences that hold at every threshold: " + + ("; ".join(f"{a} > {', '.join(sorted(bs))}" for a, bs in sorted(higher.items())) if higher + else "none (every difference between arms depends on how readings are grouped).")] + expl = report.get("explanations") or {} + if expl.get("arms"): + lines += ["", "## Explanations (mechanism claims: reported, not counted)", "", + f"Judged by their primary predictions: {expl['k']} distinct test(s), one-sided at " + f"{expl['level']:.4f} (Bonferroni); other predictions at 95%, reported only.", ""] + for arm, rows in expl["arms"].items(): for h in rows: - checked = [f"{p['step']}.{p['reading']} {p['predicted']} -> {p['verdict']}" for p in h["predictions"] - if p["verdict"] != "not measured"] + checked = [("**primary** " if p["primary"] else "") + f"{p['step']}.{p['reading']} {p['predicted']} " + f"-> {p['verdict']}" for p in h["predictions"] if p["verdict"] != "not measured"] lines.append(f"- {arm} {h['id']} [{h['state']}]: {h['claim']} ({'; '.join(checked) or 'unmeasured'})") lines += ["", f"_{report['_note']}._", ""] return "\n".join(lines) diff --git a/evalrx/models/backends/hf/_util.py b/evalrx/models/backends/hf/_util.py index c8e8a46c..0817b654 100644 --- a/evalrx/models/backends/hf/_util.py +++ b/evalrx/models/backends/hf/_util.py @@ -12,6 +12,65 @@ logger = logging.getLogger(__name__) +#: attribute names HF multimodal models give their media encoders (vision / audio towers) +MEDIA_ENCODER_NAMES = ("visual", "vision_tower", "vision_model", "vision_encoder", "audio_tower", "audio_encoder") + + +def media_encoders(module: Any, hint: "str | None" = None) -> "list[tuple[str, Any]]": + """The media encoders of an HF multimodal *module*: its submodules named like a tower + (:data:`MEDIA_ENCODER_NAMES`), plus the dotted *hint* path a spec gives, each without + the ones nested inside another match; ``[]`` for a text-only model.""" + found = [(name, sub) for name, sub in module.named_modules() if name.rsplit(".", 1)[-1] in MEDIA_ENCODER_NAMES] + hinted = _read_nested_attr(module, hint, default=None) if hint else None + if hinted is not None and hasattr(hinted, "forward"): + found.append((hint, hinted)) + out: "list[tuple[str, Any]]" = [] + for name, sub in sorted(found, key=lambda t: (t[0].count("."), t[0])): + if any(sub is kept or name.startswith(prefix + ".") for prefix, kept in out): + continue + out.append((name, sub)) + return out + + +class media_encoders_without_grad: + """Run *module*'s media encoders under ``torch.no_grad`` while active. + + A gradient pass through the decoder (``CaptureSpec(with_grad=True)``) otherwise keeps the + encoders' graph too, since their parameters require grad: a vision tower's attention over + a 6000-patch image is tens of GB when kept for backward. The decoder analyzers differentiate + towards decoder activations only, so the encoders' outputs can enter the decoder as constants; + their values are unchanged. Each encoder's ``forward`` is shadowed on the instance for the + duration and restored after, also on an error. ``names`` lists what was wrapped. + """ + + def __init__(self, module: Any, hint: "str | None" = None) -> None: + self.module, self.hint = module, hint + self.names: list[str] = [] + self._previous: list = [] + + def __enter__(self) -> "media_encoders_without_grad": + import torch + + for name, encoder in media_encoders(self.module, self.hint): + original = encoder.forward + + def forward(*args: Any, _original: Any = original, **kwargs: Any) -> Any: + with torch.no_grad(): + return _original(*args, **kwargs) + + self._previous.append((encoder, "forward" in encoder.__dict__, encoder.__dict__.get("forward"))) + encoder.forward = forward + self.names.append(name) + return self + + def __exit__(self, *exc: Any) -> None: + for encoder, had, previous in reversed(self._previous): + if had: + encoder.forward = previous + else: + del encoder.forward # back to the class method + self._previous.clear() + def _read_nested_attr(obj: Any, attr_path: "str | None", *, default: Any) -> Any: """Walk a dotted attribute path on *obj*, returning *default* if any step is missing.""" diff --git a/evalrx/models/backends/hf/model.py b/evalrx/models/backends/hf/model.py index d2716677..db3fd43e 100755 --- a/evalrx/models/backends/hf/model.py +++ b/evalrx/models/backends/hf/model.py @@ -19,6 +19,7 @@ from __future__ import annotations import logging +from contextlib import nullcontext from typing import Any from evalrx.core.capability import Capability, CapabilityError @@ -35,6 +36,7 @@ _populate_audio_extras, _populate_vision_extras, _read_nested_attr, + media_encoders_without_grad, ) from evalrx.models.backends.hf.decoding import ContrastiveDecodingMixin from evalrx.models.backends.hf.specialists import SpecialistRepairsMixin @@ -613,8 +615,14 @@ def forward(self, inputs: Any, capture: set[Capability], spec=None) -> Trace: # GRADIENTS: CaptureSpec.with_grad keeps the graph so a caller can # differentiate the returned logits (pair it with to_cpu=False). Default # stays no_grad: an attention capture with a live graph costs gigabytes. + # The graph starts at the decoder: the media encoders run without one + # unless CaptureSpec.media_grad asks for it (a vision tower's attention + # over a large image, kept for backward, is tens of GB). with_grad = bool(spec is not None and getattr(spec, "with_grad", False)) - with torch.set_grad_enabled(with_grad): + media_grad = bool(spec is not None and getattr(spec, "media_grad", False)) + audio_hint = self.spec.audio.audio_tower if self.spec.audio is not None else None + encoders = media_encoders_without_grad(model, audio_hint) if with_grad and not media_grad else nullcontext() + with torch.set_grad_enabled(with_grad), encoders: outputs = model(**enc, **flags) layers = spec.layers if spec is not None else None diff --git a/tests/test_analyzers/test_intervention_analyzers.py b/tests/test_analyzers/test_intervention_analyzers.py index a6496c05..8c083d81 100644 --- a/tests/test_analyzers/test_intervention_analyzers.py +++ b/tests/test_analyzers/test_intervention_analyzers.py @@ -422,6 +422,36 @@ def test_generic_attention_contract(vlm): assert "spatial_map" in result.artifacts +def _out_of_memory_on(vlm, monkeypatch, prompt: str): + """The model raises CUDA's out-of-memory error on the gradient pass of one case.""" + real = vlm.forward + + def forward(inputs, capture, spec=None): + if spec is not None and getattr(spec, "with_grad", False) and inputs.prompt == prompt: + raise torch.cuda.OutOfMemoryError("CUDA out of memory (test)") + return real(inputs, capture, spec) + + monkeypatch.setattr(vlm, "forward", forward) + + +@pytest.mark.parametrize("name", ["gradcam", "generic_attention"]) +def test_a_case_whose_graph_does_not_fit_is_skipped_and_the_rest_are_measured(vlm, monkeypatch, name): + from evalrx.analyzers.attribution.generic_attn import GenericAttentionExplainability + from evalrx.analyzers.attribution.gradcam import GradCAMAnalyzer + + batch = _batch() + victim = list(batch)[1] + _out_of_memory_on(vlm, monkeypatch, victim.inputs.prompt) + analyzer = GradCAMAnalyzer() if name == "gradcam" else GenericAttentionExplainability() + result = analyzer.run(vlm, batch) + f = result.findings + assert f["n_cases_analyzed"] == 3 and f["skip_reasons"] == {"out_of_memory": 1} + assert victim.id not in {r["sample_id"] for r in f["per_case"]} + assert victim.id not in result.artifacts["per_case_maps"] and len(result.artifacts["per_case_maps"]) == 3 + if name == "generic_attention": + assert f["tap_fidelity"]["tap_faithful"] is True # the tap was restored around the failed case + + def test_generic_attention_runs_text_only(vlm): from evalrx.analyzers.attribution.generic_attn import GenericAttentionExplainability diff --git a/tests/test_eval_agent/test_probing_alternatives.py b/tests/test_eval_agent/test_probing_alternatives.py index ba44ac24..54dd6e93 100644 --- a/tests/test_eval_agent/test_probing_alternatives.py +++ b/tests/test_eval_agent/test_probing_alternatives.py @@ -58,7 +58,12 @@ def generate(self, prompt): ctx = json.loads(prompt[prompt.index("Evidence (JSON):") + len("Evidence (JSON):"):]) routes = {} for route, r in ctx["routes"].items(): - routes[route] = [{"id": f"h{i}", "claim": f"claim {i}", + if not r["to_run"]: + continue + # they stand on the alternatives' first readings (without one offered they cannot be told apart) + alts = [[c["step"], c["readings"][0]["field"]] for c in r["to_run"] if c.get("alternative_to")] + primary = alts[:2] or [[r["to_run"][0]["step"], r["to_run"][0]["readings"][0]["field"]]] + routes[route] = [{"id": f"h{i}", "claim": f"claim {i}", "primary": primary, "predictions": {c["step"]: {c["readings"][0]["field"]: d if c.get("alternative_to") else "same"} for c in r["to_run"]}} for i, d in enumerate(("up", "same"), 1)] diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index d55d5251..ba1ab540 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -251,6 +251,23 @@ def test_few_answer_tasks_test_n_only_with_counterfactual_donors(): assert donors["fail"]["counterfactual_followed_donor"] == 1 and donors["pass"]["content"] == 1 +def test_open_answer_records_match_controls_without_the_gold_answer(): + from evalrx.eval_agent.probing.rules import matched_controls + + cases = CaseBatch([ + FailureCase(id="f1", inputs=Inputs(prompt="q1"), expected="1.577", observed="1.5", label=Label.FAIL), + FailureCase(id="f2", inputs=Inputs(prompt="q2"), expected="Taiwan", observed="China", label=Label.FAIL), + FailureCase(id="p1", inputs=Inputs(prompt="q3"), expected="47", observed="47", label=Label.PASS), + FailureCase(id="p2", inputs=Inputs(prompt="q4"), expected="2019", observed="2019", label=Label.PASS), + ]) + gold = triage_cases(cases, {}, host_assumed_finish=True, answer_contract=False) + assert matched_controls(gold, ["f1", "f2"], str) == ([], {"1.577": 1, "taiwan": 1}) + # the sampler's rule for open answers: every PASS case can be a FAIL case's control + none = triage_cases(cases, {}, host_assumed_finish=True, answer_contract=False, stratum="none") + assert {r["stratum"] for r in none} == {"all"} + assert matched_controls(none, ["f1", "f2"], str) == (["p1", "p2"], {}) + + def test_triage_truncation_counts_when_the_backend_reported_it(): cases = CaseBatch([FailureCase(id="f", inputs=Inputs(prompt="q"), expected="1", observed="1 2 3", label=Label.FAIL, metadata={"finish_reason": "length"})]) @@ -335,7 +352,9 @@ def _yn_case(cid, label, gold, observed): def test_u_needs_both_parts_and_s_is_a_fully_checked_stable_failure(): cases = CaseBatch([ _yn_case("s", Label.FAIL, "Yes", "No"), # every check clear -> S - _yn_case("u", Label.FAIL, "Yes", "No"), # one sample says Yes -> U + _yn_case("u", Label.FAIL, "Yes", "No"), # most samples say Yes -> U + _yn_case("m", Label.FAIL, "Yes", "No"), # one sample says Yes: noise, the Stage-0 answer is modal -> S + _yn_case("t", Label.FAIL, "Yes", "No"), # a tie with the Stage-0 answer stays clear -> S _yn_case("w", Label.FAIL, "Yes", "No"), # a wrapper flips it -> U _yn_case("i", Label.FAIL, "Yes", "No"), # wrappers unreadable -> invalid controls -> X _yn_case("p", Label.PASS, "Yes", "Yes"), # every check clear -> stable control, no route @@ -343,17 +362,22 @@ def test_u_needs_both_parts_and_s_is_a_fully_checked_stable_failure(): ids = [c.id for c in cases] obs = _clean_h_and_n(ids, {i: "No" if i == "p" else "Yes" for i in ids}) obs.update(_u_obs( - samples={"s": ["No"] * 5, "u": ["No", "Yes, there is", "No", "no", "No."], "w": ["No"] * 5, - "i": ["No"] * 5, "p": ["Yes"] * 4 + ["I cannot tell"]}, - reworded={"s": ["No", "No.", "no"], "u": ["No", "No", "No"], "w": ["No", "Yes", "No"], - "i": ["No", "Maybe", "Hard to say"], "p": ["Yes", "Yes", "Yes"]}, + samples={"s": ["No"] * 5, "u": ["Yes", "Yes, there is", "No", "yes", "No."], + "m": ["No", "Yes, there is", "No", "no", "No."], "t": ["No", "Yes", "no", "yes", "I cannot tell"], + "w": ["No"] * 5, "i": ["No"] * 5, "p": ["Yes"] * 4 + ["I cannot tell"]}, + reworded={"s": ["No", "No.", "no"], "u": ["No", "No", "No"], "m": ["No", "No", "No"], "t": ["No", "No", "No"], + "w": ["No", "Yes", "No"], "i": ["No", "Maybe", "Hard to say"], "p": ["Yes", "Yes", "Yes"]}, gen_kwargs={"temperature": 1.0})) rec = {r["case_id"]: r for r in triage_cases(cases, obs, host_assumed_finish=True, answer_contract=True, n_needs_counterfactual=True, answer_fn=_yes_no)} assert rec["s"]["routes"] == ["S"] and rec["s"]["stable"] sampling, reword = rec["u"]["U"]["parts"] - assert sampling["state"] == "fired" and sampling["agreement"] == 0.8 and sampling["answers"] == {"no": 4, "yes": 1} + assert sampling["state"] == "fired" and sampling["agreement"] == 0.4 and sampling["answers"] == {"yes": 3, "no": 2} assert rec["u"]["routes"] == ["U"] + minority, tie = rec["m"]["U"]["parts"][0], rec["t"]["U"]["parts"][0] + assert minority["state"] == "clear" and minority["agreement"] == 0.8 and minority["base_is_modal"] + assert tie["state"] == "clear" and tie["answers"] == {"no": 2, "yes": 2} + assert rec["m"]["routes"] == rec["t"]["routes"] == ["S"] assert rec["w"]["routes"] == ["U"] and rec["w"]["U"]["parts"][1]["changed"] == ["question_frame"] assert rec["i"]["routes"] == ["X"] and rec["i"]["U"]["parts"][1]["invalid_controls"] == [ "instruction_frame", "question_frame"] @@ -362,8 +386,8 @@ def test_u_needs_both_parts_and_s_is_a_fully_checked_stable_failure(): assert rec["p"]["U"]["parts"][0]["n_unreadable"] == 1 and rec["p"]["U"]["state"] == "clear" assert rec["p"]["routes"] == [] and rec["p"]["stable"] s = summarize(list(rec.values())) - assert s["S"] == {"fail": 1, "stable_pass": 1} and s["X"] == {"fail": 1, "pass": 0} - assert s["U"]["fail"] == {"n": 4, "n_tested": 3, "n_fired": 2, "rate": 0.6667} + assert s["S"] == {"fail": 3, "stable_pass": 1} and s["X"] == {"fail": 1, "pass": 0} + assert s["U"]["fail"] == {"n": 6, "n_tested": 5, "n_fired": 2, "rate": 0.4} # greedy sampling settings: the sampling part is untested, so nothing becomes S obs.update(_u_obs(samples={i: ["No"] * 5 for i in ids}, reworded={i: ["No"] * 3 for i in ids}, gen_kwargs={})) diff --git a/tests/test_eval_agent/test_probing_mvp3b.py b/tests/test_eval_agent/test_probing_mvp3b.py index bcece3d3..1fdf2094 100644 --- a/tests/test_eval_agent/test_probing_mvp3b.py +++ b/tests/test_eval_agent/test_probing_mvp3b.py @@ -122,31 +122,55 @@ def test_check_contradicts_on_a_miss_and_calls_an_explanation_without_prediction assert states["S.h1"]["predictions"][0]["verdict"] == "hit" -def test_parse_keeps_offered_steps_card_readings_and_directions_and_drops_duplicates(): +def test_parse_keeps_offered_steps_card_readings_directions_and_competing_explanations_with_primaries(): offered = {"S": {"gradcam": ["gc_top5_share", "gc_entropy"]}, "N": {"attention_temperature": ["tt_slope"]}} reply = "```json\n" + json.dumps({"routes": { - "S": [{"id": "h1", "claim": "concentrated off target", "predictions": { - "gradcam": {"gc_top5_share": "↑", "gc_entropy": "sideways", "gc_margin": "up"}, - "patchscope": {"ps_late_drop": "up"}}}, - {"id": "h2", "claim": "same as h1, reworded", "predictions": {"gradcam": {"gc_top5_share": "up"}}}, - {"id": "h3", "claim": "diffuse", "predictions": {"gradcam": {"gc_entropy": "up"}}}, - {"id": "h4", "claim": "nothing to say", "predictions": {"gradcam": {"gc_entropy": "unknown"}}}], + "S": [{"id": "h1", "claim": "concentrated off target", "primary": [["gradcam", "gc_top5_share"]], + "predictions": {"gradcam": {"gc_top5_share": "↑", "gc_entropy": "sideways", "gc_margin": "up"}, + "patchscope": {"ps_late_drop": "up"}}}, + {"id": "h2", "claim": "same as h1, reworded", "primary": [["gradcam", "gc_top5_share"]], + "predictions": {"gradcam": {"gc_top5_share": "up"}}}, + {"id": "h3", "claim": "diffuse", "primary": [["gradcam", "gc_entropy"], ["gradcam", "gc_margin"]], + "predictions": {"gradcam": {"gc_entropy": "up", "gc_top5_share": "down"}}}, + {"id": "h4", "claim": "no primary named", "predictions": {"gradcam": {"gc_entropy": "down"}}}, + {"id": "h5", "claim": "a third that competes", "primary": [["gradcam", "gc_top5_share"]], + "predictions": {"gradcam": {"gc_top5_share": "same"}}}], "U": [{"id": "h1", "claim": "not offered"}], "N": [{"claim": ""}]}}) + "\n```" hyps, dropped = parse(reply, offered, max_per_route=2) - assert [(h.id, h.predictions) for h in hyps] == [("S.h1", {"gradcam": {"gc_top5_share": "up"}}), - ("S.h3", {"gradcam": {"gc_entropy": "up"}})] + assert [(h.id, h.predictions, h.primary) for h in hyps] == [ + ("S.h1", {"gradcam": {"gc_top5_share": "up"}}, (("gradcam", "gc_top5_share"),)), + # told apart from h1 on h1's primary reading, which h3 also predicts + ("S.h3", {"gradcam": {"gc_entropy": "up", "gc_top5_share": "down"}}, (("gradcam", "gc_entropy"),))] reasons = {d["what"]: d["reason"] for d in dropped} assert reasons["route U"] == "not offered" and reasons["N[0]"] == "no claim" assert reasons["S.h1 gradcam.gc_entropy"] == "direction 'sideways'" assert reasons["S.h1 gradcam.gc_margin"] == "reading not on the card" assert reasons["S.h1 patchscope"] == "step not offered on this route" - assert "same explicit predictions" in reasons["S.h2"] and "more than 2" in reasons["S.h4"] + assert "cannot be told apart from S.h1" in reasons["S.h2"] + assert reasons["S.h3 primary ['gradcam', 'gc_margin']"] == "not one of its explicit predictions" + assert "no primary prediction" in reasons["S.h4"] and "more than 2" in reasons["S.h5"] assert parse("no json here", offered, 3) == ([], [{"what": "reply", "reason": parse("no json here", offered, 3)[1][0]["reason"]}]) assert parse(json.dumps({"x": 1}), offered, 3)[1] == [{"what": "reply", "reason": "no 'routes' object"}] +def test_only_primary_predictions_decide_and_conflict(): + a = Hypothesis("S.h1", "S", "a", {"gradcam": {"gc_top5_share": "up", "gc_entropy": "down"}}, + primary=(("gradcam", "gc_top5_share"),)) + b = Hypothesis("S.h2", "S", "b", {"gradcam": {"gc_top5_share": "same", "gc_entropy": "up"}}, + primary=(("gradcam", "gc_top5_share"),)) + seen = {"gc_top5_share": {"n": [17, 17], "ci95": [0.2, 0.4], "observed": "up"}, + "gc_entropy": {"n": [17, 17], "ci95": [0.2, 0.4], "observed": "up"}} + states = check([a, b], lambda route, step, m: seen[m.field]) + # a's secondary gc_entropy misses, but only its primary decides; b's primary misses + assert states["S.h1"]["state"] == "live" and states["S.h2"]["state"] == "contradicted" + assert [(p["reading"], p["primary"], p["verdict"]) for p in states["S.h1"]["predictions"]] == [ + ("gc_entropy", False, "miss"), ("gc_top5_share", True, "hit")] + # the pair conflicts on both readings, but D counts only the primary one + assert disagreement("S", "gradcam", [a, b])[1]["conflicting"][0]["readings"] == ["gc_top5_share"] + + def test_every_card_reading_names_its_band_and_kind(): for key, metrics in CARDS.items(): assert metrics and len({m.field for m in metrics}) == len(metrics), key @@ -154,10 +178,11 @@ def test_every_card_reading_names_its_band_and_kind(): class _Judge: - """Two explanations per route that disagree on the first reading of every offered step.""" + """Two explanations per route that disagree on the first reading of every offered step; they stand + on the steps named in *primary* where offered, else on the first offered step (one to run first).""" - def __init__(self, fail=False): - self.prompts, self.fail = [], fail + def __init__(self, fail=False, primary=()): + self.prompts, self.fail, self.primary = [], fail, set(primary) def generate(self, prompt): self.prompts.append(prompt) @@ -166,10 +191,13 @@ def generate(self, prompt): ctx = json.loads(prompt[prompt.index("Evidence (JSON):") + len("Evidence (JSON):"):]) routes = {} for route, r in ctx["routes"].items(): - up = {c["step"]: {c["readings"][0]["field"]: "up"} for c in r["to_run"]} - same = {c["step"]: {c["readings"][0]["field"]: "same"} for c in r["to_run"]} - routes[route] = [{"id": "h1", "claim": "it moves", "predictions": up}, - {"id": "h2", "claim": "it does not", "predictions": same}] + steps = r["to_run"] + r.get("already_run", []) + up = {c["step"]: {c["readings"][0]["field"]: "up"} for c in steps} + same = {c["step"]: {c["readings"][0]["field"]: "same"} for c in steps} + on = [c for c in steps if c["step"] in self.primary] or steps[:1] + primary = [[c["step"], c["readings"][0]["field"]] for c in on[:2]] + routes[route] = [{"id": "h1", "claim": "it moves", "predictions": up, "primary": primary}, + {"id": "h2", "claim": "it does not", "predictions": same, "primary": primary}] return json.dumps({"routes": routes}) @@ -232,19 +260,23 @@ def test_scored_run_asks_once_the_sample_settles_and_resumes_without_asking(tmp_ for d in report["decisions"]] -def test_a_decided_prediction_that_thins_a_route_asks_the_judge_again(tmp_path, monkeypatch): +def _wrapper_on_s(monkeypatch): + """The layers with an S step the table model ignores: prompt_sensitivity is 0 on every case, so an + "up" prediction on it misses at once.""" from evalrx.eval_agent.probing import LAYERS from evalrx.eval_agent.probing.actions import PlanStep from evalrx.eval_agent.probing.rules import Layer - # the table model ignores wrappers: prompt_sensitivity is 0 on every case, so "up" misses at once monkeypatch.setitem(CARDS, "wrapped", (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) step = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "w": "Q: {prompt}"}}, "Z1", "re-ask inside a wrapper", key="wrapped") at = next(i for i, x in enumerate(LAYERS) if x.rule_id == "Sb") - layers = (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (step,)), *LAYERS[at:]) - judge = _Judge() - report = _explained(tmp_path / "a", judge, layers=layers) + return (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (step,)), *LAYERS[at:]) + + +def test_a_decided_prediction_that_thins_a_route_asks_the_judge_again(tmp_path, monkeypatch): + judge = _Judge(primary={"wrapped"}) + report = _explained(tmp_path / "a", judge, layers=_wrapper_on_s(monkeypatch)) first, second = report["explanations"]["sets"] assert len(judge.prompts) == 2 and "settled" in first["reason"] and "fewer than two live" in second["reason"] assert first["final"]["S.h1"]["state"] == "contradicted" and first["final"]["S.h2"]["state"] == "live" @@ -252,6 +284,26 @@ def test_a_decided_prediction_that_thins_a_route_asks_the_judge_again(tmp_path, assert {p["id"]: p["state"] for p in previous}["S.h1"] == "contradicted" # what ran is shown to the judge as measured (still offered while chunks of it are left) assert "wrapped" in second["seen"]["S"] + # the re-ask adds to what is still live: S.h2 is kept, the judge's new "up" explanation takes a fresh id + # (S.h1 was the contradicted one), and its repeat of S.h2 does not compete with it + assert second["carried"] == ["N.h1", "N.h2", "S.h2"] + assert [h["id"] for h in second["hypotheses"]] == ["N.h1", "N.h2", "S.h2", "S.h3"] + assert "cannot be told apart from S.h2" in {d["what"]: d["reason"] for d in second["dropped"]}["S.h2"] + + +def test_a_route_left_with_only_steps_the_judge_is_not_asked_about_does_not_ask_again(tmp_path, monkeypatch): + import evalrx.eval_agent.probing.controller as controller + + judge = _Judge(primary={"wrapped"}) + # every S step re-measures S's cut here, the wrapper too once the judge has been asked: after the + # first ask S has tools left (the wrapper's other chunks among them), but none the judge could be + # asked to predict, so the wrapper contradicting S.h1 asks nothing + monkeypatch.setattr(controller, "restates_route", + lambda route, step: route == "S" and (step != "wrapped" or bool(judge.prompts))) + report = _explained(tmp_path / "a", judge, layers=_wrapper_on_s(monkeypatch)) + (only,) = report["explanations"]["sets"] + assert len(judge.prompts) == 1 and only["final"]["S.h1"]["state"] == "contradicted" + assert set(only["offered"]["S"]) == {"wrapped"} def test_a_failed_judge_call_leaves_D_at_zero_and_the_run_completes(tmp_path): @@ -335,7 +387,7 @@ def test_a_judge_call_is_asked_only_while_its_estimate_fits_the_budget(tmp_path, layers = (*LAYERS[:at], Layer("Z1", "S", "does a wrapper move it", (step,)), *LAYERS[at:]) def run(out, budget): - explainer = _SlowExplainer(_Judge(), identity={"provider": "stub", "model": "slow"}) + explainer = _SlowExplainer(_Judge(primary={"wrapped"}), identity={"provider": "stub", "model": "slow"}) return run_triage(_Table(_pope_like()[1]), _pope_like()[0], **_kw(tmp_path / out, max_fail=8, min_route_fail=1, scheduler="scored", layers=layers, explainer=explainer, budget_sec=budget)) @@ -347,3 +399,73 @@ def run(out, budget): # the first call's cost is unknown, so it may overshoot by one call; a later one is not # made unless the largest call so far fits assert r["cost"]["charged"]["wall_sec"] - budget <= 100.0 if asks == 1 else r["cost"]["charged"]["wall_sec"] <= budget + + +class _Wavering(_Table): + """A wrong answer flips inside a neutral wrapper: those FAIL cases are on route U.""" + + def generate(self, inputs, **kwargs): + ans = super().generate(inputs, **kwargs) + wrapped = str(inputs.prompt).startswith(("Question:", "Answer the following question")) + wrong = self.wrong.get((next((q for q, img in self.table if q in str(inputs.prompt)), None), inputs.image)) + return ("Yes" if ans == "No" else "No") if wrapped and wrong else ans + + +def _wavering(out): + cases, table = _pope_like() + model = _Wavering(table) + model.wrong = {(c.inputs.prompt, c.inputs.image): c.label.value == "fail" for c in cases} + judge = _Judge() + report = run_triage(model, cases, **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored", + explainer=Explainer(judge, identity={"provider": "stub", "model": "stub"}))) + return report, judge + + +def _offered_on(out): + _, judge = _wavering(out) + asked: dict[str, set] = {} + for p in judge.prompts: + for route, r in json.loads(p[p.index("Evidence (JSON):") + 16:])["routes"].items(): + asked.setdefault(route, set()).update(c["step"] for c in r["to_run"] + r["already_run"]) + return asked + + +def test_the_judge_is_not_asked_to_predict_the_check_a_route_is_cut_on(tmp_path, monkeypatch): + import evalrx.eval_agent.probing.controller as controller + + with monkeypatch.context() as m: + m.setattr(controller, "restates_route", lambda route, step: False) + assert "self_consistency_n10" in _offered_on(tmp_path / "unfiltered")["U"] # U1's candidate here + # filtered, U has nothing left to run here, and is explained on the tools already run on it + assert "self_consistency_n10" not in _offered_on(tmp_path / "filtered").get("U", set()) + + +def test_a_route_with_nothing_left_to_run_is_explained_on_the_tools_already_run(tmp_path): + from evalrx.eval_agent.probing.explanations import restates_route + + report, judge = _wavering(tmp_path / "w") + (prompt,) = judge.prompts + u = json.loads(prompt[prompt.index("Evidence (JSON):") + 16:])["routes"]["U"] + assert not u["to_run"] and u["already_run"] + assert {c["step"] for c in u["already_run"]} == {k for k in u["measured"] if not restates_route("U", k)} + (asked,) = report["explanations"]["sets"] + explained = [h for h in asked["hypotheses"] if h["route"] == "U"] + # kept, standing on readings the judge saw: a fit here, a test only on new cases + assert len(explained) == 2 and all(step in asked["seen"]["U"] for h in explained for step, _ in h["primary"]) + # nothing on U is run again, so they give no D + assert not any(c["route"] == "U" and c["D"] > 0 for d in report["decisions"] for c in d.get("candidates") or []) + + +def test_a_new_ask_keeps_the_live_explanations_and_adds_only_competing_ones(): + from evalrx.eval_agent.probing.explanations import carry_over + + on = (("gradcam", "gc_top5_share"),) + kept = [Hypothesis("S.h2", "S", "flat", {"gradcam": {"gc_top5_share": "same"}}, primary=on)] + new = [Hypothesis("S.h1", "S", "peaked", {"gradcam": {"gc_top5_share": "up"}}, primary=on), + Hypothesis("S.h2", "S", "flat again", {"gradcam": {"gc_top5_share": "same"}}, primary=on), + Hypothesis("N.h1", "N", "another route", {"gradcam": {"gc_top5_share": "same"}}, primary=on)] + out, dropped = carry_over(kept, new, taken={"S.h1", "S.h2"}) + # S.h1 was an earlier explanation's id: the new one is renumbered; another route is not compared + assert [(h.id, h.claim) for h in out] == [("S.h2", "flat"), ("S.h3", "peaked"), ("N.h1", "another route")] + assert dropped == [{"what": "S.h2", "reason": "cannot be told apart from S.h2 (kept from the last ask) on a " + "primary prediction"}] diff --git a/tests/test_eval_agent/test_probing_validation.py b/tests/test_eval_agent/test_probing_validation.py index d855d37d..5fa511cf 100644 --- a/tests/test_eval_agent/test_probing_validation.py +++ b/tests/test_eval_agent/test_probing_validation.py @@ -33,6 +33,7 @@ group_phenomena, partition_bundle, source_key, + supported_curve, validate, within_group_rho, ) @@ -57,6 +58,35 @@ def test_the_partition_keeps_every_validation_case_off_the_media_discovery_saw() assert len(bundle.validation_ids) + bundle.excluded["shares_a_source_with_discovery"] == len(confirm) assert bundle.excluded["shares_a_source_with_discovery"] > 0 # a POPE image has a yes and a no question assert bundle.roles["repair_confirm"] is None and bundle.to_dict()["sha1"] == bundle.to_dict()["sha1"] + assert bundle.diagnostic_val_source == "internal" and bundle.validation_from == {"confirm": len(validation)} + + +def test_a_validation_only_source_joins_the_validation_cases_under_the_same_media_rule(tmp_path): + from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label + + cases, _, explore, confirm = _split() + seen = sorted({c.inputs.image for c in explore})[:3] + (taken,) = [str(c.id) for c in confirm][:1] + source = CaseBatch([ + FailureCase(id=f"s{i}" if img != "repeat" else taken, expected="Yes", observed="No", label=Label.FAIL, + inputs=Inputs(prompt="Is there a dog in the image?", image="new9" if img == "repeat" else img), + metadata={"gold": "Yes", "finish_reason": "stop"}) + for i, img in enumerate([*seen, "new0", "new1", "new2", "new3", "repeat"])]) + manifest = tmp_path / "manifest.json" + manifest.write_text("[]") + base, _ = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) + bundle, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5, source=source, + source_manifest=manifest) + # the confirm half is unchanged; the source adds its cases on media discovery never saw, once per id + assert bundle.validation_ids[:len(base.validation_ids)] == base.validation_ids + assert bundle.validation_ids[len(base.validation_ids):] == ["s3", "s4", "s5", "s6"] + assert bundle.excluded == {"shares_a_source_with_discovery": base.excluded["shares_a_source_with_discovery"], + "source_shares_a_source_with_discovery": 3, "source_repeats_an_id": 1} + assert bundle.validation_from == {"confirm": len(base.validation_ids), "source": 4} + assert not {source_key(c) for c in validation} & {source_key(c) for c in explore} + assert bundle.diagnostic_val_source == "internal+source" and "validation-only source" in bundle.rule + assert bundle.source_manifest["path"] == str(manifest) and bundle.manifest == {} + assert bundle.to_dict()["sha1"] != base.to_dict()["sha1"] def _outcome(observed, ci, n=(8, 8), diff=None): @@ -75,14 +105,16 @@ def test_freezing_keeps_what_clears_the_band_one_issue_per_route_and_step(): "gc_top5_share": _outcome("up", [0.1, 0.4]), "gc_media_grad_share": _outcome("undetermined", [-0.1, 0.2])}, "self_consistency_n10": {"consistency": _outcome("up", [0.2, 0.4])}}, - "U": {"logprob_entropy": {"mean_top_entropy": _outcome("up", [0.1, 0.25])}}, + "U": {"logprob_entropy": {"mean_top_entropy": _outcome("up", [0.1, 0.25])}, + "patchscope": {"ps_peak_prob": _outcome("down", [-0.3, -0.1])}}, "X": {"media_drop": {"grounded_in_image": _outcome("up", [0.3, 0.9])}}, "N": {"patchscope": {"ps_peak_prob": _outcome("undetermined", [-0.2, 0.1])}}, }, } issues = {(i.kind, i.route, i.check or i.step): i for i in freeze_issues(report)} + # re-sampling on S and the output's close calls on U read the check the route is cut on assert set(issues) == {("route_signal", "U", "U"), ("reading", "S", "gradcam"), - ("reading", "U", "logprob_entropy"), ("reading", "X", "media_drop")} + ("reading", "U", "patchscope"), ("reading", "X", "media_drop")} gc = issues[("reading", "S", "gradcam")] # the reading furthest outside its band (0.15 past 0.05) is tested, the other is listed assert (gc.reading, gc.direction, gc.secondary) == ("gc_entropy", "down", ["gc_top5_share: up"]) @@ -125,7 +157,8 @@ def test_an_effect_that_holds_on_new_cases_is_supported_and_frozen_before_valida assert (wrap.route, wrap.direction) == ("S", "up") row = next(r for r in out["issues"] if r["issue_id"] == wrap.issue_id) assert row["validation"]["verdict"] == "supported" - assert out["level"] == pytest.approx(1 - ALPHA / out["k"]) and out["arms"]["rules"]["supported"] >= 1 + # one-sided at alpha / K on the claimed side: the interval at 1 - 2 alpha / K + assert out["level"] == pytest.approx(1 - 2 * ALPHA / out["k"]) and out["arms"]["rules"]["supported"] >= 1 frozen = json.loads((tmp_path / "validation" / "frozen.json").read_text()) assert frozen["sha1"] == out["frozen_sha1"] and wrap.issue_id in frozen["arms"]["rules"] # the diagnosis never touched a validation case; the validator wrote to its own directory @@ -150,6 +183,34 @@ def test_an_effect_that_held_only_on_the_discovery_cases_is_refuted(tmp_path, wr assert row["validation"]["verdict"] == "refuted" and row["validation"]["diff"] == 0.0 +def test_a_live_explanation_is_checked_on_new_cases_even_where_no_issue_ran_its_step(tmp_path, wrapper_on_s): + cases, table, explore, confirm = _split() + bundle, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) + model = _Flipper(table, cases) + report = run_triage(model, explore, **_kw(tmp_path / "probing", max_fail=8, min_route_fail=1, + layers=wrapper_on_s)) + claim = {"id": "S.h1", "route": "S", "claim": "a neutral wrapper moves these errors", + "predictions": {FIRST.name: {"prompt_sensitivity": "up"}}, "primary": [[FIRST.name, "prompt_sensitivity"]]} + tie = {"id": "U.h1", "route": "U", "claim": "a near tie", "primary": [["self_consistency_n10", "consistency"]], + "predictions": {"self_consistency_n10": {"consistency": "down"}}} + report["explanations"] = {"sets": [{"hypotheses": [claim, {**claim, "id": "S.h2"}, tie], + "final": {"S.h1": {"state": "live"}, "S.h2": {"state": "contradicted"}, + "U.h1": {"state": "live"}}}]} + out = validate(model, explore, validation, {"d": []}, {"d": report}, out_dir=tmp_path / "validation", + model_identity={"spec": "table"}, bundle=bundle, seed=0, host_assumed_finish=True, + n_needs_counterfactual=True, task_kind="yes_no", answer_fn=_yes_no, layers=wrapper_on_s, + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, progress=None) + frozen = json.loads((tmp_path / "validation" / "frozen.json").read_text()) + assert [h["id"] for h in frozen["explanations"]["d"]] == ["S.h1", "U.h1"] # the live ones, frozen first + row, tied = out["explanations"]["arms"]["d"] + assert row["state"] == "supported" and row["predictions"][0]["verdict"] == "hit" and row["predictions"][0]["primary"] + # one test in the primary family (the definitional one is not a test): one-sided at alpha + assert out["explanations"]["k"] == 1 and out["explanations"]["level"] == pytest.approx(1 - 2 * ALPHA) + # U is cut on re-sampling: re-sampling more cannot support or contradict an explanation of U + assert tied["state"] == "untestable" and tied["predictions"][0]["verdict"] == "definitional" + assert "self_consistency_n10" not in (tmp_path / "validation" / "selection_trace.jsonl").read_text() + + def test_no_carded_reading_reads_the_label_and_a_gold_target_is_refused(tmp_path): assert not label_bound((*BATTERY, *candidate_steps(LAYERS))) assert not any(m.field.startswith("fixed_") for ms in CARDS.values() for m in ms) @@ -199,3 +260,17 @@ def test_readings_that_go_together_within_groups_are_one_phenomenon_and_a_shift_ assert (credit["both"]["n_phenomena"], credit["both"]["phenomena_supported"], credit["both"]["n_issues"]) == (1, 1, 2) # the twin's phenomenon is supported through the knockout, which this arm did not freeze assert (credit["twin_only"]["phenomena_supported"], credit["twin_only"]["phenomena_inconclusive"]) == (0, 1) + + +def test_an_arm_found_more_only_where_it_holds_at_every_grouping_threshold(): + verdicts = {"a": "supported", "b": "supported", "c": "inconclusive"} + links = [{"issues": ["a", "b"], "rho": 0.55}, {"issues": ["b", "c"], "rho": -0.35}] + arms = {"two": ["a", "b"], "one": ["a"], "none": ["c"]} + curve = supported_curve(arms, verdicts, links) + # a and b are one phenomenon up to 0.55 and two above it + assert curve["supported"]["two"] == [1, 1, 1, 1, 1, 1, 2, 2, 2] + assert curve["supported"]["one"] == [1] * 9 and curve["supported"]["none"] == [0] * 9 + # "two" beats "one" only above 0.55, so that difference does not count; both beat "none" everywhere + assert {(d["higher"], d["lower"]) for d in curve["differences"]} == {("two", "none"), ("one", "none")} + above = supported_curve(arms, verdicts, links, grid=(0.6, 0.7)) + assert ("two", "one") in {(d["higher"], d["lower"]) for d in above["differences"]} diff --git a/tests/test_examples/test_benchmark_common.py b/tests/test_examples/test_benchmark_common.py index 2c293e4b..1bb8b9ca 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -298,6 +298,7 @@ def test_cli_no_model_paths(common, capsys): "claude", None, "high" ) assert defaults.held_out is False + assert defaults.triage_validation_source is None assert defaults.fix_repair_rounds == 2 assert defaults.allow_adapted_paper_methods is False assert run.build_parser().parse_args([ @@ -680,6 +681,51 @@ def test_pope_download_keeps_first_yes_first_no_per_image_and_reuses_sibling_ima assert a["kept"] == b["kept"] == 4 and [r["id"] for r in ra] == [r["id"] for r in rb] +def _chartqa_parquet(path, n): + """A ChartQA-shaped parquet: rows at even indices are human-authored.""" + import io + + import pyarrow as pa + import pyarrow.parquet as pq + from PIL import Image + + rows = [] + for i in range(n): + buf = io.BytesIO() + Image.new("RGB", (4, 4), (i * 20 % 256, 0, 0)).save(buf, format="PNG") + rows.append({"query": f"Question {i}?", "label": [str(i)], "image": {"bytes": buf.getvalue(), "path": None}, + "human_or_machine": 0 if i % 2 == 0 else 1}) + pq.write_table(pa.Table.from_pylist(rows), path) + + +def test_chartqa_validation_source_is_every_human_row_the_pool_left(common, tmp_path, monkeypatch): + _, tasks, _, _ = common + import huggingface_hub + + from evalrx.benchmark.tasks import chartqa + + files = {chartqa.TEST_PARQUET: tmp_path / "test.parquet", chartqa.VAL_PARQUET: tmp_path / "val.parquet"} + _chartqa_parquet(files[chartqa.TEST_PARQUET], 8) # human rows 0, 2, 4, 6 + _chartqa_parquet(files[chartqa.VAL_PARQUET], 6) # human rows 0, 2, 4 + monkeypatch.setattr(huggingface_hub, "hf_hub_download", lambda repo, name, **kw: str(files[name])) + pool = chartqa.download(tmp_path / "pool", limit=2, seed=1) + pool_rows = tasks.load_rows(pool["manifest"]) + assert len(pool_rows) == 2 and all(r["subset"] == "test_human" for r in pool_rows) + + out = chartqa.validation_source(tmp_path / "source", exclude=[pool["manifest"]]) + rows = tasks.load_rows(tmp_path / "source" / "manifest.json") + assert (out["kept"], out["by_subset"], out["excluded"]) == (5, {"test_human": 2, "val_human": 3}, 2) + assert not {r["id"] for r in pool_rows} & {r["id"] for r in rows} and len({r["id"] for r in rows}) == 5 + assert [r["subset"] for r in rows] == ["test_human"] * 2 + ["val_human"] * 3 + assert [r["id"] for r in rows if r["subset"] == "val_human"] == ["chartqa-val-human-0", "chartqa-val-human-2", + "chartqa-val-human-4"] + assert all(r["image"].startswith("images/chartqa-val-") for r in rows if r["subset"] == "val_human") + assert all((tmp_path / "source" / r["image"]).is_file() and r["sample_seed"] is None for r in rows) + # the same case protocol as the pool: the source builds and scores like any manifest + batch, _ = tasks.build_cases(tasks.get("chartqa"), tmp_path / "source" / "manifest.json") + assert len(batch) == 5 and tasks.score_case(list(batch)[-1], "4") + + def test_pope_cases_score_through_the_yes_no_grader(common, tmp_path, monkeypatch): _, tasks, _, _ = common from _common.tasks import pope diff --git a/tests/test_models/test_media_encoders_no_grad.py b/tests/test_models/test_media_encoders_no_grad.py new file mode 100644 index 00000000..1c499787 --- /dev/null +++ b/tests/test_models/test_media_encoders_no_grad.py @@ -0,0 +1,95 @@ +"""A gradient pass keeps no graph through the media encoders. + +``CaptureSpec(with_grad=True)`` is for differentiating the logit margin towards decoder +activations. The vision tower's attention over a large image, kept for backward, is tens +of GB (a 918x1811 chart on Qwen3.5-2B: 6400 patches, 75 GB, out of memory), and no decoder +analyzer needs it: the encoders run without a graph and their outputs enter the decoder as +constants. ``CaptureSpec(media_grad=True)`` keeps the old behaviour. +""" + +from __future__ import annotations + +import inspect + +import pytest + +torch = pytest.importorskip("torch") +pytest.importorskip("transformers") +pytest.importorskip("PIL") + +from evalrx.models.backends.hf._util import ( # noqa: E402 + media_encoders, + media_encoders_without_grad, +) +from tests.tiny_whitebox import ( # noqa: E402 + GRID, + IMAGE_TOKEN, + TOKENS_SIDE, + VEND, + VSTART, + _build, + _pixel_values, + image, +) + + +def _inputs(): + ids = [1, 2, VSTART] + [IMAGE_TOKEN] * TOKENS_SIDE * TOKENS_SIDE + [VEND] + [5, 6, 7] # tokens after the merge + enc = {"input_ids": torch.tensor([ids]), "pixel_values": _pixel_values(image(0)), + "image_grid_thw": torch.tensor([[1, GRID, GRID]])} + if "mm_token_type_ids" in inspect.signature(_build("qwen2_5_vl").forward).parameters: + enc["mm_token_type_ids"] = (enc["input_ids"] == IMAGE_TOKEN).long() + return enc + + +def _visual_output_requires_grad(module, enc) -> "tuple[bool, bool]": + """``(the vision tower's output requires grad, the logits do)`` for one forward.""" + seen = [] + (name, visual), = media_encoders(module) + handle = visual.register_forward_hook(lambda m, i, out: seen.append(bool(getattr(out, "requires_grad", False)))) + try: + with torch.set_grad_enabled(True): + out = module(**enc) + finally: + handle.remove() + return seen[0], bool(out.logits.requires_grad) + + +def test_the_vision_tower_is_found_once_and_a_text_model_has_none(): + module = _build("qwen2_5_vl") + assert [name for name, _ in media_encoders(module)] == ["model.visual"] + assert [name for name, _ in media_encoders(module, hint="model.visual")] == ["model.visual"] # not twice + assert [name for name, _ in media_encoders(module, hint="model.no_such_tower")] == ["model.visual"] + assert media_encoders(_build("qwen3_next")) == [] + + +def test_with_grad_keeps_the_decoder_graph_but_not_the_encoders(): + module, enc = _build("qwen2_5_vl"), _inputs() + assert _visual_output_requires_grad(module, enc) == (True, True) # plain: the whole graph + with media_encoders_without_grad(module) as guard: + assert guard.names == ["model.visual"] + assert _visual_output_requires_grad(module, enc) == (False, True) # encoder constant, decoder live + assert "forward" not in module.model.visual.__dict__ # the class method is back + assert _visual_output_requires_grad(module, enc) == (True, True) + + +def test_the_encoder_forward_is_restored_after_an_error_and_its_values_do_not_change(): + module, enc = _build("qwen2_5_vl"), _inputs() + with torch.no_grad(): + plain = module(**enc).logits + with pytest.raises(RuntimeError, match="boom"): + with media_encoders_without_grad(module): + raise RuntimeError("boom") + assert "forward" not in module.model.visual.__dict__ + with media_encoders_without_grad(module), torch.set_grad_enabled(True): + wrapped = module(**enc).logits + assert torch.allclose(plain, wrapped.detach()) + + +def test_the_local_backend_runs_its_encoders_without_grad_unless_asked(): + from evalrx.core.model import CaptureSpec + from evalrx.models.backends.hf.model import HFLocalModel + + source = inspect.getsource(HFLocalModel.forward) + assert "set_grad_enabled(with_grad)" in source and "media_encoders_without_grad(model" in source + assert "media_grad" in source and CaptureSpec().media_grad is False diff --git a/tests/tiny_whitebox.py b/tests/tiny_whitebox.py index 7ccd7844..24d0c123 100644 --- a/tests/tiny_whitebox.py +++ b/tests/tiny_whitebox.py @@ -22,6 +22,7 @@ from __future__ import annotations +from contextlib import nullcontext from types import SimpleNamespace from typing import Any @@ -34,6 +35,7 @@ from evalrx.core.model import Model, Trace from evalrx.core.spec import AttnSemantics from evalrx.core.tokentype import TokenTypeMap +from evalrx.models.backends.hf._util import media_encoders_without_grad IMAGE_TOKEN, VIDEO_TOKEN, VSTART, VEND = 100, 101, 102, 103 VOCAB = 128 @@ -177,7 +179,8 @@ def forward(self, inputs: Any, capture: "set[Capability]", spec: Any = None) -> # refuses image inputs without it; 4.x models do not take it. enc["mm_token_type_ids"] = (enc["input_ids"] == IMAGE_TOKEN).long() with_grad = bool(spec is not None and getattr(spec, "with_grad", False)) - with torch.set_grad_enabled(with_grad): + encoders = media_encoders_without_grad(module) if with_grad else nullcontext() + with torch.set_grad_enabled(with_grad), encoders: out = module(**enc, output_attentions=Capability.ATTENTION in capture, output_hidden_states=Capability.HIDDEN_STATES in capture) img_set = set(image_pos) From 0d01bb63910629ffd476e17871232f267bf69e0f Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:30:20 -0700 Subject: [PATCH 12/26] triage: compare answers under the task's tolerance (rules-5) The U and S checks and the follow-up readings compared answer keys by equality while the grader holds ChartQA's numeric answers to a 5 % relative rule, so two samples of 12.5 and 12.8 were two answers for the triage and one verdict for the scorer. The host now passes an agreement rule next to the answer key (tasks.same_answer on scoring.same_answer: equal keys, or two numbers with the candidate within the case's numeric_tolerance of the reference), threaded as agree_fn through run_triage / validate / triage_cases (default: equal keys, recorded in the report settings). The re-sampling check counts the samples agreeing with the Stage-0 answer as that answer and clusters the rest the same way (rivals); rewording, threshold and prompt_contrast "changed" readings use the rule too. answer_key applies the grader's yes/true aliases on exact_or_numeric. Rules version mvp4-rules-5. Re-reading triage17's stored evidence under the new rule: validation FAIL U 287 -> 261, PASS 78 -> 53, route signal 0.464 -> 0.462. --- CHANGELOG.md | 18 ++++ docs/agentic_benchmark.md | 2 +- evalrx/benchmark/runner.py | 2 +- evalrx/benchmark/scoring.py | 46 +++++++++-- evalrx/benchmark/tasks/__init__.py | 1 + evalrx/benchmark/tasks/base.py | 11 +++ evalrx/eval_agent/probing/controller.py | 18 ++-- evalrx/eval_agent/probing/rules.py | 2 +- evalrx/eval_agent/probing/triage.py | 87 ++++++++++++++------ evalrx/eval_agent/probing/validation.py | 12 +-- tests/test_eval_agent/test_probing_mvp0.py | 52 ++++++++++++ tests/test_examples/test_benchmark_common.py | 24 ++++++ 12 files changed, 228 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8969ff50..98d71224 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed — the triage compares answers under the task's tolerance + +The U and S checks and the follow-up readings compared answers by key equality, +while the grader holds a numeric answer to ChartQA's relaxed 5 % rule: two +samples of 12.5 and 12.8 were two answers for the triage and one verdict for the +scorer, so the re-sampling part of U fired on rounding jitter (ChartQA +`triage17`: 287 of 450 validation FAILs were on U). The host now passes an +agreement rule next to the answer key (`tasks.same_answer`, built on +`scoring.same_answer`: equal keys, or two numbers with the candidate within the +case's `numeric_tolerance` of the reference; `run_triage` / `validate` / +`triage_cases(agree_fn=)`, default: equal keys). The re-sampling check counts +the samples agreeing with the Stage-0 answer as that answer and clusters the +rest the same way (`rivals`), so nearby roundings neither split the base nor +pile up as rivals; the rewording, threshold and `prompt_contrast` "changed" +readings use the rule too. `answer_key` also applies the grader's yes/true +aliases on `exact_or_numeric`. Rules version `mvp4-rules-5`; `agree_fn` is +recorded in the report settings. + ### Fixed — a gradient pass keeps no graph through the media encoders; a case that does not fit is skipped `hf_local` ran the whole model under autograd when `CaptureSpec(with_grad=True)` diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 424d6804..a9649440 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -43,7 +43,7 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. -U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key, not graded; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Re-sampling fires U when another answer was sampled more often than the Stage-0 answer (a tie does not; one differing sample is ordinary noise at temperature 1.0, most of all on open answers); a wrapper fires it when its readable answer differs. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the model's own answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. +U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key under its agreement rule (two numbers within the task's numeric tolerance of each other are one answer, as the grader holds them; re-sampled answers are clustered by it), not graded against the gold; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Re-sampling fires U when another answer was sampled more often than the Stage-0 answer (a tie does not; one differing sample is ordinary noise at temperature 1.0, most of all on open answers); a wrapper fires it when its readable answer differs. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the model's own answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. On an API model (`--backend gemini`) the same plan runs with the white-box steps recorded as `unsupported` (nothing spent). Each action's cost carries what the provider counted — requests, retries, prompt/completion/thought tokens — and its USD at the dated listed price in `evalrx/models/backends/api/prices.py` (unknown for an unlisted model); Stage 0's usage goes into `baseline.json`. The rule-chosen follow-ups are gated on the actual model in the same way, so a run without internal state runs its behavioural follow-ups and records why the internal ones cannot run. diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 5650349d..d4beff1f 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -496,7 +496,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), - task_kind=task.kind, answer_fn=T.answer_key, analyzer_kwargs=extras, price_fn=_price_fn(spec), + task_kind=task.kind, answer_fn=T.answer_key, agree_fn=T.same_answer, analyzer_kwargs=extras, price_fn=_price_fn(spec), per_call_generation=sampling is not None, chunk=int(args.triage_chunk)) report = run_triage( model, explore, out_dir=run_dir / "probing", model_identity=identity, diff --git a/evalrx/benchmark/scoring.py b/evalrx/benchmark/scoring.py index b5fe6358..0c9c2ffe 100644 --- a/evalrx/benchmark/scoring.py +++ b/evalrx/benchmark/scoring.py @@ -9,6 +9,11 @@ ``short_answer_em`` is SQuAD's normalisation (HotpotQA's official metric and dspy's ``answer_exact_match``) on the extracted answer — unlike ``normalize_answer`` it REMOVES punctuation, so ``"Paris."`` == ``"Paris"``. + +:func:`answer_key` reads the answer an output commits to without the gold, and +:func:`same_answer` says when two such keys are one answer under the same +relaxed rule the grader uses: the triage checks compare answers with these two, +so an answer that moved by less than the task's tolerance has not moved. """ from __future__ import annotations @@ -51,23 +56,32 @@ def extract_final_answer(raw: str) -> str: return tagged[-1] if tagged else (lines[-1] if lines else raw) +#: ChartQA labels: a yes/no answer and a true/false label are one answer. +_ALIASES = {"yes": "true", "no": "false"} +#: An ``exact_or_numeric`` answer key that is a number (``f"{x:g}"``: plain or exponent form). +_KEY_NUMBER = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") + + +def _within(candidate: float, target: float, tolerance: float) -> bool: + """ChartQA's relaxed match: within *tolerance* (relative) of *target*; a zero target needs a zero.""" + if target == 0: + return abs(candidate) <= 1e-9 + return abs(candidate - target) <= tolerance * abs(target) + + def answer_matches(observed: str, expected: Any, *, numeric_tolerance: float) -> bool: golds = expected if isinstance(expected, list) else [expected] candidate = normalize_answer(extract_final_answer(observed)) - aliases = {"yes": "true", "no": "false"} - candidate = aliases.get(candidate, candidate) + candidate = _ALIASES.get(candidate, candidate) for gold in golds: target = normalize_answer(gold) - target = aliases.get(target, target) + target = _ALIASES.get(target, target) if candidate == target: return True candidate_number, target_number = _number(candidate), _number(target) if candidate_number is None or target_number is None: continue - if target_number == 0: - if abs(candidate_number) <= 1e-9: - return True - elif abs(candidate_number - target_number) <= numeric_tolerance * abs(target_number): + if _within(candidate_number, target_number, numeric_tolerance): return True return False @@ -187,11 +201,29 @@ def answer_key(kind: str, output: str, *, choices: list | None = None) -> "str | if not text.strip(): return "" candidate = normalize_answer(extract_final_answer(text)) + candidate = _ALIASES.get(candidate, candidate) number = _number(candidate) return f"{number:g}" if number is not None else candidate raise ValueError(f"unknown task kind {kind!r}") +def same_answer(candidate: "str | None", reference: "str | None", *, numeric_tolerance: float = 0.0) -> bool: + """Whether two answer keys (:func:`answer_key`) commit to the same answer, the way + :func:`score_output` holds a candidate against a gold: equal keys, or two numbers with the + candidate within *numeric_tolerance* (relative) of the *reference*, a zero reference needing a + zero. The reference is the answer the candidate is held against (the Stage-0 answer, the + re-asked baseline), so the relation is read from it, not symmetric at the band's edge. A zero + tolerance is key equality, and a non-numeric key only ever equals itself. + """ + if candidate == reference: + return True + if not numeric_tolerance or not candidate or not reference: + return False + if not (_KEY_NUMBER.fullmatch(candidate) and _KEY_NUMBER.fullmatch(reference)): + return False + return _within(float(candidate), float(reference), float(numeric_tolerance)) + + def score_output(kind: str, output: str, gold: Any, *, numeric_tolerance: float = 0.0, choices: list | None = None, dataset: str = "") -> bool: """``True`` iff *output* is correct for a case of task *kind*.""" diff --git a/evalrx/benchmark/tasks/__init__.py b/evalrx/benchmark/tasks/__init__.py index 018c115c..a6619f1c 100644 --- a/evalrx/benchmark/tasks/__init__.py +++ b/evalrx/benchmark/tasks/__init__.py @@ -22,6 +22,7 @@ label_case, load_rows, manifest_path, + same_answer, score_case, val_manifest_path, write_manifest, diff --git a/evalrx/benchmark/tasks/base.py b/evalrx/benchmark/tasks/base.py index 13f26654..b20ed7d8 100644 --- a/evalrx/benchmark/tasks/base.py +++ b/evalrx/benchmark/tasks/base.py @@ -127,6 +127,17 @@ def answer_key(case: Any, output: str) -> "str | None": return _key(str(meta.get("task", "exact_or_numeric")), output, choices=meta.get("choices")) +def same_answer(case: Any, candidate: "str | None", reference: "str | None") -> bool: + """Whether two answer keys are one answer for this case's task: equal, or within the case's + numeric tolerance of the reference (see :func:`~evalrx.benchmark.scoring.same_answer`) — the + rule :func:`score_case` grades with, so a triage check does not call 12.5 and 12.8 two + answers when the grader would call both right.""" + from ..scoring import same_answer as _same + + meta = getattr(case, "metadata", None) or {} + return _same(candidate, reference, numeric_tolerance=float(meta.get("numeric_tolerance", 0.0))) + + def label_case(case: Any, output: str): from evalrx.core.case import Label diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 5d9efa15..fe640151 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -576,6 +576,7 @@ def run_triage( n_needs_counterfactual: bool = False, task_kind: "str | None" = None, answer_fn: "Callable[[Any, str], str | None] | None" = None, + agree_fn: "Callable[[Any, str, str], bool] | None" = None, analyzer_kwargs: "dict[str, dict[str, Any]] | None" = None, price_fn: "Callable[[dict[str, Any] | None], float | None] | None" = None, battery: "tuple[PlanStep, ...]" = BATTERY, @@ -624,6 +625,9 @@ def run_triage( recorded as ``not_applicable`` and not run. answer_fn: ``(case, output) -> answer key`` (``""`` = no readable answer, ``None`` = the task has no categorical answer). + agree_fn: ``(case, candidate, reference) -> bool``: when two keys are + one answer, as the task grades (default: equal keys); every + answer comparison of the checks and readings uses it. analyzer_kwargs: per-analyzer constructor extras the host supplies (e.g. the task's ``score_fn``, the sampling settings). price_fn: ``api_usage -> USD`` (``None`` = no price on record). @@ -687,7 +691,8 @@ def run_triage( chunk=chunk) rank_of = partial(rank, seed) triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, - n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn, stratum=stratum) + n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn, agree_fn=agree_fn, + stratum=stratum) sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) draws = [draw] @@ -802,7 +807,7 @@ def __init__(self, records: list[dict[str, Any]]) -> None: def value(self, key: str, cid: str) -> dict[str, Any]: if (key, cid) not in self.values: - self.values[(key, cid)] = follow_up_values(run.evidence[key], run.by_id[cid], answer_fn) + self.values[(key, cid)] = follow_up_values(run.evidence[key], run.by_id[cid], answer_fn, agree_fn) return self.values[(key, cid)] def cases(self, route: str, key: str) -> tuple[list[str], list[str]]: @@ -1400,7 +1405,8 @@ def account() -> None: # what an exploration decision spent counts against its "sample": draw.to_dict(), "settings": {"host_assumed_finish": host_assumed_finish, "answer_contract": answer_contract, "n_needs_counterfactual": n_needs_counterfactual, "budget_sec": budget_sec, - "task_kind": task_kind, "answer_fn": canonical(answer_fn), "n_fail": n_fail, + "task_kind": task_kind, "answer_fn": canonical(answer_fn), "agree_fn": canonical(agree_fn), + "n_fail": n_fail, "max_fail": max_fail, "max_actions": max_actions, "min_route_fail": min_route_fail, "min_cohort": min_cohort, "per_call_generation": per_call_generation, "chunk": chunk}, "executions": run.executions, @@ -1423,7 +1429,7 @@ def account() -> None: # what an exploration decision spent counts against its **({"explanations": _explanations_report(explanation_sets, explainer, final_outcome)} if explainer is not None else {}), "summary": summary, - "follow_ups": _follow_ups(followed, records, run, sample, rank_of, layers, answer_fn), + "follow_ups": _follow_ups(followed, records, run, sample, rank_of, layers, answer_fn, agree_fn), "routes": _route_report(records, run, rank_of, layers, min_route_fail), "checks": _acceptance(battery, layers, run, draw, ledger), "cases": records, @@ -1554,7 +1560,7 @@ def _battery_state(battery: "tuple[PlanStep, ...]", run: _Run, draw: Any) -> lis def _follow_ups(followed: list[tuple[str, str, str]], records: list[dict[str, Any]], run: _Run, sample: Any, rank_of: Callable[[str], Any], layers: "tuple[Layer, ...]", - answer_fn: Any) -> list[dict[str, Any]]: + answer_fn: Any, agree_fn: Any) -> list[dict[str, Any]]: """Descriptive readings of every follow-up that ran, on the route's current cases.""" by_rule = {x.rule_id: x for x in layers} out = [] @@ -1571,7 +1577,7 @@ def _follow_ups(followed: list[tuple[str, str, str]], records: list[dict[str, An "n_route_fail": len(fail_ids), "n_controls": len(controls), "control_shortfall": shortfall, "not_run_on": len(ev.todo([*fail_ids, *controls])) if ev.step.reuse else None, **({"caveat": ev.step.caveat} if ev.step.caveat else {}), - "reading": follow_up_reading(ev, sample, fail_ids, controls, answer_fn), + "reading": follow_up_reading(ev, sample, fail_ids, controls, answer_fn, agree_fn), }) return out diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index 2d9652c4..1adf3aa4 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -47,7 +47,7 @@ from evalrx.eval_agent.probing.actions import PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -RULES_VERSION = "mvp4-rules-4" +RULES_VERSION = "mvp4-rules-5" ROUTE_ORDER = ("H", "N", "U", "S", "X") DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index 37d651d5..df423859 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -20,7 +20,9 @@ ``prompt_contrast`` wrappers that keep the question verbatim against the re-asked baseline (a wrapper whose answer is unreadable is an invalid control, not an unstable answer). Answers are compared by the task's answer - key, never graded. Any readable answer that differs fires U. + key under its agreement rule (two numbers within the task's tolerance of each + other are one answer, as its grader would hold), never graded against the + gold. Any readable answer that differs fires U. * **S** (a stable failure): a FAIL case on which every required check ran and none fired — H, N (cases with media) and both U parts. S is an investigation route, not a cause; the S readings attached to every case @@ -66,6 +68,8 @@ "ps_first_depth_frac", "ps_media_query_hits", "ps_media_query_found") AnswerFn = Callable[[Any, str], "str | None"] +#: ``(case, candidate, reference) -> bool``: whether two answer keys are one answer for the case. +AgreeFn = Callable[[Any, str, str], bool] #: The plan steps the H/N/U checks (and so the routes, S and X) are read from. #: Every other step only adds descriptive readings to a case. @@ -78,6 +82,28 @@ def default_answer(case: Any, text: str) -> str: return _norm_answer(str(text or "")) +def exact_answer(case: Any, candidate: str, reference: str) -> bool: + """Agreement rule when the host gives none: the keys are equal.""" + return candidate == reference + + +def _answer_clusters(case: Any, keys: list[str], base: str, agree: AgreeFn) -> tuple[int, dict[str, int]]: + """How many of *keys* agree with *base*, and the rest clustered: each remaining answer joins the + most frequent key it agrees with (most frequent first, ties by key), so an answer the model gives + in several nearby roundings is counted once, as one rival. Under :func:`exact_answer` the + clusters are the distinct keys.""" + rest = [k for k in keys if not agree(case, k, base)] + n_base = len(keys) - len(rest) + rivals: dict[str, int] = {} + while rest: + counts = Counter(rest) + centre = max(counts, key=lambda k: (counts[k], k)) + members = [k for k in rest if agree(case, k, centre)] # the centre agrees with itself + rivals[centre] = len(members) + rest = [k for k in rest if not agree(case, k, centre)] + return n_base, rivals + + def _has_media(case: Any) -> bool: inputs = getattr(case, "inputs", None) return any(getattr(inputs, slot, None) is not None for slot in MEDIA_SLOTS) @@ -213,11 +239,13 @@ def _samples_vary(gen: dict[str, Any]) -> bool: return bool(gen.get("do_sample")) or temperature > 0.0 -def _u_sampling(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: +def _u_sampling(obs: "Observation | None", case: Any, answer_fn: AnswerFn, agree_fn: AgreeFn) -> dict[str, Any]: """Fires when another answer was sampled more often than the Stage-0 answer (a tie stays clear). One differing sample is ordinary sampling noise at temperature 1.0, most of all on open answers; - the signal is that the model's greedy answer is not what it usually says. + the signal is that the model's greedy answer is not what it usually says. Samples agreeing with + the Stage-0 answer under *agree_fn* are that answer; the others are clustered the same way + (:func:`_answer_clusters`), so nearby roundings neither split the base nor pile up as rivals. """ why = _unavailable(obs, "self_consistency") if why is not None: @@ -242,9 +270,9 @@ def _u_sampling(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> di answers=dict(Counter(readable))) if not readable: return {**out, "state": UNTESTED, "reason": "no sample commits to a readable answer"} - counts = Counter(readable) - out["agreement"] = round(counts[base] / len(readable), 4) - out["base_is_modal"] = counts[base] == max(counts.values()) + n_base, rivals = _answer_clusters(case, readable, base, agree_fn) + out.update(agreement=round(n_base / len(readable), 4), rivals=rivals, + base_is_modal=n_base >= max(rivals.values(), default=0)) return {**out, "state": CLEAR if out["base_is_modal"] else FIRED} @@ -252,7 +280,7 @@ def _outputs(obs: Observation) -> dict[str, dict[str, str]]: return ((obs.findings or {}).get("artifacts") or {}).get("outputs") or {} -def _u_reword(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: +def _u_reword(obs: "Observation | None", case: Any, answer_fn: AnswerFn, agree_fn: AgreeFn) -> dict[str, Any]: why = _unavailable(obs, "prompt_contrast (rewording)") if why is not None: return {"part": "reword", "state": UNTESTED, "reason": why} @@ -268,19 +296,20 @@ def _u_reword(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict return {**out, "state": UNTESTED, "reason": "the re-asked question commits to no readable answer"} variants = {s: answer_fn(case, texts[cid]) for s, texts in outputs.items() if s != "baseline" and cid in texts} valid = {s: a for s, a in variants.items() if a} + stage0 = answer_fn(case, str(getattr(case, "observed", "") or "")) out.update(base_answer=base, answers=valid, invalid_controls=sorted(s for s in variants if s not in valid), - baseline_matches_stage0=answer_fn(case, str(getattr(case, "observed", "") or "")) == base) + baseline_matches_stage0=bool(stage0) and agree_fn(case, stage0, base)) if not valid: return {**out, "state": UNTESTED, "reason": f"no wrapper gave a readable answer (invalid controls: {out['invalid_controls']})"} - out["changed"] = sorted(s for s, a in valid.items() if a != base) + out["changed"] = sorted(s for s, a in valid.items() if not agree_fn(case, a, base)) return {**out, "state": FIRED if out["changed"] else CLEAR} def _u_check(sampling: "Observation | None", reword: "Observation | None", case: Any, - answer_fn: AnswerFn) -> dict[str, Any]: + answer_fn: AnswerFn, agree_fn: AgreeFn) -> dict[str, Any]: """U fires when either part fires; it is clear only when both parts ran and are clear.""" - parts = [_u_sampling(sampling, case, answer_fn), _u_reword(reword, case, answer_fn)] + parts = [_u_sampling(sampling, case, answer_fn, agree_fn), _u_reword(reword, case, answer_fn, agree_fn)] states = [p["state"] for p in parts] state = FIRED if FIRED in states else CLEAR if all(st == CLEAR for st in states) else UNTESTED out: dict[str, Any] = {"state": state, "parts": parts} @@ -289,7 +318,7 @@ def _u_check(sampling: "Observation | None", reword: "Observation | None", case: return out -def _s_threshold(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> dict[str, Any]: +def _s_threshold(obs: "Observation | None", case: Any, answer_fn: AnswerFn, agree_fn: AgreeFn) -> dict[str, Any]: """The answer under the changed decision criterion, against the re-asked baseline.""" if obs is None: return {"state": UNTESTED, "reason": "threshold instruction not in the plan for this task"} @@ -306,7 +335,8 @@ def _s_threshold(obs: "Observation | None", case: Any, answer_fn: AnswerFn) -> d if not base or not alt: return {**out, "state": UNTESTED, "reason": "an answer was unreadable or the task has no answer key"} before, after = (scored.get("baseline") or {}).get(cid), (scored.get(variant) or {}).get(cid) - out.update(changed=alt != base, fixed=before == 0.0 and after == 1.0, broken=before == 1.0 and after == 0.0) + out.update(changed=not agree_fn(case, alt, base), fixed=before == 0.0 and after == 1.0, + broken=before == 1.0 and after == 0.0) return {**out, "state": "measured"} @@ -333,7 +363,8 @@ def _s_patchscope(obs: "Observation | None", cid: str) -> dict[str, Any]: def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence]", *, host_assumed_finish: bool, answer_contract: bool, n_needs_counterfactual: bool = False, - answer_fn: "AnswerFn | None" = None, stratum: str = "gold") -> list[dict[str, Any]]: + answer_fn: "AnswerFn | None" = None, agree_fn: "AgreeFn | None" = None, + stratum: str = "gold") -> list[dict[str, Any]]: """One record per case: label, stratum, every H/N/U check, routes, knockout and S readings. *observations* are keyed by plan step (``prompt_reword`` and @@ -348,7 +379,11 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence *answer_fn* ``(case, output) -> key`` reads the answer an output commits to (``""``: none; ``None``: the task has no categorical answer); default - :func:`default_answer`. + :func:`default_answer`. *agree_fn* ``(case, candidate, reference) -> bool`` says + when two keys are one answer, the way the task grades (two numbers within its + tolerance of each other); default :func:`exact_answer`, equal keys. Every + answer comparison of the U and S checks and of the follow-up readings goes + through it, so the tolerance belongs here, not in the key. *stratum* is the sampler's rule (``"gold"`` or ``"none"``): controls are matched within a record's stratum, so it must be the rule the sample was drawn with. Open-answer tasks draw with ``"none"``; @@ -356,7 +391,7 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence """ from evalrx.eval_agent.probing.sampler import STRATA - answer = answer_fn or default_answer + answer, agree = answer_fn or default_answer, agree_fn or exact_answer stratum_of = STRATA[stratum] records = [] for case in cases: @@ -384,7 +419,7 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence } n = _n_check(pick(observations, "modality_ablation", cid), case, n_needs_counterfactual) u = _u_check(pick(observations, "self_consistency", cid), pick(observations, "prompt_reword", cid), - case, answer) + case, answer, agree) label = getattr(getattr(case, "label", None), "value", None) checks = {"H": h["state"], "N": n["state"], "U": u["state"]} routes = [tag for tag, state in checks.items() if state == FIRED] @@ -411,7 +446,7 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence "U": u, "knockout": _knockout(pick(observations, "attention_knockout", cid), cid), "S_readings": { - "threshold": _s_threshold(pick(observations, "prompt_threshold", cid), case, answer), + "threshold": _s_threshold(pick(observations, "prompt_threshold", cid), case, answer, agree), "embed_lens": _measured_row(pick(observations, "embed_lens", cid), cid, "embed_lens", _EMBED_FIELDS), "patchscope": _s_patchscope(pick(observations, "patchscope", cid), cid), @@ -623,10 +658,11 @@ def _numeric(row: dict[str, Any]) -> dict[str, float]: COMPLIANCE_WORDS = 5 -def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn, +def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn, agree_fn: AgreeFn, asks_for_text: bool = False) -> dict[str, float]: """``prompt_contrast``: per strategy, whether the answer moved off the re-asked - question (by answer key) and whether that fixed or broke it (by the task's scorer). + question (by answer key, under the task's agreement rule) and whether that fixed + or broke it (by the task's scorer). With *asks_for_text* (a strategy asking for a description before the answer) also how many words it added and whether that reached ``COMPLIANCE_WORDS``: @@ -644,7 +680,7 @@ def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn, continue alt = answer_fn(case, texts[cid]) if base and alt: - out[f"changed_{strategy}"] = float(alt != base) + out[f"changed_{strategy}"] = float(not agree_fn(case, alt, base)) if asks_for_text: extra = len(str(texts[cid]).split()) - len(str(outputs["baseline"][cid]).split()) out[f"extra_words_{strategy}"] = float(extra) @@ -656,7 +692,8 @@ def _contrast_values(obs: Observation, case: Any, answer_fn: AnswerFn, return out -def follow_up_values(evidence: StepEvidence, case: Any, answer_fn: "AnswerFn | None" = None) -> dict[str, Any]: +def follow_up_values(evidence: StepEvidence, case: Any, answer_fn: "AnswerFn | None" = None, + agree_fn: "AgreeFn | None" = None) -> dict[str, Any]: """One case's numeric readings from a follow-up step, or why there are none.""" cid = str(case.id) obs = evidence.for_case(cid) @@ -666,7 +703,7 @@ def follow_up_values(evidence: StepEvidence, case: Any, answer_fn: "AnswerFn | N return {"state": UNTESTED, "action_id": obs.action_id, "reason": f"{obs.status}: {obs.error or ''}".strip()} values = _numeric(obs.per_case().get(cid) or {}) if evidence.step.analyzer == "prompt_contrast": - values.update(_contrast_values(obs, case, answer_fn or default_answer, + values.update(_contrast_values(obs, case, answer_fn or default_answer, agree_fn or exact_answer, asks_for_text=evidence.step.min_output_tokens > 0)) if not values: return {"state": UNTESTED, "action_id": obs.action_id, "reason": obs.missing.get(cid, "no per_case row")} @@ -674,7 +711,7 @@ def follow_up_values(evidence: StepEvidence, case: Any, answer_fn: "AnswerFn | N def follow_up_reading(evidence: StepEvidence, cases: Any, route_ids: "list[str]", control_ids: "list[str]", - answer_fn: "AnswerFn | None" = None) -> dict[str, Any]: + answer_fn: "AnswerFn | None" = None, agree_fn: "AgreeFn | None" = None) -> dict[str, Any]: """Mean of every numeric per-case reading over the route's FAIL cases and their PASS controls. Descriptive, like the S readings: no test, and a field is listed even when @@ -682,7 +719,7 @@ def follow_up_reading(evidence: StepEvidence, cases: Any, route_ids: "list[str]" mean (an answer-change reading needs both answers readable). """ by_id = {str(c.id): c for c in cases} - rows = {cid: follow_up_values(evidence, by_id[cid], answer_fn) for cid in [*route_ids, *control_ids]} + rows = {cid: follow_up_values(evidence, by_id[cid], answer_fn, agree_fn) for cid in [*route_ids, *control_ids]} out: dict[str, Any] = {} for name, ids in (("route_fail", route_ids), ("controls", control_ids)): measured = [rows[cid]["values"] for cid in ids if rows[cid]["state"] == "measured"] diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py index ac5adb0f..86bb9dfa 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/probing/validation.py @@ -541,7 +541,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili reports: dict[str, dict[str, Any]], *, out_dir: "str | Path", model_identity: dict[str, Any], bundle: "PartitionBundle | None" = None, seed: int = 0, stratum: str = "gold", host_assumed_finish: bool = False, answer_contract: bool = False, n_needs_counterfactual: bool = False, - task_kind: "str | None" = None, answer_fn: Any = None, + task_kind: "str | None" = None, answer_fn: Any = None, agree_fn: Any = None, analyzer_kwargs: "dict[str, dict[str, Any]] | None" = None, price_fn: Any = None, per_call_generation: bool = True, chunk: int = 8, budget_sec: float = 0.0, battery: "tuple[PlanStep, ...] | None" = None, layers: "tuple[Layer, ...]" = LAYERS, @@ -599,7 +599,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili run.run_step(step, list(draw.case_ids), kind="validation", revision=0) records = triage_cases(sample, run.evidence, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, - answer_fn=answer_fn, stratum=stratum) + answer_fn=answer_fn, agree_fn=agree_fn, stratum=stratum) rank_of = partial(rank, seed) by_rule = {x.rule_id: x for x in layers} steps = {s.name: s for s in (*battery, *candidate_steps(layers))} @@ -631,7 +631,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili continue measured[(issue.route, step.name)] = (fail_ids, controls) metric = Metric(issue.reading, "", issue.band, issue.metric_kind) - values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn) for cid in (*fail_ids, *controls)} + values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn, agree_fn) for cid in (*fail_ids, *controls)} o = outcome(values, fail_ids, controls, metric, level=level) o95 = outcome(values, fail_ids, controls, metric) per_case[issue.issue_id] = ({cid: float(v["values"][issue.reading]) for cid, v in values.items() @@ -677,7 +677,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili "phenomenon_links": links, "arms": credit, "phenomenon_curve": curve, - "explanations": _check_explanations(frozen["explanations"], run, measured, answer_fn), + "explanations": _check_explanations(frozen["explanations"], run, measured, answer_fn, agree_fn), "cost": {"charged_sec": round(run.charged("wall_sec"), 3), "executions": len(run.executions)}, "_note": ("each issue's interval is at 1 - 2 alpha/K: a one-sided test at alpha/K on its claimed side " "(Bonferroni over the K issues of the family); ci95 " @@ -705,7 +705,7 @@ def live_explanations(reports: dict[str, dict[str, Any]]) -> dict[str, list[dict def _check_explanations(explanations: dict[str, list[dict[str, Any]]], run: Any, - measured: dict[tuple[str, str], Any], answer_fn: Any) -> dict[str, Any]: + measured: dict[tuple[str, str], Any], answer_fn: Any, agree_fn: Any) -> dict[str, Any]: """The frozen live explanations, judged on the validation evidence of their route by their primary predictions (mechanism claims: reported, not counted). @@ -740,7 +740,7 @@ def _check_explanations(explanations: dict[str, list[dict[str, Any]]], run: Any, fail_ids, controls = measured[(h["route"], step)] metric = next(m for m in CARDS[step] if m.field == f) ev = run.evidence[step] - values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn) for cid in (*fail_ids, *controls)} + values = {cid: follow_up_values(ev, run.by_id[cid], answer_fn, agree_fn) for cid in (*fail_ids, *controls)} o = outcome(values, fail_ids, controls, metric, level=level if row["primary"] else 0.95) preds.append({**row, "observed": o.get("observed"), "n": o.get("n"), "diff": o.get("diff"), "ci": o.get("ci95"), "verdict": verdict(d, o.get("ci95"), metric.band)}) diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index ba1ab540..a7ae5a3d 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -403,6 +403,58 @@ def test_u_needs_both_parts_and_s_is_a_fully_checked_stable_failure(): assert t["N"]["state"] == "not_applicable" and t["routes"] == ["S"] +def _num_case(cid, observed): + return FailureCase(id=cid, inputs=Inputs(prompt=f"How much in {cid}?", image=f"{cid}.png"), expected=["12.5"], + observed=observed, label=Label.FAIL, + metadata={"task": "exact_or_numeric", "numeric_tolerance": 0.05}) + + +def test_u_and_s_compare_answers_under_the_tasks_tolerance(): + """ChartQA grades 12.6 against 12.5 as right (5 %), so the triage must not call them two answers: + the host's agreement rule (``agree_fn``) decides, and the samples are clustered by it.""" + from evalrx.benchmark import tasks + from evalrx.eval_agent.probing.triage import _contrast_values + + cases = CaseBatch([_num_case("r", "100"), _num_case("p", "12.5"), _num_case("w", "12.4")]) + ids = [c.id for c in cases] + obs = _clean_h_and_n(ids, {i: "7" for i in ids}) + obs.update(_u_obs( + samples={"r": ["101", "102", "99", "250", "250"], # roundings of the base vs a twice-sampled rival + "p": ["12.6", "13.5", "13.6", "13.7", "12.5"], # a rival the model gives in three roundings + "w": ["12.4"] * 5}, + reworded={"r": ["100", "100", "100"], "p": ["12.5", "12.5", "12.5"], "w": ["12.5", "12.6", "13.5"]}, + gen_kwargs={"temperature": 1.0})) + th = _obs("prompt_contrast", [{"sample_id": i} for i in ids]) + th.findings.update(artifacts={"outputs": {"baseline": {"w": "12.5"}, "sensitive": {"w": "12.6"}}}, + by_strategy={"baseline": {"w": 0.0}, "sensitive": {"w": 0.0}}) + obs["prompt_threshold"] = th + kw = dict(host_assumed_finish=True, answer_contract=True, stratum="none", answer_fn=tasks.answer_key) + exact = {r["case_id"]: r for r in triage_cases(cases, obs, **kw)} + within = {r["case_id"]: r for r in triage_cases(cases, obs, agree_fn=tasks.same_answer, **kw)} + + # r: by key the base was never sampled (fires); within 5 % three samples are the base, two the rival + assert exact["r"]["U"]["parts"][0]["state"] == "fired" and exact["r"]["U"]["parts"][0]["agreement"] == 0.0 + r = within["r"]["U"]["parts"][0] + assert r["state"] == "clear" and r["agreement"] == 0.6 and r["rivals"] == {"250": 2} and r["base_is_modal"] + assert r["answers"] == {"101": 1, "102": 1, "99": 1, "250": 2} # the exact counts stay on record + # p: by key five different answers tie (clear); within 5 % the rival 13.5-13.7 outnumbers the base 3 to 2 + assert exact["p"]["U"]["parts"][0]["state"] == "clear" + p = within["p"]["U"]["parts"][0] + assert p["state"] == "fired" and p["agreement"] == 0.4 and p["rivals"] == {"13.7": 3} + # w: a wrapper that moved the answer by less than the tolerance did not move it; the Stage-0 answer + # 12.4 is the re-asked 12.5; the threshold instruction's 12.6 is no change + assert exact["w"]["U"]["parts"][1]["changed"] == ["instruction_frame", "question_frame"] + w = within["w"]["U"]["parts"][1] + assert w["changed"] == ["instruction_frame"] and w["baseline_matches_stage0"] + assert not exact["w"]["U"]["parts"][1]["baseline_matches_stage0"] + assert exact["w"]["S_readings"]["threshold"]["changed"] and not within["w"]["S_readings"]["threshold"]["changed"] + assert within["r"]["routes"] == ["S"] and within["p"]["routes"] == within["w"]["routes"] == ["U"] + # the follow-up reading of a prompt_contrast step uses the same rule + case_w = next(c for c in cases if c.id == "w") + assert _contrast_values(th, case_w, tasks.answer_key, tasks.same_answer)["changed_sensitive"] == 0.0 + assert _contrast_values(th, case_w, tasks.answer_key, lambda c, a, b: a == b)["changed_sensitive"] == 1.0 + + def test_s_readings_are_summarised_per_cohort_and_stratum(): cases = CaseBatch([ _yn_case("s1", Label.FAIL, "Yes", "No"), _yn_case("s2", Label.FAIL, "Yes", "No"), diff --git a/tests/test_examples/test_benchmark_common.py b/tests/test_examples/test_benchmark_common.py index 1bb8b9ca..2085f572 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -184,6 +184,30 @@ def test_answer_keys_read_answers_without_the_gold(common): case = FailureCase(id="c", inputs=Inputs(prompt="q"), expected="C", metadata={"task": "multiple_choice_letter", "choices": ["A", "B", "C", "D", "E"]}) assert tasks.answer_key(case, "E") == "E" # the case's own choices + # ChartQA's label aliases hold for the key as for the grader + assert key("exact_or_numeric", "Yes") == key("exact_or_numeric", "TRUE") == "true" + + +def test_two_answer_keys_are_one_answer_within_the_tasks_tolerance(common): + """The grader calls 12.6 right against a gold of 12.5 (ChartQA's 5 %), so two keys that + close are one answer for the triage checks too; the rule is read from the reference.""" + _, tasks, scoring, _ = common + same = scoring.same_answer + assert same("12.6", "12.5", numeric_tolerance=0.05) and same("12.4", "12.5", numeric_tolerance=0.05) + assert not same("13.5", "12.5", numeric_tolerance=0.05) # 8 % off + assert same("1.5e+06", "1.52e+06", numeric_tolerance=0.05) # keys of large numbers (``:g``) + assert same("0", "0", numeric_tolerance=0.05) and not same("0.001", "0", numeric_tolerance=0.05) + assert same("-3", "-3.1", numeric_tolerance=0.05) + assert same("beatles", "beatles", numeric_tolerance=0.05) and not same("beatles", "beatle", numeric_tolerance=0.05) + assert not same("12.6", "12.5") and not same("12.6", "12.5", numeric_tolerance=0.0) # zero tolerance = equality + assert not same("", "12.5", numeric_tolerance=0.05) and not same("12.5", "", numeric_tolerance=0.05) + from evalrx.core.case import FailureCase, Inputs + + chart = FailureCase(id="c", inputs=Inputs(prompt="q"), expected=["12.5"], + metadata={"task": "exact_or_numeric", "numeric_tolerance": 0.05}) + plain = FailureCase(id="p", inputs=Inputs(prompt="q"), expected=["12.5"], metadata={"task": "exact_or_numeric"}) + assert tasks.same_answer(chart, "12.6", "12.5") and not tasks.same_answer(plain, "12.6", "12.5") + assert tasks.same_answer(plain, "12.5", "12.5") def test_parsed_choice_refuses_leaked_thought_preambles_and_enumerations(common): From a70219c11d10875db4de44522863525c5e063834 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:00:35 -0700 Subject: [PATCH 13/26] triage: --confirm-split-by media splits the pool by media content The explore/confirm draw was over single cases, so on ChartQA (two questions per chart, each row saving its own copy of the image) 207 of the 500 CONFIRM cases shared a chart with DISCOVERY and were dropped by the partition, not at random. --confirm-split-by media (default: case, the judge-driven loop's split, which a triage run must share to be compared case for case) groups the cases by media content and moves whole groups, stratified by the labels a group holds, so DISCOVERY and CONFIRM never share an image and the diagnostic validation leaves nothing out. The bundle records split_by and its rule. On the ChartQA pool with triage17's labels: EXPLORE 502 / CONFIRM 498 cases, 176 FAILs each; internal validation 293 (100 FAIL) -> 498 (176 FAIL); EXPLORE charts 406 -> 299. --- CHANGELOG.md | 11 ++++ docs/agentic_benchmark.md | 2 +- evalrx/benchmark/run.py | 5 ++ evalrx/benchmark/runner.py | 9 ++-- evalrx/eval_agent/probing/partition.py | 52 +++++++++++++++++-- evalrx/eval_agent/probing/validation.py | 15 ++++-- tests/test_eval_agent/test_probing_mvp0.py | 4 ++ .../test_probing_validation.py | 25 +++++++++ tests/test_examples/test_benchmark_common.py | 1 + 9 files changed, 112 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98d71224..4207f646 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,17 @@ and `generic_attention` also skip a case whose graph still does not fit validation (`triage17`) the failed chunk stopped both steps on the S route at 12 of 135 cases. +### Added — the pool can be split into EXPLORE and CONFIRM by media content + +`--confirm-split-by media` (default `case`) draws the explore/confirm split over +media groups: cases on the same image (by content) go to one side, stratified by +the labels the group holds, so DISCOVERY and CONFIRM never share an image and +the diagnostic validation leaves nothing out. Under the per-case split 207 of +ChartQA's 500 CONFIRM cases shared a chart with DISCOVERY and were dropped, not +at random (charts with two questions). The bundle records `split_by`; the +per-case split stays the default because a judge-driven run splits by case and +the two policies are compared case for case. + ### Added — a validation-only source for the diagnostic validation `--triage-validation-source MANIFEST` (with `--triage-validate`) adds cases used diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index a9649440..3338ad58 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -39,7 +39,7 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. -**Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. +**Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); `--confirm-split-by media` instead draws the explore/confirm split over media groups, whole images on one side, so nothing is left out (default `case`: the judge-driven loop's split, which a triage run must share to be compared case for case); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 567a11e7..2c05d3ff 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -138,6 +138,11 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP help="fraction of the main batch reserved as CONFIRM (label-stratified, seed " "20260818); the rest is EXPLORE where M1-M4 and the fix search run. " "0.5 = the 50/50 default; 1/3 with --limit 192 = 128 explore / 64 confirm") + p.add_argument("--confirm-split-by", choices=["case", "media"], default="case", + help="triage_active: what the explore/confirm draw is over. case = the loop's own " + "stratified split (a judge-driven run on the same batch sees the same EXPLORE); media = " + "whole media groups (cases on the same image, by content) go to one side, so " + "DISCOVERY and CONFIRM never share an image and the validation leaves nothing out") p.add_argument("--val-limit", type=int, default=0, help="with --held-out: cases taken from the top of manifest_val.json " "(0 = the whole validation manifest)") diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index d4beff1f..bb4adf8b 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -459,11 +459,13 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: from .run import triage_weights - explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED) + explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED, + by=args.confirm_split_by) bundle, validation = partition_bundle(explore, confirm, seed=CONFIRM_SPLIT_SEED, confirm_split=float(args.confirm_split), manifest=baseline.get("manifest"), source=source[0] if source else None, - source_manifest=source[1] if source else None) + source_manifest=source[1] if source else None, + split_by=args.confirm_split_by) if args.triage_validate and not len(validation): raise SystemExit("--triage-validate needs CONFIRM cases on media EXPLORE does not contain; " "set --confirm-split above 0 or give a --triage-validation-source") @@ -508,7 +510,8 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, weights=Weights(**triage_weights(args.triage_weights)), explore_share=float(args.triage_explore_share), explore_from=args.triage_explore_from, - partition={"confirm_split": float(args.confirm_split), "seed": CONFIRM_SPLIT_SEED, + partition={"confirm_split": float(args.confirm_split), "split_by": args.confirm_split_by, + "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, "n_validation": len(validation), "n_validation_source": len(source[0]) if source else 0, "bundle_sha1": bundle_row["sha1"], diff --git a/evalrx/eval_agent/probing/partition.py b/evalrx/eval_agent/probing/partition.py index ff1e18d0..4cad401d 100644 --- a/evalrx/eval_agent/probing/partition.py +++ b/evalrx/eval_agent/probing/partition.py @@ -4,6 +4,13 @@ batch sees, or the two policies cannot be compared case for case. Rather than re-implementing the stratified split (and drifting from it), this calls ``VLDiagnoseLoop._split_partitions`` with only the attributes it reads. + +``by="media"`` is the triage protocol's own variant: the cases are grouped by +their media content and whole groups go to one side, so DISCOVERY and CONFIRM +never share an image and :func:`~evalrx.eval_agent.probing.validation.partition_bundle` +leaves nothing out (under the per-case split 207 of ChartQA's 500 CONFIRM cases +shared a chart with DISCOVERY and were dropped). A judge-driven run still splits +by case, so the two policies are compared case for case under ``by="case"`` only. """ from __future__ import annotations @@ -14,10 +21,18 @@ if TYPE_CHECKING: from evalrx.core.case import CaseBatch +#: What the explore/confirm draw is over: single cases (the loop's split) or media groups. +SPLIT_BY = ("case", "media") + -def explore_confirm_split(data: "CaseBatch", confirm_split: float, - seed: int) -> "tuple[CaseBatch, CaseBatch | None]": - """``(explore, confirm)`` exactly as ``VLDiagnoseLoop(confirm_split=..., confirm_split_seed=seed)``.""" +def explore_confirm_split(data: "CaseBatch", confirm_split: float, seed: int, *, + by: str = "case") -> "tuple[CaseBatch, CaseBatch | None]": + """``(explore, confirm)`` exactly as ``VLDiagnoseLoop(confirm_split=..., confirm_split_seed=seed)``; + with ``by="media"`` the same stratified draw over media groups (:func:`split_by_media`).""" + if by not in SPLIT_BY: + raise ValueError(f"by must be one of {SPLIT_BY}, not {by!r}") + if by == "media": + return split_by_media(data, float(confirm_split), int(seed)) from evalrx.eval_agent.loop import VLDiagnoseLoop view = SimpleNamespace( @@ -26,3 +41,34 @@ def explore_confirm_split(data: "CaseBatch", confirm_split: float, ) explore, confirm, _test = VLDiagnoseLoop._split_partitions(view, data) return explore, confirm + + +def split_by_media(data: "CaseBatch", confirm_split: float, seed: int) -> "tuple[CaseBatch, CaseBatch | None]": + """Whole media groups (cases on the same image, by content) go to one side. The groups are drawn + stratified by the labels they hold (a chart with one FAIL and one PASS question is its own + stratum), so each side keeps the batch's FAIL share. The loop's thresholds hold: no split under + 4 cases or when a side would be empty (then ``(data, None)``).""" + from evalrx.core.case import CaseBatch + from evalrx.eval_agent.loop import VLDiagnoseLoop + from evalrx.eval_agent.probing.validation import source_key + from evalrx.stats.subset_sampling import stratified_subset + + cases = list(data) + n_confirm = round(len(cases) * confirm_split) + if confirm_split <= 0.0 or len(cases) < 4 or n_confirm <= 0 or n_confirm >= len(cases): + return data, None + groups: dict[str, list] = {} + for c in cases: + groups.setdefault(source_key(c), []).append(c) + members = list(groups.values()) # first-appearance order: deterministic + n_groups = max(1, min(len(members) - 1, round(len(members) * confirm_split))) + + def stratum(group: list) -> tuple: + return tuple(sorted(repr(VLDiagnoseLoop._strat_key(c)) for c in group)) + + chosen = {id(c) for g in stratified_subset(members, stratum, n_groups, seed=seed) for c in g} + confirm = [c for c in cases if id(c) in chosen] + explore = [c for c in cases if id(c) not in chosen] + if not confirm or not explore: + return data, None + return CaseBatch(explore), CaseBatch(confirm) diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py index 86bb9dfa..986c718a 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/probing/validation.py @@ -168,6 +168,7 @@ class PartitionBundle: manifest: dict[str, Any] = field(default_factory=dict) validation_from: dict[str, int] = field(default_factory=dict) # validation cases by origin (confirm, source) source_manifest: dict[str, Any] = field(default_factory=dict) # the validation-only manifest, when given + split_by: str = "case" # what the explore/confirm draw was over: "case" | "media" roles: dict[str, Any] = field(default_factory=lambda: { "controller": "DISCOVERY", "judge": "DISCOVERY (route summaries only)", "validator": "DIAGNOSTIC_VALIDATION", "repair_confirm": None}) @@ -187,9 +188,11 @@ def _file_info(path: "str | Path | None") -> dict[str, Any]: def partition_bundle(discovery: "CaseBatch", confirm: "CaseBatch | None", *, seed: int, confirm_split: float, manifest: "str | Path | None" = None, source: "CaseBatch | None" = None, - source_manifest: "str | Path | None" = None) -> "tuple[PartitionBundle, CaseBatch]": + source_manifest: "str | Path | None" = None, split_by: str = "case") -> "tuple[PartitionBundle, CaseBatch]": """DIAGNOSTIC_VALIDATION = CONFIRM minus the cases sharing a source with DISCOVERY, plus the cases of - a validation-only *source* (a manifest the controller never sees) that share none with it either.""" + a validation-only *source* (a manifest the controller never sees) that share none with it either. + *split_by* records how the explore/confirm draw was made (``"media"``: whole sources on one side, so + the CONFIRM exclusion is empty by construction and is kept only as a check).""" from evalrx.core.case import CaseBatch seen = {source_key(c) for c in discovery} @@ -219,13 +222,15 @@ def partition_bundle(discovery: "CaseBatch", confirm: "CaseBatch | None", *, see discovery_ids=[str(c.id) for c in discovery], validation_ids=[str(c.id) for c in kept], excluded=excluded, n_sources={"discovery": len(seen), "validation": len({source_key(c) for c in kept})}, - rule=("DISCOVERY = EXPLORE; DIAGNOSTIC_VALIDATION = CONFIRM minus every case whose media content " - "also appears in DISCOVERY" + rule=(("DISCOVERY = EXPLORE, split from CONFIRM by media content (a source is on one side only); " + "DIAGNOSTIC_VALIDATION = CONFIRM" if split_by == "media" else + "DISCOVERY = EXPLORE; DIAGNOSTIC_VALIDATION = CONFIRM minus every case whose media content " + "also appears in DISCOVERY") + ("; plus every case of the validation-only source whose media content does not" if source is not None else "") + "; repair CONFIRM: none (repair is out of scope)"), seed=int(seed), confirm_split=float(confirm_split), manifest=_file_info(manifest), - validation_from=origin, source_manifest=_file_info(source_manifest)) + validation_from=origin, source_manifest=_file_info(source_manifest), split_by=str(split_by)) return bundle, CaseBatch(kept) diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index a7ae5a3d..ef3e1645 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -82,6 +82,10 @@ def test_explore_split_is_the_loops_split(): got_e, got_c = explore_confirm_split(cases, 0.5, 20260818) assert [c.id for c in got_e] == [c.id for c in want_e] assert [c.id for c in got_c] == [c.id for c in want_c] + by_case = explore_confirm_split(cases, 0.5, 20260818, by="case") + assert [c.id for c in by_case[0]] == [c.id for c in got_e] and [c.id for c in by_case[1]] == [c.id for c in got_c] + with pytest.raises(ValueError): + explore_confirm_split(cases, 0.5, 20260818, by="chart") # -- executor -------------------------------------------------------------------- diff --git a/tests/test_eval_agent/test_probing_validation.py b/tests/test_eval_agent/test_probing_validation.py index 5fa511cf..4b951c31 100644 --- a/tests/test_eval_agent/test_probing_validation.py +++ b/tests/test_eval_agent/test_probing_validation.py @@ -61,6 +61,31 @@ def test_the_partition_keeps_every_validation_case_off_the_media_discovery_saw() assert bundle.diagnostic_val_source == "internal" and bundle.validation_from == {"confirm": len(validation)} +def test_a_media_split_keeps_every_image_on_one_side_so_the_validation_drops_nothing(): + from evalrx.core.case import Label + + cases, _, by_case_explore, by_case_confirm = _split() + explore, confirm = explore_confirm_split(cases, 0.5, SEED, by="media") + assert not {source_key(c) for c in explore} & {source_key(c) for c in confirm} + assert len(explore) + len(confirm) == len(cases) and {c.id for c in explore} | {c.id for c in confirm} == {c.id for c in cases} + assert abs(len(confirm) - len(cases) / 2) <= 4 # 96 images, 2 questions each: 48 a side + fail = lambda batch: sum(c.label == Label.FAIL for c in batch) / len(batch) # noqa: E731 + assert abs(fail(confirm) - fail(cases)) <= 0.1 # stratified by the group's labels + # the per-case split of the same batch shares images across the sides; this one is deterministic and + # moves whole images at a time + assert {source_key(c) for c in by_case_explore} & {source_key(c) for c in by_case_confirm} + again = explore_confirm_split(cases, 0.5, SEED, by="media") + assert [c.id for c in again[1]] == [c.id for c in confirm] + bundle, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5, split_by="media") + assert bundle.excluded["shares_a_source_with_discovery"] == 0 and len(validation) == len(confirm) + assert bundle.split_by == "media" and bundle.rule.startswith("DISCOVERY = EXPLORE, split from CONFIRM by media") + assert bundle.to_dict()["split_by"] == "media" + # too small to split, or everything on one image: no split, as the loop + assert explore_confirm_split(cases[:3], 0.5, SEED, by="media")[1] is None + one_image = [c for c in cases if c.inputs.image == "img0"] + assert explore_confirm_split(one_image + one_image, 0.5, SEED, by="media")[1] is None + + def test_a_validation_only_source_joins_the_validation_cases_under_the_same_media_rule(tmp_path): from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label diff --git a/tests/test_examples/test_benchmark_common.py b/tests/test_examples/test_benchmark_common.py index 2085f572..a3db1c4d 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -323,6 +323,7 @@ def test_cli_no_model_paths(common, capsys): ) assert defaults.held_out is False assert defaults.triage_validation_source is None + assert defaults.confirm_split_by == "case" assert defaults.fix_repair_rounds == 2 assert defaults.allow_adapted_paper_methods is False assert run.build_parser().parse_args([ From 26957410bdfd2644e26a1e2396fcf163efb71e04 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:14:39 -0700 Subject: [PATCH 14/26] triage: random and cheapest-first controls; a zero-call step is priced at its own cost (score-5) Two controls for the scored scheduler, --triage-scheduler random | cheapest: the same candidate pool, gain floor, budget and stop rules, only the pick differs (a seeded uniform draw among the candidates at or above the floor; the cheapest of them, unpriced last, ties by the soft order). Neither explores nor takes an explainer, so scored_x0 is their nearest value arm. Reports triage_report.random / .cheapest; scoring.choose(policy=). step_cost took a step's own measurement only from observations that called the model, so the two audits of stored outputs counted as unmeasured and a budget check priced them at the run's most expensive case per case: on ChartQA triage18 the 32 -> 64 FAIL expansion (912 s when run) was estimated at 3205 s, or 22215 s after an exploring arm had fitted tuned_lens on 4 cases, and every budget-tier arm stopped on "expand over budget" with budget to spare. A step's own cost now covers every observation that called the model or completed without calling it; the typical and worst-case prices of a step that never ran still come from model-calling observations only (scoring mvp3-score-5). --- CHANGELOG.md | 28 ++++++++++++ docs/agentic_benchmark.md | 4 +- evalrx/benchmark/run.py | 6 ++- evalrx/eval_agent/probing/controller.py | 40 ++++++++++------ evalrx/eval_agent/probing/scoring.py | 48 ++++++++++++++++---- tests/test_eval_agent/test_probing_chunks.py | 31 +++++++++++++ tests/test_eval_agent/test_probing_mvp3.py | 34 +++++++++++++- 7 files changed, 165 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4207f646..aa3403e7 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,22 @@ readings use the rule too. `answer_key` also applies the grader's yes/true aliases on `exact_or_numeric`. Rules version `mvp4-rules-5`; `agree_fn` is recorded in the report settings. +### Fixed — a budget check priced a step that ran without model calls at the run's worst case + +`step_cost` took a step's own measurement only from observations that called +the model, so the two audits of stored outputs (`answer_extraction_audit`, +`termination_audit`: no calls, next to no time) counted as never measured and a +budget check priced them at the run's most expensive case per case. An +expansion's estimate carried both over every new case: on ChartQA `triage18` +the 32 → 64 FAIL expansion (912 s when run) was estimated at 3205 s after +`patchscope` had run and at 22215 s after an exploring arm had fitted +`tuned_lens` on 4 cases (167.7 s per case), so every budget-tier arm stopped on +"expand over budget" with budget to spare, the exploring arms at 32 FAIL cases +whatever the tier (4000, 5500 or 7100 s). A step's own cost now covers every +observation that called the model or completed without calling it; the typical +and worst-case prices of a step that never ran still come from model-calling +observations only (scoring `mvp3-score-5`). + ### Fixed — a gradient pass keeps no graph through the media encoders; a case that does not fit is skipped `hf_local` ran the whole model under autograd when `CaptureSpec(with_grad=True)` @@ -41,6 +57,18 @@ and `generic_attention` also skip a case whose graph still does not fit validation (`triage17`) the failed chunk stopped both steps on the S route at 12 of 135 cases. +### Added — random and cheapest-first controls for the scored scheduler + +`--triage-scheduler random` and `--triage-scheduler cheapest` (reports +`triage_report.random.*` / `triage_report.cheapest.*`) take the scored +scheduler's candidate pool, budget, gain floor and stop rules and differ in the +pick only: a seeded uniform draw among the candidates at or above the gain +floor, or the lowest-cost one (an unpriced candidate last, ties by soft order). +Neither explores nor takes an explainer, so the scored scheduler without +exploration is their nearest value arm and the comparison isolates the value +ordering. Decisions record `choice: random | cheapest` and a rationale; +`scoring.choose(policy=)` carries the rule. + ### Added — the pool can be split into EXPLORE and CONFIRM by media content `--confirm-split-by media` (default `case`) draws the explore/confirm split over diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 3338ad58..64c4610b 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -35,7 +35,9 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. -**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet; one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the evidence spending, `--triage-explore-share` (default 0.1; the judge's calls are not counted), not of the decisions, and draws from its own targets — actions the value never takes: the next candidate of a route with too few FAIL cases to be active, and on each active route the representative of every other route's layer it does not own, when that step has readings to compare with the controls. Whenever a target fits — exploration's spending plus its conservative estimate (a budget check's) within the share — a seeded draw among them runs instead of the best candidate. Completing a target on its route is exploration too, paid from the share, until the cases measured so far show a reading outside its band (the verdicts' 95% interval): the step has then found something, and its completion is an incomplete step that T values like any other. The run stops once no candidate's gain reaches 0.01 and no target fits. `--triage-explore-from candidates` (an ablation) draws from the candidates other than the best instead, alternatives included. `--triage-weights` (e.g. `c=0`) sets the weights of D, T, C and R for ablations. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. +**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet (a budget check prices such a step at the run's most expensive case per case instead, so an unknown tool cannot look cheap; a step that ran without calling the model, like the audits of stored outputs, is priced at what it measured); one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the evidence spending, `--triage-explore-share` (default 0.1; the judge's calls are not counted), not of the decisions, and draws from its own targets — actions the value never takes: the next candidate of a route with too few FAIL cases to be active, and on each active route the representative of every other route's layer it does not own, when that step has readings to compare with the controls. Whenever a target fits — exploration's spending plus its conservative estimate (a budget check's) within the share — a seeded draw among them runs instead of the best candidate. Completing a target on its route is exploration too, paid from the share, until the cases measured so far show a reading outside its band (the verdicts' 95% interval): the step has then found something, and its completion is an incomplete step that T values like any other. The run stops once no candidate's gain reaches 0.01 and no target fits. `--triage-explore-from candidates` (an ablation) draws from the candidates other than the best instead, alternatives included. `--triage-weights` (e.g. `c=0`) sets the weights of D, T, C and R for ablations. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. + +**Controls.** `--triage-scheduler random` and `--triage-scheduler cheapest` (reports `triage_report.random.*` / `triage_report.cheapest.*`) decide over the scored scheduler's candidates with its budget, gain floor and stop rules, and differ in the pick only: a seeded uniform draw among the candidates at or above the gain floor, or the lowest-cost one (ties by soft order). They never explore and take no explainer, so the scored scheduler without exploration is their nearest value arm; the comparison isolates the value ordering from the candidate set. **Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 2c05d3ff..7a6bb09f 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -164,9 +164,11 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP p.add_argument("--triage-max-actions", type=int, default=12, help="triage_active: decisions after the battery (expansions + route follow-ups; the " "scored scheduler's further chunks of a step it already took do not count)") - p.add_argument("--triage-scheduler", choices=["rules", "scored"], default="rules", + p.add_argument("--triage-scheduler", choices=["rules", "scored", "random", "cheapest"], default="rules", help="triage_active: rules = MVP-2 fixed rounds over the routes' layers; scored = MVP-3 " - "value per cost, U = q*[D+T+C-R]+/(c+eps) (report: triage_report.scored.*)") + "value per cost, U = q*[D+T+C-R]+/(c+eps) (report: triage_report.scored.*); random / " + "cheapest = controls over the scored candidates and stop rules that differ in the pick " + "only (a seeded uniform draw, or the lowest cost), never exploring") p.add_argument("--triage-budget-usd", type=float, default=0.0, help="triage_active: USD cap on priced API models (0 = none), charged like " "--triage-budget-sec") diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index fe640151..605c1eec 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -147,7 +147,9 @@ from evalrx.core.case import CaseBatch POLICY_VERSION = "mvp2-0" -SCHEDULERS = ("rules", "scored") +SCHEDULERS = ("rules", "scored", "random", "cheapest") +#: The schedulers that decide over the scored candidate pool: the value, or a control differing in the pick only. +VALUE_SCHEDULERS = ("scored", "random", "cheapest") #: Neutral wrappers around the question, kept verbatim (with its output #: contract): the meaning cannot change, only the surface. A wrapper whose @@ -644,7 +646,11 @@ def run_triage( OpenAI-compatible endpoint drops them): when it does not, steps run without their ``gen_kwargs`` and are gated on the host's output cap. - scheduler: ``"rules"`` (MVP-2: rounds over the routes' soft layer order) + scheduler: ``"rules"`` (MVP-2: rounds over the routes' soft layer order); + ``"random"`` / ``"cheapest"``: controls over the scored scheduler's + candidates and stop rules, differing in the pick only (a seeded + uniform draw, or the lowest cost); they never explore and take no + explainer (report ``triage_report.random`` / ``.cheapest``) or ``"scored"`` (MVP-3: the candidate with the highest U = q·[D+T+C−R]₊/(c+ε), see :mod:`.scoring`). Both share the ledger; the scored report is ``triage_report.scored``. @@ -671,7 +677,8 @@ def run_triage( if scheduler not in SCHEDULERS: raise ValueError(f"scheduler must be one of {SCHEDULERS}; got {scheduler!r}") if explainer is not None and scheduler != "scored": - raise ValueError("explanations give D to the scored scheduler; the rules scheduler does not read them") + raise ValueError("explanations give D to the scored scheduler; the other schedulers do not read them") + share = float(explore_share) if scheduler == "scored" else 0.0 # the controls never explore if explore_from not in ("targets", "candidates"): raise ValueError(f"explore_from must be 'targets' or 'candidates'; got {explore_from!r}") weights = weights or Weights() @@ -747,7 +754,7 @@ def n_actions() -> int: """What ``max_actions`` caps: expansions, follow-ups and scheduled battery steps. The scored scheduler's further chunks of a step it already took (``extend``) do not count: chunking a step must not use up the cap a whole step used before.""" - kinds = ("expand", "follow_up", "battery") if scheduler == "scored" else spending + kinds = ("expand", "follow_up", "battery") if scheduler in VALUE_SCHEDULERS else spending return sum(1 for d in decisions if d["kind"] in kinds) def expansion_plan() -> "tuple[Any, Any, list[str], float | None] | None": @@ -1213,7 +1220,8 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], return pool, filtered, axis explored: dict[str, float] = {} # what exploration decisions spent, per cost axis - if scheduler == "scored": + if scheduler in VALUE_SCHEDULERS: + policy = "value" if scheduler == "scored" else scheduler current: "ExplanationSet | None" = None while stop is None: records = triage(sample, run.evidence) @@ -1237,14 +1245,15 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], pool, filtered, axis = scored_pool(records, gaps, states, options, growing, live, outcome_of) targets: "list[Scored] | None" = None held_targets: list[dict[str, Any]] = [] - if explore_from == "targets": + if explore_from == "targets" and policy == "value": targets, completions, held, held_targets = exploration_targets(records, states, growing, axis, outcome_of) pool, filtered = pool + completions, filtered + held # exploration's share is of the evidence: the judge's calls are not an opportunity to explore spent = run.charged(axis) - float(run.judge_cost.get(axis) or 0.0) - pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_share=explore_share, - explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain, targets=targets) + pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_share=share, + explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain, targets=targets, + policy=policy) if pick is None: over = [f for f in filtered if not f["reason"].startswith("batch-dependent")] # a candidate the budget filtered out binds before the gain floor does @@ -1265,7 +1274,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], and c.order < pick.order] extra = {"choice": why, "scoring_version": SCORING_VERSION, "axis": axis, "U": round(pick.U, 6), "gain": round(pick.gain, 6), - "rationale": _scored_rationale(pick, why, explored.get(axis, 0.0), spent, explore_share), + "rationale": _scored_rationale(pick, why, explored.get(axis, 0.0), spent, share), **({"alternative_to": pick.alternative_to} if pick.alternative_to else {}), **({"explore_target": pick.note} if why == "explore" and pick.note else {}), "candidates": [c.row() for c in ranked], "filtered": filtered, @@ -1396,10 +1405,10 @@ def account() -> None: # what an exploration decision spent counts against its report = { "policy": POLICY_VERSION, "scheduler": scheduler, - **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_share": explore_share, + **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_share": share, "explore_from": explore_from, "explored": {a: round(v, 6) for a, v in explored.items()}, - "min_gain": min_gain, "min_cover": min_cover} if scheduler == "scored" else {}), + "min_gain": min_gain, "min_cover": min_cover} if scheduler in VALUE_SCHEDULERS else {}), "rules_version": RULES_VERSION, "model": model_identity, "sample": draw.to_dict(), @@ -1448,13 +1457,18 @@ def _scored_rationale(pick: Scored, why: str, explored: float, spent: float, sha target = f" of {pick.note}" if pick.note else "" return (f"exploration{target} ({explored:.4g} of the {spent:.4g} spent on evidence so far went to " f"exploration; share {share}): " + terms) + if why == "random": + return f"control: a seeded uniform draw among the candidates at or above the gain floor: {terms}" + if why == "cheapest": + return f"control: the cheapest candidate at or above the gain floor: {terms}" alt = f"; an alternative to {pick.alternative_to}" if pick.alternative_to else "" return f"highest value: {terms}{alt}" def report_name(scheduler: str, explained: bool = False) -> str: - """``triage_report`` (rules), ``triage_report.scored``, or ``triage_report.scored_d`` (with D): - the arms of a comparison can share one probing directory and its ledger.""" + """``triage_report`` (rules), ``triage_report.scored``, ``triage_report.scored_d`` (with D), or + ``triage_report.random`` / ``triage_report.cheapest`` (the controls): the arms of a comparison can + share one probing directory and its ledger.""" if scheduler == "rules": return "triage_report" return f"triage_report.{scheduler}" + ("_d" if explained else "") diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/probing/scoring.py index 3d7d75ad..369cd273 100644 --- a/evalrx/eval_agent/probing/scoring.py +++ b/evalrx/eval_agent/probing/scoring.py @@ -76,10 +76,18 @@ and no target fits (the minimum exploration is met). ``explore_from="candidates"`` (an ablation) draws from the candidates other than the top one instead, alternatives included. + +**Controls.** Two schedulers take the scored scheduler's candidates and stop +rules and differ only in the pick, so a comparison with them isolates the +value ordering: ``random`` draws uniformly (seeded) among the candidates at or +above the gain floor, ``cheapest`` takes the lowest-cost one (an unpriced +candidate last, ties by soft order). Neither explores or reads explanations +(D is 0): their nearest value arm is the scored scheduler without exploration. """ from __future__ import annotations +import math import random from dataclasses import dataclass, field from typing import Any @@ -87,7 +95,7 @@ from evalrx.eval_agent.probing.actions import OK, UNSUPPORTED, PlanStep from evalrx.eval_agent.probing.evidence import StepEvidence -SCORING_VERSION = "mvp3-score-4" +SCORING_VERSION = "mvp3-score-5" @dataclass(frozen=True) @@ -178,14 +186,17 @@ def step_cost(step: PlanStep, n_cases: int, evidence: dict[str, StepEvidence], a """Cost of running *step* on *n_cases* new cases, and its basis. No analyzer-specific prior: a step that has run in this run is priced at its - own measured cost per case (``own``). One that has not is priced at the - run's ``typical`` (median) cost per case when ranking, or its ``max`` when - checking a budget, so an unknown tool cannot look cheap; ``None`` before - anything was measured. + own measured cost per case (``own``) over every observation that called the + model or completed without calling it (an audit of stored outputs costs what + it measured: next to nothing). One that has not run is priced at the run's + ``typical`` (median) cost per case of the model-calling observations when + ranking, or their ``max`` when checking a budget, so an unknown tool cannot + look cheap; ``None`` before anything was measured. """ ev = evidence.get(step.name) rows = [(_amount(o.cost, axis), len(o.planned_ids)) for o in (ev.chunks if ev else []) - if (o.cost or {}).get("calls") and o.planned_ids and o.cost.get(axis) is not None] + if ((o.cost or {}).get("calls") or o.status == OK) and o.planned_ids + and (o.cost or {}).get(axis) is not None] if rows and sum(k for _, k in rows): return sum(s for s, _ in rows) / sum(k for _, k in rows) * n_cases, "own" pool = per_case_costs(evidence, axis) @@ -255,15 +266,34 @@ def value(s: Scored, weights: Weights, axis: str) -> Scored: return s +#: How a decision picks among the scored candidates: the value (the scored scheduler) or a control. +POLICIES = ("value", "random", "cheapest") + + def choose(candidates: list[Scored], *, decision_no: int, seed: int, explore_share: float, explored: float, - spent: float, min_gain: float, targets: "list[Scored] | None" = None) -> "tuple[Scored | None, str]": - """The candidate to run, and why: ``best`` / ``explore`` / ``below_threshold`` / ``none``. + spent: float, min_gain: float, targets: "list[Scored] | None" = None, + policy: str = "value") -> "tuple[Scored | None, str]": + """The candidate to run, and why: ``best`` / ``explore`` / ``random`` / ``cheapest`` / + ``below_threshold`` / ``none``. *explored* and *spent* are what exploration and the run's evidence have cost so far, on the candidates' cost axis. Exploration draws from *targets*, the candidates only it takes; with ``targets=None`` it draws from the other candidates instead (below the gain floor, from all of them). A seeded draw among those that keep exploration within *explore_share* of the - spending runs instead of the best.""" + spending runs instead of the best. + + *policy* ``"value"`` is the scored scheduler. The controls take the candidates at or above the + gain floor and never explore: ``"random"`` a seeded uniform draw among them, ``"cheapest"`` + the lowest-cost one (an unpriced candidate last, ties by soft order).""" + if policy not in POLICIES: + raise ValueError(f"policy must be one of {POLICIES}; got {policy!r}") + if policy != "value": + eligible = [s for s in candidates if s.gain >= min_gain] + if not eligible: + return None, "below_threshold" if candidates else "none" + if policy == "random": + return random.Random(f"{seed}:{decision_no}").choice(eligible), "random" + return min(eligible, key=lambda s: (s.cost if s.cost is not None else math.inf, s.order)), "cheapest" ranked = sorted(candidates, key=lambda s: (-s.U, s.order)) best = ranked[0] if ranked else None if targets is None: diff --git a/tests/test_eval_agent/test_probing_chunks.py b/tests/test_eval_agent/test_probing_chunks.py index 77193e89..7017e0c9 100644 --- a/tests/test_eval_agent/test_probing_chunks.py +++ b/tests/test_eval_agent/test_probing_chunks.py @@ -109,3 +109,34 @@ def test_further_chunks_of_a_taken_step_do_not_use_up_max_actions(tmp_path): route_cases = [r for r in report["routes"] if r["route"] == taken["route"]][0] layer = next(x for x in route_cases["layers"] if x["rule_id"] == taken["rule_id"]) assert layer["state"] == "done" # the step ran on all of its route's cases + + +def test_the_control_schedulers_run_over_the_scored_pool_and_never_explore(tmp_path): + import pytest + + from evalrx.eval_agent.probing.controller import report_name + from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table + + cases, table = _pope_like() + reports = {} + for scheduler in ("random", "cheapest"): + reports[scheduler] = run_triage(_Table(table), cases, **_kw(tmp_path / scheduler, max_fail=4, min_route_fail=1, + chunk=2, scheduler=scheduler, explore_share=0.5)) + for scheduler, report in reports.items(): + assert report["scheduler"] == scheduler and report["explore_share"] == 0.0 and report["explored"] == {} + chosen = [d for d in report["decisions"] if "choice" in d] + assert chosen and {d["choice"] for d in chosen} == {scheduler} + assert all(d["rationale"].startswith("control:") for d in chosen) + assert report["stop"]["reason"] in ("below_threshold", "no_candidate", "max_actions", "budget") + assert report_name(scheduler) == f"triage_report.{scheduler}" + # the cheapest control takes the lowest-cost candidate at or above the gain floor at every decision + floor = reports["cheapest"]["min_gain"] + steps = [d for d in reports["cheapest"]["decisions"] + if d.get("choice") == "cheapest" and d["kind"] in ("follow_up", "battery", "extend")] + assert steps + for d in steps: + priced = [c for c in d["candidates"] if c["cost"] is not None and c["gain"] >= floor] + taken = next(c for c in priced if c["key"] == d["key"] and c.get("route") == d.get("route")) + assert taken["cost"] == min(c["cost"] for c in priced) + with pytest.raises(ValueError): + run_triage(_Table(table), cases, **_kw(tmp_path / "x", scheduler="random", explainer=object())) diff --git a/tests/test_eval_agent/test_probing_mvp3.py b/tests/test_eval_agent/test_probing_mvp3.py index c85cf8cd..4070630c 100644 --- a/tests/test_eval_agent/test_probing_mvp3.py +++ b/tests/test_eval_agent/test_probing_mvp3.py @@ -14,7 +14,7 @@ import json from evalrx.eval_agent.probing import BATTERY, LAYERS, run_triage -from evalrx.eval_agent.probing.actions import OK, UNFAITHFUL, Observation +from evalrx.eval_agent.probing.actions import OK, UNFAITHFUL, UNSUPPORTED, Observation from evalrx.eval_agent.probing.compare import compare from evalrx.eval_agent.probing.evidence import StepEvidence from evalrx.eval_agent.probing.rules import candidate_steps @@ -57,12 +57,44 @@ def test_costs_come_from_the_steps_own_measurement_else_the_runs_typical_or_wors assert sorted(per_case_costs(ev, "wall_sec")) == [1.0, 4.0, 5.0] # no model call: not a cost sample assert step_cost(sc, 3, ev, "wall_sec") == (15.0, "own") # 5 s per case, its own assert step_cost(ko, 3, ev, "wall_sec") == (6.0, "own") # 6 s over 3 cases + # ran without calling the model: priced at what it measured (nothing), not as unmeasured -- + # else a budget check prices every audit of the next expansion at the run's worst case + assert step_cost(_step("answer_extraction_audit"), 64, ev, "wall_sec", unmeasured="max") == (0.0, "own") + unsupported = {"gradcam": StepEvidence(_step("gradcam"), [_obs("g", ["a"], status=UNSUPPORTED, + cost={"wall_sec": 0.0, "calls": {}})])} + assert step_cost(_step("gradcam"), 2, {**ev, **unsupported}, "wall_sec", unmeasured="max") == (10.0, "max") # never run: priced at the run's median case when ranking, its worst case in a budget check assert step_cost(_step("gradcam"), 2, ev, "wall_sec") == (8.0, "typical") assert step_cost(_step("gradcam"), 2, ev, "wall_sec", unmeasured="max") == (10.0, "max") assert step_cost(_step("causal_trace"), 2, {}, "wall_sec") == (None, "none") +def test_the_random_and_cheapest_controls_pick_among_the_same_candidates_without_exploring(): + import pytest + + def s(key, U, gain, order, cost=10.0): + return Scored(kind="follow_up", key=key, U=U, gain=gain, order=order, cost=cost) + + pool = [s("late", 0.5, 0.2, (1, 2), cost=10.0), s("early", 0.5, 0.2, (1, 0), cost=30.0), + s("cheap", 0.1, 0.3, (0, 0), cost=1.0), s("zero", 0.0, 0.0, (0, 1), cost=0.5)] + # exploration would fit here (90 spent, share 0.5): the controls still never explore + kw = dict(seed=0, explore_share=0.5, min_gain=0.01, explored=0.0, spent=90.0) + assert choose(pool, decision_no=0, **kw)[1] == "explore" + draws = [choose(pool, decision_no=n, policy="random", **kw) for n in range(30)] + assert {why for _, why in draws} == {"random"} and {p.key for p, _ in draws} == {"late", "early", "cheap"} + assert choose(pool, decision_no=3, policy="random", **kw) == choose(pool, decision_no=3, policy="random", **kw) + assert choose(pool, decision_no=0, policy="cheapest", **kw) == (pool[2], "cheapest") # not "zero": below the floor + # cheapest: ties by soft order, an unpriced candidate last + tie = [s("b", 0.5, 0.2, (1, 1), cost=5.0), s("a", 0.5, 0.2, (1, 0), cost=5.0), s("u", 0.9, 0.9, (0, 0), cost=None)] + assert choose(tie, decision_no=0, policy="cheapest", **kw)[0].key == "a" + assert choose([tie[2]], decision_no=0, policy="cheapest", **kw)[0].key == "u" + # the same stops as the scored scheduler + assert choose([pool[3]], decision_no=0, policy="random", **kw) == (None, "below_threshold") + assert choose([], decision_no=0, policy="cheapest", **kw) == (None, "none") + with pytest.raises(ValueError): + choose(pool, decision_no=0, policy="greedy", **kw) + + def test_coverage_gain_is_the_gap_removed_over_all_units(): units = {"S1:yes": {"rule_id": "S1", "stratum": "yes", "need": 2, "measured": 0, "gap": 1.0, "_ids": ["a", "b"]}, "S1:no": {"rule_id": "S1", "stratum": "no", "need": 2, "measured": 1, "gap": 0.5, "_ids": ["c", "d"]}, From 479b95f9511b579fd38794bad1de9419ca1e4ece Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:38:03 -0700 Subject: [PATCH 15/26] triage: an expansion's battery runs chunk by chunk, each chunk checked against the budget The decision to expand was checked once, on the sum of the battery steps' estimates over the new cases, and the battery then ran unchecked. On ChartQA triage18 the 64 -> 128 FAIL expansion was estimated at 1668 s from the cases measured so far and cost 2413 s, so the 4000 s arms that expanded charged 4220-4548 s. do_expand now runs every immediate step on one chunk of the new cases before any step moves to the next, with the budget checked before each chunk on the cost measured so far, like every other action. A refusal stops the run (stop budget, pending expansion): the chunks measured so far are routed on every check, a check that never ran on the remaining new cases is untested, and the run overshoots by at most one chunk of one step. The budget_checked parameter of run_step is gone. Test: an expansion whose cases cost four times the estimate stops at the budget with one whole chunk measured, for both schedulers. --- CHANGELOG.md | 14 ++++ docs/agentic_benchmark.md | 2 +- evalrx/eval_agent/probing/controller.py | 66 +++++++++++++++---- tests/test_eval_agent/test_probing_chunks.py | 67 ++++++++++++++++++++ 4 files changed, 136 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa3403e7..b99d8049 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,20 @@ observation that called the model or completed without calling it; the typical and worst-case prices of a step that never ran still come from model-calling observations only (scoring `mvp3-score-5`). +### Fixed — an expansion's battery ran past the budget + +The decision to expand was checked once, on the sum of the battery steps' +estimates over the new cases, and the battery then ran unchecked: on ChartQA +`triage18` the 64 → 128 FAIL expansion was estimated at 1668 s from the cases +measured so far and cost 2413 s (the later cases were dearer), so the 4000 s +arms that expanded charged 4220–4548 s. The battery now runs chunk by chunk, +every immediate step on one chunk of the new cases before any step moves to the +next, with the budget checked before each chunk on the cost measured so far, +like every other action; a refusal stops the run (`stop: budget`, pending +`expansion`) with the chunks measured so far routed and a check that never ran +on the remaining new cases untested (a case with no fired check is X), so an +expansion overshoots by at most one chunk of one step. + ### Fixed — a gradient pass keeps no graph through the media encoders; a case that does not fit is skipped `hf_local` ran the whole model under autograd when `CaptureSpec(with_grad=True)` diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 64c4610b..d251ce94 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -31,7 +31,7 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="prediction")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="prediction", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. -**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Every step's per-case rows are independent of the batch, so steps run on the new cases alone and keep the old rows: `embed_lens` and `patchscope` tell question words (and `embed_lens` recurring media words, from the first 16 distinct images) from a fixed reference — EXPLORE in the sampler's rank order — instead of the batch, `tuned_lens` is fit once on the first 32 of those cases (cached on the model), and `causal_trace` seeds its noise from each case's content instead of its position; `self_consistency` draws each case's samples under a seed of its content too, so the U sampling check is the same in every run. No route reads `embed_lens` or `patchscope`, so they still wait until the sample stops growing. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). +**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Every step's per-case rows are independent of the batch, so steps run on the new cases alone and keep the old rows: `embed_lens` and `patchscope` tell question words (and `embed_lens` recurring media words, from the first 16 distinct images) from a fixed reference — EXPLORE in the sampler's rank order — instead of the batch, `tuned_lens` is fit once on the first 32 of those cases (cached on the model), and `causal_trace` seeds its noise from each case's content instead of its position; `self_consistency` draws each case's samples under a seed of its content too, so the U sampling check is the same in every run. No route reads `embed_lens` or `patchscope`, so they still wait until the sample stops growing. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. An expansion's battery runs chunk by chunk too, every immediate step on one chunk of the new cases before any step moves to the next, each chunk checked against the budget (the decision to expand is checked on an estimate from the cases measured so far, which undershot by 30 % on ChartQA where the later cases were dearer); a refusal stops the run there, the chunks measured so far are routed, and a check that never ran on the remaining new cases is untested (a case with no fired check is X). Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). **Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 605c1eec..9bdb6c51 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -36,7 +36,11 @@ run once the expansions have settled. Steps run in chunks of ``chunk`` cases (FAIL and PASS alternating), with the - budget checked before each chunk on the cost measured so far. + budget checked before each chunk on the cost measured so far. An expansion's + battery runs every step on one chunk of the new cases before any step moves to + the next, so a refusal part-way stops the run with whole cases measured; a check + that never ran on the rest of the new cases is untested (a case with no fired + check is X). 3. **Follow-ups.** Each active route proposes its next layer's candidate (see :mod:`~evalrx.eval_agent.probing.rules`), and the candidate runs on the @@ -434,8 +438,7 @@ def _adopt(self, ev: StepEvidence, step_id: str, target: "list[str]", return record def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: int, - rule_id: "str | None" = None, route: "str | None" = None, - budget_checked: bool = False) -> "dict[str, Any] | None": + rule_id: "str | None" = None, route: "str | None" = None) -> "dict[str, Any] | None": """Bring *step*'s evidence up to date on *target*; the last execution record, or ``None`` when every case is already covered. @@ -472,7 +475,7 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: record = None for part in self.chunks(step, todo): out = self._run_part(step, part, ev, base, analyzer, version, context, step_id, config, - kind=kind, revision=revision, rule_id=rule_id, budget_checked=budget_checked) + kind=kind, revision=revision, rule_id=rule_id) record = out if out is not None else record if out is not None and out["status"] == FAILED and not out.get("reused"): # an execution that raised costs time and would likely raise again on the rest @@ -485,7 +488,7 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: def _run_part(self, step: PlanStep, target: "list[str]", ev: StepEvidence, base: dict[str, Any], analyzer: Any, version: str, context: dict[str, Any], step_id: str, config: dict[str, Any], *, - kind: str, revision: int, rule_id: "str | None", budget_checked: bool) -> "dict[str, Any] | None": + kind: str, revision: int, rule_id: "str | None") -> "dict[str, Any] | None": """One case set of :meth:`run_step`: read back what exists, else execute.""" todo = ev.todo(target) if not todo: @@ -494,7 +497,7 @@ def _run_part(self, step: PlanStep, target: "list[str]", ev: StepEvidence, base: # charged with the evidence read, so a resumed run (or a second scheduler on the # same ledger) must skip what the run that executed it could not afford. estimate = self.estimate_sec(step, len(todo)) - why = None if budget_checked else self.over_budget(estimate, self.estimate_usd(step, len(todo))) + why = self.over_budget(estimate, self.estimate_usd(step, len(todo))) if why is not None: self.ledger.trace({**base, "event": "skipped", "status": SKIPPED, "reason": why, "n_cases": len(todo)}) self.blocked[step.name] = why @@ -777,7 +780,16 @@ def not_possible(gaps: list[dict[str, Any]]) -> dict[str, Any]: "reason": (f"the sample has the cap of {max_fail} FAIL cases" if len(draw.fail_ids) >= max_fail else f"EXPLORE has no FAIL case beyond the {n_available} drawn")} - def do_expand(plan: Any, gaps: list[dict[str, Any]], extra: dict[str, Any]) -> None: + def do_expand(plan: Any, gaps: list[dict[str, Any]], extra: dict[str, Any]) -> "dict[str, Any] | None": + """Adopt the next nested sample and run the immediate battery on its new cases; the + execution record the budget refused when that cut the battery short, else ``None``. + + The decision to expand was checked on an estimate from the cases measured so far; + the battery then runs chunk by chunk, every step on one chunk of the new cases + before any step moves to the next, each chunk checked against the budget on the + cost measured so far. A refusal stops the run there: the chunks measured so far are + routed on every check, and a check that never ran on the remaining new cases is + untested (a case with no fired check is X).""" nonlocal sample, draw, revision bigger, bigger_draw, new_ids, estimate = plan decide({"kind": "expand", "rule_id": "E1", "from_fail": len(draw.fail_ids), @@ -791,9 +803,33 @@ def do_expand(plan: Any, gaps: list[dict[str, Any]], extra: dict[str, Any]) -> N manifest() ledger.trace({"event": "revision", "revision": revision, "n_fail": len(draw.fail_ids), "n_pass": len(draw.pass_ids), "n_new_cases": len(new_ids), "scheduler": scheduler}) + reuse_steps = [s for s in immediate if s.reuse] + failed: set[str] = set() # a step that raised on a chunk is not run on the rest of this expansion + + def skip(step: PlanStep) -> bool: + ev = run.evidence.get(step.name) + return step.name in failed or (ev is not None and ev.refused() is not None) + + for part in (run.chunks(reuse_steps[0], new_ids) if reuse_steps else []): + for step in reuse_steps: + if skip(step): + continue + record = run.run_step(step, part, kind="expansion", revision=revision, rule_id="E1") + if record is None: + continue + if record["status"] == SKIPPED: + return record + if record["status"] == FAILED and not record.get("reused"): + failed.add(step.name) + # the batch-dependent route steps run on the whole sample, once; and a reuse step takes + # up any case an earlier revision left uncovered (its chunks raised or were refused then) for step in immediate: - run.run_step(step, list(draw.case_ids), kind="expansion", revision=revision, rule_id="E1", - budget_checked=True) + if skip(step): + continue + record = run.run_step(step, list(draw.case_ids), kind="expansion", revision=revision, rule_id="E1") + if record is not None and record["status"] == SKIPPED: + return record + return None by_rule = {x.rule_id: x for x in layers} step_layers: dict[tuple[str, str], Layer] = {} @@ -1293,8 +1329,11 @@ def account() -> None: # what an exploration decision spent counts against its explored[a] = explored.get(a, 0.0) + run.charged(a) - before[a] if pick.kind == "expand": - do_expand(pick.payload, gaps, extra) + cut = do_expand(pick.payload, gaps, extra) account() + if cut is not None: + stop = {"reason": "budget", "detail": cut["reason"], "pending": "expansion"} + break round_no += 1 continue proposal = pick.payload @@ -1334,8 +1373,11 @@ def account() -> None: # what an exploration decision spent counts against its decide({"kind": "expand_skipped", "rule_id": "E1", "reason": why, "gaps": gaps, "estimate_sec": plan[3]}) continue - do_expand(plan, gaps, {"rationale": "an evidence gap a larger nested sample can close; expansion " - "precedes the routes' candidates because it revises the routes"}) + cut = do_expand(plan, gaps, {"rationale": "an evidence gap a larger nested sample can close; expansion " + "precedes the routes' candidates because it revises the routes"}) + if cut is not None: + stop = {"reason": "budget", "detail": cut["reason"], "pending": "expansion"} + break continue expansion_note = not_possible(gaps) decide({"kind": "expand_not_possible", "rule_id": "E1", **expansion_note}) diff --git a/tests/test_eval_agent/test_probing_chunks.py b/tests/test_eval_agent/test_probing_chunks.py index 7017e0c9..b78b9c30 100644 --- a/tests/test_eval_agent/test_probing_chunks.py +++ b/tests/test_eval_agent/test_probing_chunks.py @@ -12,6 +12,8 @@ from __future__ import annotations +import json + import pytest import evalrx.eval_agent.probing.controller as controller @@ -140,3 +142,68 @@ def test_the_control_schedulers_run_over_the_scored_pool_and_never_explore(tmp_p assert taken["cost"] == min(c["cost"] for c in priced) with pytest.raises(ValueError): run_triage(_Table(table), cases, **_kw(tmp_path / "x", scheduler="random", explainer=object())) + + +EXPANSION_SEC = 4.0 # an expansion's cases cost four times what the first draw's did + + +@pytest.fixture +def dearer_expansion(monkeypatch): + """One second per case on the first draw, four on an expansion's new cases: the estimate the + decision to expand is checked on (the cases measured so far) undershoots by a factor of four.""" + real = controller.execute + + def execute(action, *args, **kwargs): + obs = real(action, *args, **kwargs) + if obs.cost.get("calls"): + obs.cost["wall_sec"] = (EXPANSION_SEC if action.source == "E1" else 1.0) * len(obs.planned_ids) + return obs + + monkeypatch.setattr(controller, "execute", execute) + + +def _planned(out, report, kind): + """Case sets of the executions of *kind* that ran fresh, in execution order.""" + ledger = controller.Ledger(out) + return [frozenset(ledger.settled(e["action_id"]).planned_ids) for e in report["executions"] + if e["kind"] == kind and e["status"] == "ok" and not e["reused"]] + + +@pytest.mark.parametrize("scheduler", ["rules", "scored"]) +def test_an_expansion_dearer_than_its_estimate_stops_at_the_budget_with_whole_cases_measured( + tmp_path, dearer_expansion, scheduler): + cases, table = _pope_like() + kw = dict(max_fail=8, min_route_fail=1, chunk=4, scheduler=scheduler) + full = run_triage(_Table(table), cases, **_kw(tmp_path / "full", **kw)) + (expand,) = [d for d in full["decisions"] if d["kind"] == "expand"] + rows = full["executions"] + first = next(i for i, e in enumerate(rows) if e["kind"] == "expansion") + cost = lambda e: float((e.get("cost") or {}).get("wall_sec") or 0.0) if not e["reused"] else 0.0 # noqa: E731 + before, actual = sum(cost(e) for e in rows[:first]), sum(cost(e) for e in rows if e["kind"] == "expansion") + # twice the estimate fits the budget, the real cost does not: an unchecked battery would overshoot + budget = before + 2 * expand["estimate_sec"] + 1.0 + assert expand["estimate_sec"] < actual / 2 and before + actual > budget + 4 * EXPANSION_SEC + + report = run_triage(_Table(table), cases, **_kw(tmp_path / "b", budget_sec=budget, **kw)) + assert report["stop"]["reason"] == "budget" and report["stop"]["pending"] == "expansion" + assert [d["kind"] for d in report["decisions"] if d["kind"] == "expand"] == ["expand"] + assert report["cost"]["charged"]["wall_sec"] <= budget + 4 * EXPANSION_SEC # at most one chunk of one step + # chunk-major: every step ran on the first chunk of new cases before any step took the second + parts = _planned(tmp_path / "b", report, "expansion") + order = [p for i, p in enumerate(parts) if i == 0 or p != parts[i - 1]] + assert len(order) == len(set(order)) and len(parts) > 1 + # the chunk measured in full is routed on every check; at most one chunk is part-measured, and a + # check that never ran on it is untested, not read off anything + manifest = json.loads((tmp_path / "b" / "split_manifest.json").read_text()) + new = set(manifest["revisions"][1]["case_ids"]) - set(manifest["revisions"][0]["case_ids"]) + by_id = {r["case_id"]: r for r in report["cases"]} + covered: dict[str, set[str]] = {} + for e, ids in zip([e for e in report["executions"] if e["kind"] == "expansion" and e["status"] == "ok" + and not e["reused"]], parts): + covered.setdefault(e["key"], set()).update(ids) + whole = set.intersection(*covered.values()) + assert whole and len(new - whole) <= 4 and whole < new + assert all(by_id[cid]["U"]["state"] != "untested" and not by_id[cid]["x_reasons"] for cid in whole) + assert all((by_id[cid]["U"]["state"] == "untested") == (cid not in covered["self_consistency"]) for cid in new) + skipped = [e for e in report["executions"] if e["kind"] == "expansion" and e["status"] == "skipped"] + assert len(skipped) == 1 and "exceeds" in skipped[0]["reason"] From d6b9a2fda8e39aa3f66ef62e8913dcd888e1b38f Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:06:24 -0700 Subject: [PATCH 16/26] triage: protocol scripts kept in the repo, dead code removed, compare has a CLI, docs synced The drivers of the multi-arm scheduler comparison (run_triage17.sh, run_triage18.sh and its phase 2 and 3 variants, the GPU launcher) and the analysis scripts behind the design document's tables (the union validation validate_arms.py, the budget-matched discovery curve, the U re-count under the tolerant agreement rule) lived in a job's scratch directory; they are now examples/benchmark/tools/triage/ with a README, the machine-specific paths taken from the environment. Removed what later code had superseded: Ledger.spent / spent_wall_sec (the budget is charged by _Run.charged), StepEvidence.sec_per_case (costs come from scoring.step_cost), the run_triage_mvp0 alias (tests call run_triage) and the sampler's _rank alias. compare.py gets a main() (python -m evalrx.eval_agent.probing.compare a.json b.json [--json]). A layer that narrows its route's cases (X1) states its filter in its state (case_filter). Stale strings updated: the package and controller docstrings no longer describe MVP-2, --m1-policy says when a judge is built and that CONFIRM reaches only the validator; the design document has a current status header and a list of the remaining gaps between design and implementation. POLICY_VERSION stays mvp2-0 on purpose: it is part of every action identity. Tests: full suite 2826 passed / 16 skipped; test_probing_chunks 8 passed separately; ruff clean (the new scripts too). --- CHANGELOG.md | 22 +++++ docs/agentic_benchmark.md | 2 + evalrx/benchmark/run.py | 5 +- evalrx/eval_agent/probing/__init__.py | 27 +++--- evalrx/eval_agent/probing/compare.py | 22 +++++ evalrx/eval_agent/probing/controller.py | 24 ++--- evalrx/eval_agent/probing/evidence.py | 7 -- evalrx/eval_agent/probing/ledger.py | 7 -- evalrx/eval_agent/probing/rules.py | 7 +- evalrx/eval_agent/probing/sampler.py | 6 +- examples/benchmark/tools/triage/README.md | 70 +++++++++++++++ examples/benchmark/tools/triage/_common.sh | 78 ++++++++++++++++ .../benchmark/tools/triage/discovery_curve.py | 80 +++++++++++++++++ .../tools/triage/launch_when_free.sh | 20 +++++ examples/benchmark/tools/triage/recount_u.py | 89 +++++++++++++++++++ .../benchmark/tools/triage/run_triage17.sh | 17 ++++ .../benchmark/tools/triage/run_triage18.sh | 27 ++++++ .../tools/triage/run_triage18_phase2.sh | 30 +++++++ .../tools/triage/run_triage18_phase3.sh | 32 +++++++ .../benchmark/tools/triage/validate_arms.py | 51 +++++++++++ tests/test_eval_agent/test_probing_mvp0.py | 20 ++--- tests/test_eval_agent/test_probing_mvp2.py | 11 +++ tests/test_eval_agent/test_probing_mvp3b.py | 8 +- 23 files changed, 603 insertions(+), 59 deletions(-) create mode 100644 examples/benchmark/tools/triage/README.md create mode 100644 examples/benchmark/tools/triage/_common.sh create mode 100644 examples/benchmark/tools/triage/discovery_curve.py create mode 100755 examples/benchmark/tools/triage/launch_when_free.sh create mode 100644 examples/benchmark/tools/triage/recount_u.py create mode 100755 examples/benchmark/tools/triage/run_triage17.sh create mode 100755 examples/benchmark/tools/triage/run_triage18.sh create mode 100755 examples/benchmark/tools/triage/run_triage18_phase2.sh create mode 100755 examples/benchmark/tools/triage/run_triage18_phase3.sh create mode 100644 examples/benchmark/tools/triage/validate_arms.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b99d8049..7693b575 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,28 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed — probing: protocol scripts kept in the repo, dead code removed, `compare` has a CLI + +The drivers of the multi-arm scheduler comparison (`run_triage17.sh`, `run_triage18.sh` +and its phase 2 and 3 variants, the GPU launcher) and the analysis scripts behind the +design document's tables (the union validation `validate_arms.py`, the budget-matched +discovery curve, the U re-count under the tolerant agreement rule) lived in a job's +scratch directory; they are now `examples/benchmark/tools/triage/` with a README, the +machine-specific paths taken from the environment. + +Removed what later code had superseded: `Ledger.spent` / `spent_wall_sec` (the budget +is charged by `_Run.charged`), `StepEvidence.sec_per_case` (costs come from +`scoring.step_cost`), the `run_triage_mvp0` alias (tests call `run_triage`) and the +sampler's `_rank` alias. `python -m evalrx.eval_agent.probing.compare ` +prints two arms' reports side by side (`--json` for the diff). A layer that narrows its +route's cases (X1) states its filter in its state (`case_filter`), where only the rule's +source had carried it. Stale strings updated: the package and controller docstrings no +longer describe MVP-2, `--m1-policy` says when a judge is built and that CONFIRM reaches +only the validator, and `evalsmith/probing/probing_design_mix.md` has a current status +header and a list of the remaining gaps between the design and the implementation. +`POLICY_VERSION` stays `mvp2-0`: it is part of every action identity, and a bump would +re-execute every stored observation. + ### Changed — the triage compares answers under the task's tolerance The U and S checks and the follow-up readings compared answers by key equality, diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index d251ce94..9be55839 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -43,6 +43,8 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); `--confirm-split-by media` instead draws the explore/confirm split over media groups, whole images on one side, so nothing is left out (default `case`: the judge-driven loop's split, which a triage run must share to be compared case for case); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. +**Multi-arm protocol.** The scheduler comparison (rules, scored, scored without exploration, scored with D, random, cheapest; each at the full budget and at budget tiers) runs every arm into one run directory on a shared ledger, copies each arm's report aside as `triage_report...json`, then validates the union of the arms' frozen families once. The drivers and the analysis scripts (the union validation, the budget-matched discovery curve, the U re-count under the tolerant agreement rule) are under `examples/benchmark/tools/triage/` with a README; `python -m evalrx.eval_agent.probing.compare a.json b.json` puts two arms' reports side by side. + The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. U (an answer that moves) needs both of its parts: re-sampling at temperature 1.0 (with the run's `--top-p`/`--top-k` on local backends; temperature only on `--backend gemini`, whose runtime merges per-call settings; the `endpoint` backend drops per-call settings, so this part stays untested there), compared with the Stage-0 answer, and the two wrappers, compared with the question re-asked unchanged. Answers are compared by the task's answer key under its agreement rule (two numbers within the task's numeric tolerance of each other are one answer, as the grader holds them; re-sampled answers are clustered by it), not graded against the gold; an unreadable answer is set aside, and a wrapper with no readable answer is an invalid control. Re-sampling fires U when another answer was sampled more often than the Stage-0 answer (a tie does not; one differing sample is ordinary noise at temperature 1.0, most of all on open answers); a wrapper fires it when its readable answer differs. S is a FAIL case on which H, N (when the case has media) and both U parts ran and none fired; a missing check leaves the case in X, never in S. The threshold instruction, `embed_lens` and `patchscope` are attached to every case as descriptive S readings — whether the instruction fixes errors and what it breaks, how close the case's own question word gets to the media tokens, whether the model's own answer ranked first at some layer before the last, and whether the question word is decoded off the media tokens — and summarised for S failures, other failures and stable PASS controls by gold answer. They are not tests and name no mechanism. diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 7a6bb09f..d0a9fbc3 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -154,8 +154,9 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "triage_active = triage controller: after Stage 0, run the triage battery " "strictly on a matched EXPLORE sample, expand it and run route follow-ups " "chosen by fixed rules, write the trace, cost ledger and triage report " - "under /probing/, and stop (no judge, no " - "M2-M5, CONFIRM untouched)") + "under /probing/, and stop. M2-M5 do not run; a judge is built only with " + "--triage-explanations judge; the controller never sees CONFIRM (only " + "--triage-validate reads it, after the stop)") p.add_argument("--triage-n-fail", type=int, default=8, help="triage_active: FAIL cases in the sample (PASS controls are matched per gold answer)") p.add_argument("--triage-max-fail", type=int, default=32, diff --git a/evalrx/eval_agent/probing/__init__.py b/evalrx/eval_agent/probing/__init__.py index 348d59cb..7fecf36b 100644 --- a/evalrx/eval_agent/probing/__init__.py +++ b/evalrx/eval_agent/probing/__init__.py @@ -7,10 +7,14 @@ cases and configuration it planned, and records why each action ran, what it cost, and whether its measurement can be trusted. -MVP-2 runs a fixed battery, then expansions and follow-ups chosen by fixed -rules, with no judge and no M2-M5: +A run draws a matched, nested sample of EXPLORE, runs a fixed battery on it, and +then decides one action at a time between expanding the sample and the routes' +follow-ups: by fixed rules, by value (optionally with competing explanations a +judge proposes, which give the value its D), or by the random and cheapest-first +controls. The issues a report supports can be frozen and validated once on cases +the controller never saw. - partition.py the same EXPLORE/CONFIRM split the diagnosis loop uses + partition.py the EXPLORE/CONFIRM split the diagnosis loop uses, or one by media content sampler.py matched, nested FAIL/PASS sample (S8 ⊆ S16 ⊆ S32 ...) actions.py PlanStep / ProbeAction / Observation and their content identities metering.py per-action call counts, model seconds, GPU peak memory, API usage @@ -19,10 +23,11 @@ evidence.py one step's observations over a growing sample (per-case reuse) triage.py H/N/U/S/X route labels traced back to case, field and action rules.py route layers, follow-up choice, and the expansion rule - controller.py the battery and run_triage() - scoring.py the scored scheduler's value of a candidate (MVP-3) - explanations.py competing explanations, their predictions and D (MVP-3) - validation.py the data roles, frozen issues and their one validation (MVP-4) + scoring.py the scored scheduler's value of a candidate, and the controls' pick + explanations.py competing explanations, their predictions and D + controller.py the battery, the schedulers and run_triage() + validation.py the data roles, frozen issues and their one validation + compare.py two arms' reports side by side (also a CLI) Nothing here is imported by the default ``judge`` path. """ @@ -30,12 +35,7 @@ from __future__ import annotations from evalrx.eval_agent.probing.actions import Observation, PlanStep, ProbeAction -from evalrx.eval_agent.probing.controller import ( - BATTERY, - POLICY_VERSION, - run_triage, - run_triage_mvp0, -) +from evalrx.eval_agent.probing.controller import BATTERY, POLICY_VERSION, run_triage from evalrx.eval_agent.probing.partition import explore_confirm_split from evalrx.eval_agent.probing.rules import LAYERS, RULES_VERSION from evalrx.eval_agent.probing.sampler import SampleDraw, matched_sample @@ -52,5 +52,4 @@ "explore_confirm_split", "matched_sample", "run_triage", - "run_triage_mvp0", ] diff --git a/evalrx/eval_agent/probing/compare.py b/evalrx/eval_agent/probing/compare.py index 4f578fd2..0f4c9d6a 100644 --- a/evalrx/eval_agent/probing/compare.py +++ b/evalrx/eval_agent/probing/compare.py @@ -8,7 +8,10 @@ from __future__ import annotations +import argparse +import json from itertools import combinations +from pathlib import Path from typing import Any from evalrx.eval_agent.probing.explanations import CARDS, primary_readings, verdict @@ -111,3 +114,22 @@ def markdown(diff: dict[str, Any]) -> str: f"apart: {a_name} {d['baseline']['n_resolved']}/{d['baseline']['n_conflicting_pairs']}, " f"{b_name} {d['other']['n_resolved']}/{d['other']['n_conflicting_pairs']}.", ""] return "\n".join(lines) + + +def main(argv: "list[str] | None" = None) -> int: + """``python -m evalrx.eval_agent.probing.compare [--json]``: two arms' + triage reports side by side, as Markdown (default) or as the JSON diff.""" + p = argparse.ArgumentParser(description="two triage reports side by side: selection order, evidence cost, " + "coverage and, with an explaining run, the explanations told apart") + p.add_argument("baseline", type=Path, help="the baseline arm's triage_report*.json") + p.add_argument("other", type=Path, help="the other arm's triage_report*.json") + p.add_argument("--json", action="store_true", help="print the diff as JSON instead of Markdown") + args = p.parse_args(argv) + diff = compare(json.loads(args.baseline.read_text(encoding="utf-8")), + json.loads(args.other.read_text(encoding="utf-8"))) + print(json.dumps(diff, indent=2, default=str) if args.json else markdown(diff)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 9bdb6c51..cd51768e 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -1,4 +1,4 @@ -"""MVP-2: the triage battery, nested expansion and route follow-ups chosen by fixed rules. +"""The triage controller: the battery, nested expansion and follow-ups, chosen by rules or by value. A run goes through three phases: @@ -55,13 +55,16 @@ step's own measured cost per case, else the most expensive case measured in this run; there is no per-analyzer cost prior). -The rules scheduler calls no judge and names no hypothesis. The scored -scheduler (MVP-3) may take an explainer: the judge then proposes competing -explanations once the sample has settled, and their predictions give each -candidate its D (:mod:`.explanations`); no explanation is a finding. CONFIRM -never enters. Outputs land in ``out_dir``:: +Four schedulers decide after the battery (``scheduler``): ``rules`` (rounds over +the routes' soft layer order; no judge, no hypothesis), ``scored`` (the candidate +of highest value, :mod:`.scoring`), and the controls ``random`` and ``cheapest`` +over the same candidates. The scored scheduler may take an explainer: the judge +then proposes competing explanations once the sample has settled, and their +predictions give each candidate its D (:mod:`.explanations`); no explanation is a +finding. CONFIRM never enters the controller (:mod:`.validation` reads it after +the stop, when asked). Outputs land in ``out_dir``:: - split_manifest.json triage_report[.scored].json triage_report[.scored].md + split_manifest.json triage_report[.[_d]].json triage_report[.[_d]].md selection_trace.jsonl cost_ledger.jsonl observations/.json explanations/.json (with an explainer: each judge call's prompt, reply and cost) """ @@ -150,6 +153,9 @@ if TYPE_CHECKING: from evalrx.core.case import CaseBatch +#: Part of every action identity (with the model identity and the tool version): bumped only +#: when the controller changes what an action executes or records, never for a rename, since a +#: bump re-executes every stored observation on resume. The label dates from MVP-2. POLICY_VERSION = "mvp2-0" SCHEDULERS = ("rules", "scored", "random", "cheapest") #: The schedulers that decide over the scored candidate pool: the value, or a control differing in the pick only. @@ -1516,10 +1522,6 @@ def report_name(scheduler: str, explained: bool = False) -> str: return f"triage_report.{scheduler}" + ("_d" if explained else "") -#: The MVP-0 entry point, now the same controller (no expansion unless ``max_fail`` is given). -run_triage_mvp0 = run_triage - - def _revision_row(revision: int, draw: Any, summary: dict[str, Any], records: list[dict[str, Any]], gaps: list[dict[str, Any]]) -> dict[str, Any]: routes = Counter(tag for r in records if r["label"] == "fail" for tag in r["routes"]) diff --git a/evalrx/eval_agent/probing/evidence.py b/evalrx/eval_agent/probing/evidence.py index 803e8d2a..e984c3ac 100644 --- a/evalrx/eval_agent/probing/evidence.py +++ b/evalrx/eval_agent/probing/evidence.py @@ -72,13 +72,6 @@ def valid_on(self, ids: Iterable[str]) -> bool: def statuses_on(self, ids: Iterable[str]) -> list[str]: return sorted({obs.status for cid in ids if (obs := self.for_case(cid)) is not None}) - def sec_per_case(self) -> "float | None": - """Wall seconds per planned case over the chunks that executed, for budget estimates.""" - rows = [(float(o.cost.get("wall_sec") or 0.0), len(o.planned_ids)) for o in self.chunks - if o.cost.get("calls") and o.planned_ids] - n = sum(k for _, k in rows) - return sum(s for s, _ in rows) / n if n else None - def pick(evidence: "dict[str, Any]", key: str, cid: str) -> "Observation | None": """The observation for *cid* under *key*: a plain :class:`Observation` (one batch) or a diff --git a/evalrx/eval_agent/probing/ledger.py b/evalrx/eval_agent/probing/ledger.py index 96a6a18f..3270744c 100644 --- a/evalrx/eval_agent/probing/ledger.py +++ b/evalrx/eval_agent/probing/ledger.py @@ -97,10 +97,3 @@ def settled(self, action_id: str) -> "Observation | None": def attempts(self, action_id: str) -> int: return sum(1 for e in self.trace_events() if e.get("event") == "planned" and e.get("action_id") == action_id) - - def spent_wall_sec(self) -> float: - return self.spent("wall_sec") - - def spent(self, axis: str) -> float: - """Executed actions' spend on *axis* (``wall_sec`` or ``usd``), over every invocation.""" - return sum(float(e.get(axis) or 0.0) for e in self.cost_events() if e.get("kind") == "action") diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index 1adf3aa4..6f9cba70 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -80,7 +80,8 @@ class Layer: """One question of a route, its candidates in fallback order, and where the prior comes from. ``served_by`` names battery steps that already answer it. ``case_filter`` - narrows the route's FAIL cases to the ones the question is about. + narrows the route's FAIL cases to the ones the question is about, and + ``filter_note`` says so in the layer's state (the trace and the report). """ rule_id: str @@ -272,7 +273,9 @@ def route_states(route: str, records: list[dict[str, Any]], evidence: dict[str, controls, shortfall = matched_controls(records, fail_ids, rank) state = layer_state(layer, evidence, fail_ids, [*fail_ids, *controls], gate, blocked, pending) out.append({**state, "question": layer.question, "n_fail": len(fail_ids), "n_controls": len(controls), - "control_shortfall": shortfall, "_fail_ids": fail_ids, "_control_ids": controls}) + "control_shortfall": shortfall, + **({"case_filter": layer.filter_note} if layer.case_filter is not None else {}), + "_fail_ids": fail_ids, "_control_ids": controls}) return out diff --git a/evalrx/eval_agent/probing/sampler.py b/evalrx/eval_agent/probing/sampler.py index 7101958b..02fbf404 100644 --- a/evalrx/eval_agent/probing/sampler.py +++ b/evalrx/eval_agent/probing/sampler.py @@ -46,8 +46,6 @@ def rank(seed: int, case_id: str) -> str: return hashlib.sha1(f"{seed}:{case_id}".encode("utf-8")).hexdigest() -_rank = rank - @dataclass(frozen=True) class SampleDraw: @@ -80,8 +78,8 @@ def matched_sample(cases: "CaseBatch", n_fail: int, *, seed: int, key = STRATA[stratum] pool = list(cases) - fails = sorted((c for c in pool if c.label == Label.FAIL), key=lambda c: _rank(seed, str(c.id))) - passes = sorted((c for c in pool if c.label == Label.PASS), key=lambda c: _rank(seed, str(c.id))) + fails = sorted((c for c in pool if c.label == Label.FAIL), key=lambda c: rank(seed, str(c.id))) + passes = sorted((c for c in pool if c.label == Label.PASS), key=lambda c: rank(seed, str(c.id))) chosen_fail = fails[:max(0, int(n_fail))] need: dict[str, int] = {} diff --git a/examples/benchmark/tools/triage/README.md b/examples/benchmark/tools/triage/README.md new file mode 100644 index 00000000..21462773 --- /dev/null +++ b/examples/benchmark/tools/triage/README.md @@ -0,0 +1,70 @@ +# Triage protocol scripts + +The drivers and analysis scripts of the scheduler comparison run with `--m1-policy triage_active` +(design and results: `evalsmith/probing/probing_design_mix.md`; the controller: +[`docs/agentic_benchmark.md`](../../../../docs/agentic_benchmark.md), "Triage policy"). They were +written as scratch for the triage17/18 runs on Qwen3.5-2B and ChartQA and are kept here so the +protocol and the tables derived from it can be re-run. Machine-specific values (python, scratch +directory, data and output roots, the judge) come from the environment; see `_common.sh`. + +## The protocol + +Every arm is one `evalrx.benchmark.run` invocation into the **same run directory**, so the arms +share one observation ledger (an action with the same identity is read back, not re-run) and each +is charged what its evidence cost when first executed. After each arm its report is copied aside +as `probing/..json`; then `validate_arms.py` runs the benchmark entry once more +with the controller replaced by the stored reports and the runner's `validate()` replaced by one +over the union of every arm's frozen issues: one family, one Bonferroni level, one validation +ledger, every arm credited with its own issues (`validation/validation_report.{json,md}`, +`validation/frozen.json`). + +| arm | flags | +|---|---| +| `rules` | `--triage-scheduler rules` | +| `scored` | `--triage-scheduler scored` | +| `scored_x0` | `--triage-scheduler scored --triage-explore-share 0` | +| `scored_d` | `--triage-scheduler scored --triage-explanations judge` (judge: `JUDGE_FLAGS`) | +| `random`, `cheapest` | `--triage-scheduler random` / `cheapest` (controls over the scored candidates) | +| budget tier `b` | `--triage-budget-sec N`; `full` = no cap | + +Common to every arm: `--triage-n-fail 8 --triage-max-fail <32 or 128> --triage-max-actions 30 +--triage-chunk 8`, `--attn-impl eager`, the frozen ChartQA pool (`--data-dir ... --limit 1000`), +one GPU with nothing else on it (`CUDA_VISIBLE_DEVICES`, `CUDA_DEVICE_ORDER=PCI_BUS_ID`), weights +offline, a private `TMPDIR`, and no `CLAUDE*` variables in the environment (the claude CLI judge +must not see a parent session). + +## Scripts + +| script | what it did | +|---|---| +| `_common.sh` | sourced by the run scripts: paths from the environment, the arm table, code snapshots, the arm loop, the union validation | +| `run_triage17.sh` | triage17 (10-21/22): triage16's 12 stored arms validated once more with a validation-only source added (`--triage-validation-source`) | +| `run_triage18.sh` | triage18 phase 1 (10-22/23): the 12 arms (rules / scored / scored_x0 / scored_d x full / b700 / b900) at `--triage-max-fail 128` on a code snapshot (commit 0d01bb6), then their union validation | +| `run_triage18_phase2.sh` | phase 2 (10-23/24): the controls at full budget and the budget tiers 4000 / 5500 / 7100 s for all six schedulers (20 arms) added to the same directory, then the 32-arm union validation; the 12-arm validation kept as `*.12arms.*` | +| `run_triage18_phase3.sh` | phase 3 (10-24): all 32 arms again under the `step_cost` fix (scoring `mvp3-score-5`), phase-2 reports moved to `probing/arms_p2/` and its validation kept as `*.32arms_p2.*` | +| `launch_when_free.sh` | polls for a GPU with under 3 GB in use every 20 s and starts a run script on it | +| `validate_arms.py` | the union validation driver the run scripts call | +| `discovery_curve.py` | budget-matched discovery curve: supported phenomena each arm had found within a charged budget B (the design document's "预算对齐" tables) | +| `recount_u.py` | re-reads a run's stored U evidence under the exact and the tolerant agreement rule (the rules-5 "离线重算" table) | + +The phase scripts are idempotent: an arm whose report copy exists is skipped, so a killed run is +resumed by starting the script again. The 700 / 900 s tiers are kept in the phase-3 validation but +not interpreted: at `--triage-max-fail 128` they stop inside the first expansion. + +## Data + +The ChartQA pool is `examples/benchmark/vlm/_data/triage_pool/chartqa/` (1000 human-authored rows, +seed 5022, frozen from the HF cache with `python -m evalrx.benchmark.tasks.chartqa`), and the +validation-only source `.../triage_pool/chartqa_validation/` is every human row the pool left +(`python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json`). `_data/` is +not committed; `partition_bundle.json` records each manifest's sha1. + +## Usage + +```bash +export PY=/path/to/venv/bin/python TRIAGE_SCRATCH=/path/to/scratch # see _common.sh for the rest +nohup bash examples/benchmark/tools/triage/launch_when_free.sh run_triage18_phase3.sh > launcher.log 2>&1 & +python examples/benchmark/tools/triage/discovery_curve.py --grid 3000 4000 5000 6000 7095 +python -m evalrx.eval_agent.probing.compare /probing/triage_report.rules_full.json \ + /probing/triage_report.scored.scored_full.json +``` diff --git a/examples/benchmark/tools/triage/_common.sh b/examples/benchmark/tools/triage/_common.sh new file mode 100644 index 00000000..222016dd --- /dev/null +++ b/examples/benchmark/tools/triage/_common.sh @@ -0,0 +1,78 @@ +# Shared settings of the triage protocol scripts (sourced by run_*.sh, not run). +# Machine-specific values come from the environment: +# PY python with evalrx and the model stack (default: python; the runs used a vLLM/transformers venv) +# TRIAGE_SCRATCH logs, a private TMPDIR and code snapshots (default: ~/.cache/evalrx/triage) +# TRIAGE_DATA the frozen ChartQA pool (default: /examples/benchmark/vlm/_data/triage_pool) +# TRIAGE_OUT the run-directory root (default: /examples/benchmark/vlm/qwen/host_outputs) +# TRIAGE_SOURCE the validation-only manifest (default: $TRIAGE_DATA/chartqa_validation/manifest.json) +# TRIAGE_MODEL / TRIAGE_DATASET the model spec and task (default: qwen3.5-2b-vl / chartqa) +# JUDGE_FLAGS the judge of the scored_d arms (default: claude-opus-5 through the claude CLI, effort high) +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../../../.." && pwd) +PY=${PY:-python} +SCRATCH=${TRIAGE_SCRATCH:-$HOME/.cache/evalrx/triage} +DATA=${TRIAGE_DATA:-$REPO/examples/benchmark/vlm/_data/triage_pool} +OUT=${TRIAGE_OUT:-$REPO/examples/benchmark/vlm/qwen/host_outputs} +SRC=${TRIAGE_SOURCE:-$DATA/chartqa_validation/manifest.json} +MODEL=${TRIAGE_MODEL:-qwen3.5-2b-vl} +DATASET=${TRIAGE_DATASET:-chartqa} +JUDGE_FLAGS=${JUDGE_FLAGS:---judge-provider claude --judge-model claude-opus-5 --judge-effort high} +mkdir -p "$SCRATCH" + +common_flags() { # : the flags every arm shares (model, data, protocol constants) + echo "--modality vlm --model $MODEL --backend hf_local --dataset $DATASET --data-dir $DATA --run-dir $OUT --run-tag $1 --limit 1000 --no-download --device cuda --attn-impl eager --m1-policy triage_active --triage-n-fail 8 --triage-max-fail $2 --triage-max-actions 30 --triage-chunk 8 $JUDGE_FLAGS" +} +report_name() { # -> the report stem run_triage writes + case $1 in rules) echo triage_report ;; scored|scored_x0) echo triage_report.scored ;; scored_d) echo triage_report.scored_d ;; + random) echo triage_report.random ;; cheapest) echo triage_report.cheapest ;; esac +} +sched_flags() { # -> its flags + case $1 in rules) echo "--triage-scheduler rules" ;; scored) echo "--triage-scheduler scored" ;; + scored_x0) echo "--triage-scheduler scored --triage-explore-share 0" ;; + scored_d) echo "--triage-scheduler scored --triage-explanations judge" ;; + random) echo "--triage-scheduler random" ;; cheapest) echo "--triage-scheduler cheapest" ;; esac +} +budget_flags() { # > + case $1 in b*) echo "--triage-budget-sec ${1#b}" ;; esac +} +arm_names_json() { # -> the JSON list validate_arms.py takes + local s="[" a k b + for a in "$@"; do k=${a%:*}; b=${a#*:}; s="$s[\"${k}_${b}\",\"$(report_name "$k")\"],"; done + echo "${s%,}]" +} +snapshot_code() { # : the code the arms run on, so the working tree can change meanwhile + mkdir -p "$1" || return 1 + if [ "$2" = worktree ]; then (cd "$REPO" && git ls-files -z | rsync -a --files-from=- --from0 ./ "$1"/) + else (cd "$REPO" && git archive "$2") | tar -x -C "$1"; fi +} +prepare_env() { # : one GPU, offline weights, a private TMPDIR + local v + for v in $(env | grep -o '^CLAUDE[^=]*'); do unset "$v"; done # the claude CLI judge must not see a parent session + export CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=$1 HF_HUB_OFFLINE=1 PYTHONPATH=$2 + export TMPDIR=$SCRATCH/tmp_$3; mkdir -p "$TMPDIR" +} +run_arms() { # : each arm once; its report copy marks it done + local log=$1 run=$2 common=$3 a k b arm name flags rc; shift 3 + for a in "$@"; do + k=${a%:*}; b=${a#*:}; arm=${k}_${b}; name=$(report_name "$k"); flags="$(sched_flags "$k") $(budget_flags "$b")" + if [ -f "$run/probing/$name.$arm.json" ]; then echo "SKIP $arm (report copy exists)" >> "$log"; continue; fi + echo "ARM $arm start $(date '+%m-%d %H:%M'): $flags" >> "$log" + $PY -u -m evalrx.benchmark.run $common $flags >> "$log" 2>&1 + rc=$? + if [ $rc -ne 0 ] || [ ! -f "$run/probing/$name.json" ]; then echo "ARM $arm FAILED rc=$rc at $(date '+%m-%d %H:%M')" >> "$log"; return 1; fi + cp "$run/probing/$name.json" "$run/probing/$name.$arm.json"; cp "$run/probing/$name.md" "$run/probing/$name.$arm.md" + echo "ARM $arm done $(date '+%m-%d %H:%M')" >> "$log" + done +} +validate_union() { # : one Stage 0 (plus the source's), then the union validation + echo "VALIDATE start $(date '+%m-%d %H:%M')" >> "$1" + $PY -u "$HERE/validate_arms.py" "$2" -- $3 --triage-validate --triage-validation-source "$SRC" >> "$1" 2>&1 + echo "EXIT validate $? at $(date '+%m-%d %H:%M')" >> "$1" +} +keep_aside() { # : copy the current validation report and frozen family aside, once + local v=$1/validation + if [ -f "$v/validation_report.json" ] && [ ! -f "$v/validation_report.$2.json" ]; then + cp "$v/validation_report.json" "$v/validation_report.$2.json"; cp "$v/validation_report.md" "$v/validation_report.$2.md" + cp "$v/frozen.json" "$v/frozen.$2.json" + fi +} diff --git a/examples/benchmark/tools/triage/discovery_curve.py b/examples/benchmark/tools/triage/discovery_curve.py new file mode 100644 index 00000000..ca3aa2e2 --- /dev/null +++ b/examples/benchmark/tools/triage/discovery_curve.py @@ -0,0 +1,80 @@ +"""Budget-matched discovery curve of a multi-arm run directory (no model, no GPU). + +For each arm, the number of validation-supported phenomena whose issues the arm had discovered within a +charged budget B. An issue counts as discovered at the charge of its step's last execution on its route (a +battery step: on the whole sample; a route signal: once the five route steps have run), so the curve is +conservative for a chunked step (its last chunk). Charges follow the report: every execution the arm read, +at the cost of its first execution (a read-back at its original cost, once); judge calls are not charged. + +usage: python discovery_curve.py [--arms arm:report_stem ...] [--grid B ...] + e.g. python discovery_curve.py .../chartqa.triage18-chartqa-2b-mf128 --arms rules_full:triage_report \ + scored_full:triage_report.scored --grid 3000 4000 5000 6000 7095 +""" +import argparse +import json +import math +from pathlib import Path + +ROUTE_STEPS = {"answer_extraction_audit", "termination_audit", "modality_ablation", "self_consistency", "prompt_reword"} +DEFAULT_ARMS = ["rules_full:triage_report", "scored_full:triage_report.scored", + "scored_x0_full:triage_report.scored", "scored_d_full:triage_report.scored_d"] +DEFAULT_GRID = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000] + + +def curve_of(run: Path, arm: str, stem: str, report: dict, frozen: dict, grid: list) -> dict: + probing = run / "probing" + phen_of = {iid: p["id"] for p in report["phenomena"] for iid in p["issues"]} + supported = {p["id"] for p in report["phenomena"] if p["verdict"] == "supported"} + issue_by_id = {i["issue_id"]: i for i in report["issues"]} + r = json.loads((probing / f"{stem}.{arm}.json").read_text()) + seen, charge, cum = set(), 0.0, [] + for e in r["executions"]: + aid = e.get("action_id") + if aid is None: + charge += float((e.get("cost") or {}).get("wall_sec") or 0.0) + elif aid not in seen: + seen.add(aid) + f = probing / "observations" / f"{aid}.json" + obs = json.loads(f.read_text()) if f.is_file() else {} + charge += float((obs.get("cost") or e.get("cost") or {}).get("wall_sec") or 0.0) + cum.append((e, charge)) + settled = max((c for e, c in cum if e.get("key") in ROUTE_STEPS), default=0.0) # the routes are known + found_at = {} + for iid in frozen["arms"].get(arm) or []: + i = issue_by_id[iid] + if not i.get("step"): + found_at[iid] = settled # a route signal: known once the route steps ran + continue + # a follow-up is keyed by route; a battery step runs on the whole sample (route None) + last = [c for e, c in cum if e.get("key") == i["step"] and e.get("route") in (i["route"], None)] + if not last: # a reading frozen for a route from a step that ran on another route's cases + last = [c for e, c in cum if e.get("key") == i["step"]] + found_at[iid] = max(last) if last else None + curve = [len({phen_of[iid] for iid, c in found_at.items() + if c is not None and c <= B and phen_of.get(iid) in supported}) for B in grid] + return {"total_charged": round(r["cost"]["charged"]["wall_sec"]), "settled_at": round(settled), "curve": curve, + "found_at": {phen_of.get(k, "?"): (round(v) if v is not None else None) for k, v in found_at.items()}} + + +def main() -> int: + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("run", type=Path, help="the run directory (holding probing/ and validation/)") + p.add_argument("--arms", nargs="+", default=DEFAULT_ARMS, metavar="ARM:STEM", + help="arm name and its report stem, e.g. rules_full:triage_report") + p.add_argument("--grid", nargs="+", type=float, default=DEFAULT_GRID, metavar="B", + help="charged budgets (seconds) to count the supported phenomena found within") + a = p.parse_args() + report = json.loads((a.run / "validation" / "validation_report.json").read_text()) + frozen = json.loads((a.run / "validation" / "frozen.json").read_text()) + grid = [*a.grid, math.inf] + for spec in a.arms: + arm, stem = spec.split(":", 1) + row = curve_of(a.run, arm, stem, report, frozen, grid) + print(f"{arm:16s} charged={row['total_charged']:6d} settled={row['settled_at']:6d} " + f"curve@{[int(b) for b in grid[:-1]] + ['total']}: {row['curve']}") + print(" phenomenon -> found at:", dict(sorted(row["found_at"].items(), key=lambda kv: (kv[1] is None, kv[1] or 0)))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/benchmark/tools/triage/launch_when_free.sh b/examples/benchmark/tools/triage/launch_when_free.sh new file mode 100755 index 00000000..2ed23f46 --- /dev/null +++ b/examples/benchmark/tools/triage/launch_when_free.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Poll every 20 s for a GPU with under 3 GB in use and start the given protocol script on it at once (a 60 s +# poll lost a free GPU to another user within the minute). A GPU is never shared. +# usage: launch_when_free.sh [its arguments after the gpu index...] +# e.g. nohup bash launch_when_free.sh run_triage18_phase3.sh > launcher.log 2>&1 & +set -u +SCRIPT=${1:?run script}; shift +HERE=$(cd "$(dirname "$0")" && pwd) +[ -f "$SCRIPT" ] || SCRIPT=$HERE/$SCRIPT +for _ in $(seq 1 4320); do # up to 24 h + free=$(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader,nounits | awk -F', ' '$2 < 3000 {print $1}' | head -1) + if [ -n "$free" ]; then + echo "LAUNCH $(basename "$SCRIPT") on GPU $free at $(date '+%m-%d %H:%M')" + bash "$SCRIPT" "$free" "$@" + echo "RUN_DONE rc=$? at $(date '+%m-%d %H:%M')" + exit 0 + fi + sleep 20 +done +echo "NO_GPU after 24h"; exit 1 diff --git a/examples/benchmark/tools/triage/recount_u.py b/examples/benchmark/tools/triage/recount_u.py new file mode 100644 index 00000000..ec40c7b1 --- /dev/null +++ b/examples/benchmark/tools/triage/recount_u.py @@ -0,0 +1,89 @@ +"""Re-read a run's stored U evidence under the exact and the tolerant agreement rule (no model, no GPU). + +usage: python recount_u.py + +Reads the self_consistency and prompt_reword observations of the run's probing/ and validation/ ledgers and +re-derives every case's U check with ``triage._u_check`` twice: with key equality (``exact_answer``, the rule up +to rules-4) and with the task's tolerant rule (``tasks.same_answer``, rules-5). Prints the fired/clear/untested +tallies per label and the FAIL cases whose U state flips. The case labels come from the run's baseline.json +(and baseline_validation_source.json for the validation ledger); the task metadata is ChartQA's. +""" +import json +import sys +from collections import Counter +from pathlib import Path +from types import SimpleNamespace + +from evalrx.benchmark import tasks +from evalrx.eval_agent.probing.actions import Observation +from evalrx.eval_agent.probing.triage import _u_check, exact_answer + +D = Path(sys.argv[1]) +META = {"task": "exact_or_numeric", "numeric_tolerance": 0.05} + + +def cases_of(*files): + out = {} + for f in files: + if not (D / f).is_file(): + continue + for r in json.load(open(D / f))["cases"]: + out[r["id"]] = SimpleNamespace(id=r["id"], observed=r["observed"], label=r["label"], metadata=META) + return out + + +def chunks(sub): + root = D / sub / "observations" + idx = [json.loads(line) for line in open(root / "index.jsonl")] + by = {"self_consistency": [], "prompt_reword": []} + for r in dict.fromkeys(x["action_id"] for x in idx): + o = Observation.from_dict(json.load(open(root / f"{r}.json"))) + if o.status != "ok": + continue + if o.analyzer == "self_consistency": + by["self_consistency"].append(o) + elif o.analyzer == "prompt_contrast" and "question_frame" in (o.params.get("strategies") or {}): + by["prompt_reword"].append(o) + return by + + +def for_case(objs, cid): + for o in reversed(objs): + if cid in o.planned_ids: + return o + return None + + +def recount(sub, cases): + by = chunks(sub) + covered = sorted({c for o in by["self_consistency"] for c in o.planned_ids} + | {c for o in by["prompt_reword"] for c in o.planned_ids}) + tally = {} + for rule, agree in (("exact", exact_answer), ("tolerant", tasks.same_answer)): + t = {lab: Counter() for lab in ("fail", "pass")} + for cid in covered: + case = cases.get(cid) + if case is None: + continue + u = _u_check(for_case(by["self_consistency"], cid), for_case(by["prompt_reword"], cid), case, + tasks.answer_key, agree) + lab = t[case.label] + lab["n"] += 1 + lab[f"U_{u['state']}"] += 1 + for part in u["parts"]: + lab[f"{part['part']}_{part['state']}"] += 1 + tally[rule] = {k: dict(v) for k, v in t.items()} + print(sub, json.dumps(tally, indent=1, sort_keys=True)) + flips = Counter() # which FAIL cases change state between the two rules + for cid in covered: + case = cases.get(cid) + if case is None or case.label != "fail": + continue + states = [_u_check(for_case(by["self_consistency"], cid), for_case(by["prompt_reword"], cid), case, + tasks.answer_key, agree)["state"] for agree in (exact_answer, tasks.same_answer)] + flips[f"{states[0]}->{states[1]}"] += 1 + print(sub, "FAIL U transitions", dict(flips)) + + +recount("probing", cases_of("baseline.json")) +recount("validation", cases_of("baseline.json", "baseline_validation_source.json")) diff --git a/examples/benchmark/tools/triage/run_triage17.sh b/examples/benchmark/tools/triage/run_triage17.sh new file mode 100755 index 00000000..c2978c46 --- /dev/null +++ b/examples/benchmark/tools/triage/run_triage17.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# triage17 (10-21/22): triage16's stored arms, validated once more on DIAGNOSTIC_VALIDATION extended by the +# validation-only source (the human rows the pool left: the rest of the test split plus the val split). Only +# the validation runs (two Stage 0 passes: the pool's and the source's); the code is the working tree. +# usage: run_triage17.sh [run tag] [source manifest] +set -u +. "$(dirname "$0")/_common.sh" +GPU=${1:?gpu index} +TAG=${2:-triage17-chartqa-2b-extval} +SRC=${3:-$SRC} +LOG=$SCRATCH/validate_$TAG.log +COMMON=$(common_flags "$TAG" 32) +ARMS="rules:full scored:full scored_x0:full scored_d:full rules:b700 scored:b700 scored_x0:b700 scored_d:b700 rules:b900 scored:b900 scored_x0:b900 scored_d:b900" +prepare_env "$GPU" "$REPO" "$TAG" +cd "$REPO" || exit 1 +echo "START $TAG validation on GPU $GPU at $(date '+%m-%d %H:%M') source=$SRC" >> "$LOG" +validate_union "$LOG" "$(arm_names_json $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/run_triage18.sh b/examples/benchmark/tools/triage/run_triage18.sh new file mode 100755 index 00000000..1d9ac4eb --- /dev/null +++ b/examples/benchmark/tools/triage/run_triage18.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# triage18 phase 1 (10-22/23): the 12-arm protocol of triage12-16 (rules / scored / scored_x0 / scored_d x +# full / b700 / b900) under rules-5 with --triage-max-fail 128, then the 12 arms validated together on CONFIRM +# plus the validation-only source. The arms run on a code snapshot (the original run: commit 0d01bb6), so the +# working tree can be edited meanwhile; triage17's observation ledgers are copied in for chunk reuse. +# Idempotent: an arm whose report copy exists is skipped. +# usage: run_triage18.sh [git ref to snapshot, default HEAD] +set -u +. "$(dirname "$0")/_common.sh" +GPU=${1:?gpu index}; REF=${2:-HEAD} +TAG=triage18-chartqa-2b-mf128 +RUN=$OUT/$MODEL/$DATASET.$TAG +PREV=$OUT/$MODEL/$DATASET.triage17-chartqa-2b-extval +LOG=$SCRATCH/run_$TAG.log +CODE=$SCRATCH/code_${TAG}_$(date +%s) +COMMON=$(common_flags "$TAG" 128) +ARMS="rules:full scored:full scored_x0:full scored_d:full rules:b700 scored:b700 scored_x0:b700 scored_d:b700 rules:b900 scored:b900 scored_x0:b900 scored_d:b900" + +snapshot_code "$CODE" "$REF" || exit 1 +prepare_env "$GPU" "$CODE" "$TAG" +cd "$CODE" || exit 1 +mkdir -p "$RUN/probing" "$RUN/validation" +[ -d "$RUN/probing/observations" ] || { [ -d "$PREV/probing/observations" ] && cp -r "$PREV/probing/observations" "$RUN/probing/"; } +[ -d "$RUN/validation/observations" ] || { [ -d "$PREV/validation/observations" ] && cp -r "$PREV/validation/observations" "$RUN/validation/"; } +echo "START $TAG on GPU $GPU at $(date '+%m-%d %H:%M') code=$CODE ($REF)" >> "$LOG" +run_arms "$LOG" "$RUN" "$COMMON" $ARMS || exit 1 +validate_union "$LOG" "$(arm_names_json $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/run_triage18_phase2.sh b/examples/benchmark/tools/triage/run_triage18_phase2.sh new file mode 100755 index 00000000..819e13ab --- /dev/null +++ b/examples/benchmark/tools/triage/run_triage18_phase2.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# triage18 phase 2 (10-23/24), in the triage18 run directory (shared probing ledger), one GPU, one go: +# 1. the controls at the full budget: random_full, cheapest_full; +# 2. the rescaled budget tiers 4000 / 5500 / 7100 s for all six schedulers = 18 arms (at max_fail 128 the +# 700/900 s tiers stop inside the expansion and are all alike); +# 3. one union validation over all 32 arms (validation ledger reused; the 12-arm report kept as *.12arms.*). +# The arms run on a snapshot of the working tree's tracked files (the original run carried the control +# schedulers before they were committed as 2695741). Idempotent. usage: run_triage18_phase2.sh +set -u +. "$(dirname "$0")/_common.sh" +GPU=${1:?gpu index} +TAG=triage18-chartqa-2b-mf128 +RUN=$OUT/$MODEL/$DATASET.$TAG +LOG=$SCRATCH/run_${TAG}_phase2.log +CODE=$SCRATCH/code_${TAG}_p2_$(date +%s) +COMMON=$(common_flags "$TAG" 128) +PHASE1="rules:full scored:full scored_x0:full scored_d:full rules:b700 scored:b700 scored_x0:b700 scored_d:b700 rules:b900 scored:b900 scored_x0:b900 scored_d:b900" +ARMS="random:full cheapest:full" +for b in 4000 5500 7100; do for k in rules scored scored_x0 scored_d random cheapest; do ARMS="$ARMS $k:b$b"; done; done + +snapshot_code "$CODE" worktree || exit 1 +grep -q '"cheapest"' "$CODE/evalrx/eval_agent/probing/controller.py" || { echo "snapshot has no control schedulers" >> "$LOG"; exit 1; } +[ -f "$RUN/probing/triage_report.rules_full.json" ] || { echo "phase 1 arms missing" >> "$LOG"; exit 1; } +prepare_env "$GPU" "$CODE" "${TAG}_phase2" +cd "$CODE" || exit 1 +echo "START phase2 on GPU $GPU at $(date '+%m-%d %H:%M') code=$CODE (HEAD $(git -C "$REPO" rev-parse --short HEAD) + $(git -C "$REPO" status --short | wc -l) modified files)" >> "$LOG" +echo "ARMS: $ARMS" >> "$LOG" +keep_aside "$RUN" 12arms +run_arms "$LOG" "$RUN" "$COMMON" $ARMS || exit 1 +validate_union "$LOG" "$(arm_names_json $PHASE1 $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/run_triage18_phase3.sh b/examples/benchmark/tools/triage/run_triage18_phase3.sh new file mode 100755 index 00000000..8f837098 --- /dev/null +++ b/examples/benchmark/tools/triage/run_triage18_phase3.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# triage18 phase 3 (10-24), in the triage18 run directory (shared probing ledger), one GPU, one go: every one +# of the 32 arms again under the step_cost fix (scoring mvp3-score-5: a zero-call audit is priced at what it +# measured, so an expansion's estimate is no longer 3.5-24x its cost), then one union validation over the 32 +# arms. Phase-2 artefacts are kept: arm reports under probing/arms_p2/, the validation as *.32arms_p2.*. +# The arms run on a snapshot of the working tree's tracked files. Idempotent. usage: run_triage18_phase3.sh +set -u +. "$(dirname "$0")/_common.sh" +GPU=${1:?gpu index} +TAG=triage18-chartqa-2b-mf128 +RUN=$OUT/$MODEL/$DATASET.$TAG +LOG=$SCRATCH/run_${TAG}_phase3.log +CODE=$SCRATCH/code_${TAG}_p3_$(date +%s) +COMMON=$(common_flags "$TAG" 128) +ARMS="" +for k in rules scored scored_x0 scored_d random cheapest; do ARMS="$ARMS $k:full"; done +for b in 700 900; do for k in rules scored scored_x0 scored_d; do ARMS="$ARMS $k:b$b"; done; done +for b in 4000 5500 7100; do for k in rules scored scored_x0 scored_d random cheapest; do ARMS="$ARMS $k:b$b"; done; done + +snapshot_code "$CODE" worktree || exit 1 +grep -q 'mvp3-score-5' "$CODE/evalrx/eval_agent/probing/scoring.py" || { echo "snapshot lacks the step_cost fix" >> "$LOG"; exit 1; } +prepare_env "$GPU" "$CODE" "${TAG}_phase3" +cd "$CODE" || exit 1 +echo "START phase3 on GPU $GPU at $(date '+%m-%d %H:%M') code=$CODE (HEAD $(git -C "$REPO" rev-parse --short HEAD) + $(git -C "$REPO" status --short | wc -l) modified files)" >> "$LOG" +echo "ARMS: $ARMS" >> "$LOG" +if [ ! -d "$RUN/probing/arms_p2" ]; then # keep phase 2's arm reports aside, once + mkdir -p "$RUN/probing/arms_p2" + for a in $ARMS; do k=${a%:*}; b=${a#*:}; n=$(report_name "$k"); mv "$RUN/probing/$n.${k}_$b.json" "$RUN/probing/$n.${k}_$b.md" "$RUN/probing/arms_p2/" 2>> "$LOG"; done +fi +keep_aside "$RUN" 32arms_p2 +run_arms "$LOG" "$RUN" "$COMMON" $ARMS || exit 1 +validate_union "$LOG" "$(arm_names_json $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/validate_arms.py b/examples/benchmark/tools/triage/validate_arms.py new file mode 100644 index 00000000..e94d4d26 --- /dev/null +++ b/examples/benchmark/tools/triage/validate_arms.py @@ -0,0 +1,51 @@ +"""One Stage 0 (plus the validation source's), then the stored triage arms of a run directory validated together. + +usage: python validate_arms.py '' -- + +Every arm of a comparison runs ``evalrx.benchmark.run`` into the same run directory, each copying its report +aside as ``probing/..json`` (see ``_common.sh``). This driver then runs the benchmark entry +once more with two of the runner's steps replaced: the controller is not run (the first listed arm's stored +report stands in for it), and the runner's ``validate()`` call becomes one over the union of every listed +arm's frozen issues, so the arms share one family, one Bonferroni level and one validation ledger. The +``summary.json`` the runner then overwrites is kept as ``summary.before_validation.json``. +""" +import json +import shutil +import sys + +import evalrx.eval_agent.probing as probing +import evalrx.eval_agent.probing.validation as validation +from evalrx.benchmark import runner +from evalrx.benchmark.run import main + +ARMS = json.loads(sys.argv[1]) +argv = sys.argv[sys.argv.index("--") + 1:] +real_validate = validation.validate +orig = runner._run_triage + + +def arms(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline, **kw): + root = run_dir / "probing" + reports = {arm: json.loads((root / f"{name}.{arm}.json").read_text()) for arm, name in ARMS} + first = next(iter(reports.values())) + if (run_dir / "summary.json").is_file(): + shutil.copy(run_dir / "summary.json", run_dir / "summary.before_validation.json") + + def stored(*_a, **_k): + return first + + def union(model_, discovery, validation_, families_, reports_, **kw_): + # the runner's own entry (the first arm under the scheduler's report name) stays, for its summary + families = {**families_, **{arm: validation.freeze_issues(r) for arm, r in reports.items()}} + return real_validate(model_, discovery, validation_, families, {**reports_, **reports}, **kw_) + + probing.run_triage = stored + validation.validate = union + try: + return orig(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline, **kw) + finally: + validation.validate = real_validate + + +runner._run_triage = arms +sys.exit(main(argv)) diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index ef3e1645..8cf2e8cc 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -18,7 +18,7 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.model import Model -from evalrx.eval_agent.probing import explore_confirm_split, matched_sample, run_triage_mvp0 +from evalrx.eval_agent.probing import explore_confirm_split, matched_sample, run_triage from evalrx.eval_agent.probing.actions import ( FAILED, OK, @@ -545,7 +545,7 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): host_assumed_finish=True, n_needs_counterfactual=True, task_kind="yes_no", analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) - report = run_triage_mvp0(model, vlm_cases, **kw) + report = run_triage(model, vlm_cases, **kw) steps = _steps(report) assert [s["status"] for s in report["executions"]] == [OK] * 9 # 2 FAIL: no route proposes @@ -593,7 +593,7 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): # resume: same identities -> read back, no model calls, no new action cost # (only this invocation's Stage 0, which the caller did spend) n_forwards = model.n_forwards - again = run_triage_mvp0(model, vlm_cases, **kw) + again = run_triage(model, vlm_cases, **kw) assert all(s["reused"] for s in again["executions"]) and model.n_forwards == n_forwards costs2 = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] assert [c["kind"] for c in costs2[len(costs):]] == ["stage0"] and costs2[-1]["invocation"] == 2 @@ -601,7 +601,7 @@ def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): assert [e["event"] for e in events].count("reused") == 9 # a different model identity is a different action: nothing is reused - other = run_triage_mvp0(model, vlm_cases, **{**kw, "model_identity": {**ident, "dtype": "fp32"}}) + other = run_triage(model, vlm_cases, **{**kw, "model_identity": {**ident, "dtype": "fp32"}}) assert not any(s["reused"] for s in other["executions"]) @@ -616,11 +616,11 @@ def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch model = TinyVLM("qwen2_5_vl") kw = dict(out_dir=tmp_path / "v", model_identity={"spec": "tiny"}, n_fail=2, progress=None) - first = run_triage_mvp0(model, vlm_cases, **kw) + first = run_triage(model, vlm_cases, **kw) real = controller.tool_version monkeypatch.setattr(controller, "tool_version", lambda a: real(a) + ("-edited" if a.name == "attention_knockout" else "")) - second = run_triage_mvp0(model, vlm_cases, **kw) + second = run_triage(model, vlm_cases, **kw) assert _rerun(second) == ["attention_knockout"] assert _steps(second)["attention_knockout"]["action_id"] != _steps(first)["attention_knockout"]["action_id"] @@ -631,11 +631,11 @@ def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): model = TinyVLM("qwen2_5_vl") kw = dict(out_dir=tmp_path / "p", model_identity={"spec": "tiny"}, n_fail=2, progress=None) - first = run_triage_mvp0(model, vlm_cases, **kw) + first = run_triage(model, vlm_cases, **kw) ko_id = _steps(first)["attention_knockout"]["action_id"] ledger = Ledger(tmp_path / "p") (ledger.obs_dir / f"{ko_id}.json").unlink() # as if the process died before settling - second = run_triage_mvp0(model, vlm_cases, **kw) + second = run_triage(model, vlm_cases, **kw) planned = [e for e in ledger.trace_events() if e.get("event") == "planned" and e["action_id"] == ko_id] assert [e["attempt"] for e in planned] == [1, 2] assert planned[1]["previous_attempts_uncertain"] == 1 @@ -644,7 +644,7 @@ def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): def test_mvp0_black_box_gates_off_the_white_box_step(tmp_path, vlm_cases): model = _BlackBox() - report = run_triage_mvp0(model, vlm_cases, out_dir=tmp_path / "bb", model_identity={"spec": "bb"}, + report = run_triage(model, vlm_cases, out_dir=tmp_path / "bb", model_identity={"spec": "bb"}, n_fail=2, progress=None) steps = _steps(report) assert steps["attention_knockout"]["status"] == UNSUPPORTED @@ -684,7 +684,7 @@ def test_api_run_meters_tokens_and_dollars_and_runs_its_behavioural_follow_up(tm from evalrx.models.backends.api.prices import usd model = _FakeAPI() - report = run_triage_mvp0( + report = run_triage( model, vlm_cases, out_dir=tmp_path / "api", model_identity={"spec": "fake-api"}, n_fail=2, min_route_fail=1, task_kind="yes_no", n_needs_counterfactual=True, progress=None, analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_probing_mvp2.py index 7181b928..1ec8887a 100644 --- a/tests/test_eval_agent/test_probing_mvp2.py +++ b/tests/test_eval_agent/test_probing_mvp2.py @@ -450,3 +450,14 @@ def generate(self, inputs, **kwargs): same, rows = _split_equals_whole(registry.analyzers.get("format_sensitivity")(), _Letters({}), mc, cut=2) assert rows and same + + +def test_a_layer_that_narrows_its_route_states_its_filter(): + from evalrx.eval_agent.probing.rules import public, route_states + + records = _records() + [{"case_id": f"x{i}", "label": "fail", "stratum": "no", "routes": ["X"], "stable": False, + "N": {"state": "untested", "reason": "no counterfactual donor"}} for i in range(3)] + x1 = route_states("X", records, {}, _no_gate, str)[0] + assert x1["rule_id"] == "X1" and x1["n_fail"] == 3 + assert x1["case_filter"].startswith("X cases whose N check is missing") and "case_filter" in public(x1) + assert all("case_filter" not in st for st in route_states("N", records, {}, _no_gate, str)) diff --git a/tests/test_eval_agent/test_probing_mvp3b.py b/tests/test_eval_agent/test_probing_mvp3b.py index 1fdf2094..c19b1a1b 100644 --- a/tests/test_eval_agent/test_probing_mvp3b.py +++ b/tests/test_eval_agent/test_probing_mvp3b.py @@ -320,8 +320,8 @@ def test_the_rules_scheduler_does_not_take_an_explainer(tmp_path): **_kw(tmp_path / "r", explainer=Explainer(_Judge(), identity={}))) -def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence(tmp_path): - from evalrx.eval_agent.probing.compare import compare, markdown +def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence(tmp_path, capsys): + from evalrx.eval_agent.probing.compare import compare, main, markdown out = tmp_path / "c" rules = run_triage(_Table(_pope_like()[1]), _pope_like()[0], **_kw(out, max_fail=8, min_route_fail=1)) @@ -333,6 +333,10 @@ def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence( "n_conflicting_pairs"] assert diff["judge"]["other"]["n_calls"] == 1 and "tells apart" in markdown(diff) json.dumps(diff) + a, b = tmp_path / "a.json", tmp_path / "b.json" + a.write_text(json.dumps(rules, default=str)), b.write_text(json.dumps(explained, default=str)) + assert main([str(a), str(b)]) == 0 and "tells apart" in capsys.readouterr().out + assert main([str(a), str(b), "--json"]) == 0 and json.loads(capsys.readouterr().out)["same_sample"] is True @pytest.mark.parametrize("scheduler", ["rules", "scored"]) From b74d298a7b81f4e7b6224c8ec1513c836d9c9e9b Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:48:24 -0700 Subject: [PATCH 17/26] triage: experiment scripts moved out of the repository The drivers and analysis scripts of the triage17/18 scheduler comparison (run_triage17.sh, run_triage18.sh and its phase 2 and 3 variants, the GPU launcher, validate_arms.py, discovery_curve.py, recount_u.py and their README) were added to examples/benchmark/tools/triage/ by d6b9a2f. They are one experiment's drivers, not a feature of the package: nothing in the code or the tests uses them, the run scripts hard-code that experiment's model, dataset and budget tiers, and validate_arms.py monkeypatches the runner's private functions. They now live beside the design document, outside the repository (evalsmith/probing/scripts/, pointed at the checkout through TRIAGE_REPO). CHANGELOG and docs/agentic_benchmark.md no longer point at the directory. --- CHANGELOG.md | 9 +- docs/agentic_benchmark.md | 2 +- examples/benchmark/tools/triage/README.md | 70 --------------- examples/benchmark/tools/triage/_common.sh | 78 ---------------- .../benchmark/tools/triage/discovery_curve.py | 80 ----------------- .../tools/triage/launch_when_free.sh | 20 ----- examples/benchmark/tools/triage/recount_u.py | 89 ------------------- .../benchmark/tools/triage/run_triage17.sh | 17 ---- .../benchmark/tools/triage/run_triage18.sh | 27 ------ .../tools/triage/run_triage18_phase2.sh | 30 ------- .../tools/triage/run_triage18_phase3.sh | 32 ------- .../benchmark/tools/triage/validate_arms.py | 51 ----------- 12 files changed, 2 insertions(+), 503 deletions(-) delete mode 100644 examples/benchmark/tools/triage/README.md delete mode 100644 examples/benchmark/tools/triage/_common.sh delete mode 100644 examples/benchmark/tools/triage/discovery_curve.py delete mode 100755 examples/benchmark/tools/triage/launch_when_free.sh delete mode 100644 examples/benchmark/tools/triage/recount_u.py delete mode 100755 examples/benchmark/tools/triage/run_triage17.sh delete mode 100755 examples/benchmark/tools/triage/run_triage18.sh delete mode 100755 examples/benchmark/tools/triage/run_triage18_phase2.sh delete mode 100755 examples/benchmark/tools/triage/run_triage18_phase3.sh delete mode 100644 examples/benchmark/tools/triage/validate_arms.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7693b575..886ee7a2 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,14 +6,7 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] -### Changed — probing: protocol scripts kept in the repo, dead code removed, `compare` has a CLI - -The drivers of the multi-arm scheduler comparison (`run_triage17.sh`, `run_triage18.sh` -and its phase 2 and 3 variants, the GPU launcher) and the analysis scripts behind the -design document's tables (the union validation `validate_arms.py`, the budget-matched -discovery curve, the U re-count under the tolerant agreement rule) lived in a job's -scratch directory; they are now `examples/benchmark/tools/triage/` with a README, the -machine-specific paths taken from the environment. +### Changed — probing: dead code removed, `compare` has a CLI Removed what later code had superseded: `Ledger.spent` / `spent_wall_sec` (the budget is charged by `_Run.charged`), `StepEvidence.sec_per_case` (costs come from diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 9be55839..0e3d69fc 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -43,7 +43,7 @@ After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage **Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); `--confirm-split-by media` instead draws the explore/confirm split over media groups, whole images on one side, so nothing is left out (default `case`: the judge-driven loop's split, which a triage run must share to be compared case for case); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. -**Multi-arm protocol.** The scheduler comparison (rules, scored, scored without exploration, scored with D, random, cheapest; each at the full budget and at budget tiers) runs every arm into one run directory on a shared ledger, copies each arm's report aside as `triage_report...json`, then validates the union of the arms' frozen families once. The drivers and the analysis scripts (the union validation, the budget-matched discovery curve, the U re-count under the tolerant agreement rule) are under `examples/benchmark/tools/triage/` with a README; `python -m evalrx.eval_agent.probing.compare a.json b.json` puts two arms' reports side by side. +**Multi-arm protocol.** The scheduler comparison (rules, scored, scored without exploration, scored with D, random, cheapest; each at the full budget and at budget tiers) runs every arm into one run directory on a shared ledger, copies each arm's report aside as `triage_report...json`, then validates the union of the arms' frozen families once. The drivers of that comparison are experiment scripts kept outside the package; `python -m evalrx.eval_agent.probing.compare a.json b.json` puts two arms' reports side by side. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. diff --git a/examples/benchmark/tools/triage/README.md b/examples/benchmark/tools/triage/README.md deleted file mode 100644 index 21462773..00000000 --- a/examples/benchmark/tools/triage/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# Triage protocol scripts - -The drivers and analysis scripts of the scheduler comparison run with `--m1-policy triage_active` -(design and results: `evalsmith/probing/probing_design_mix.md`; the controller: -[`docs/agentic_benchmark.md`](../../../../docs/agentic_benchmark.md), "Triage policy"). They were -written as scratch for the triage17/18 runs on Qwen3.5-2B and ChartQA and are kept here so the -protocol and the tables derived from it can be re-run. Machine-specific values (python, scratch -directory, data and output roots, the judge) come from the environment; see `_common.sh`. - -## The protocol - -Every arm is one `evalrx.benchmark.run` invocation into the **same run directory**, so the arms -share one observation ledger (an action with the same identity is read back, not re-run) and each -is charged what its evidence cost when first executed. After each arm its report is copied aside -as `probing/..json`; then `validate_arms.py` runs the benchmark entry once more -with the controller replaced by the stored reports and the runner's `validate()` replaced by one -over the union of every arm's frozen issues: one family, one Bonferroni level, one validation -ledger, every arm credited with its own issues (`validation/validation_report.{json,md}`, -`validation/frozen.json`). - -| arm | flags | -|---|---| -| `rules` | `--triage-scheduler rules` | -| `scored` | `--triage-scheduler scored` | -| `scored_x0` | `--triage-scheduler scored --triage-explore-share 0` | -| `scored_d` | `--triage-scheduler scored --triage-explanations judge` (judge: `JUDGE_FLAGS`) | -| `random`, `cheapest` | `--triage-scheduler random` / `cheapest` (controls over the scored candidates) | -| budget tier `b` | `--triage-budget-sec N`; `full` = no cap | - -Common to every arm: `--triage-n-fail 8 --triage-max-fail <32 or 128> --triage-max-actions 30 ---triage-chunk 8`, `--attn-impl eager`, the frozen ChartQA pool (`--data-dir ... --limit 1000`), -one GPU with nothing else on it (`CUDA_VISIBLE_DEVICES`, `CUDA_DEVICE_ORDER=PCI_BUS_ID`), weights -offline, a private `TMPDIR`, and no `CLAUDE*` variables in the environment (the claude CLI judge -must not see a parent session). - -## Scripts - -| script | what it did | -|---|---| -| `_common.sh` | sourced by the run scripts: paths from the environment, the arm table, code snapshots, the arm loop, the union validation | -| `run_triage17.sh` | triage17 (10-21/22): triage16's 12 stored arms validated once more with a validation-only source added (`--triage-validation-source`) | -| `run_triage18.sh` | triage18 phase 1 (10-22/23): the 12 arms (rules / scored / scored_x0 / scored_d x full / b700 / b900) at `--triage-max-fail 128` on a code snapshot (commit 0d01bb6), then their union validation | -| `run_triage18_phase2.sh` | phase 2 (10-23/24): the controls at full budget and the budget tiers 4000 / 5500 / 7100 s for all six schedulers (20 arms) added to the same directory, then the 32-arm union validation; the 12-arm validation kept as `*.12arms.*` | -| `run_triage18_phase3.sh` | phase 3 (10-24): all 32 arms again under the `step_cost` fix (scoring `mvp3-score-5`), phase-2 reports moved to `probing/arms_p2/` and its validation kept as `*.32arms_p2.*` | -| `launch_when_free.sh` | polls for a GPU with under 3 GB in use every 20 s and starts a run script on it | -| `validate_arms.py` | the union validation driver the run scripts call | -| `discovery_curve.py` | budget-matched discovery curve: supported phenomena each arm had found within a charged budget B (the design document's "预算对齐" tables) | -| `recount_u.py` | re-reads a run's stored U evidence under the exact and the tolerant agreement rule (the rules-5 "离线重算" table) | - -The phase scripts are idempotent: an arm whose report copy exists is skipped, so a killed run is -resumed by starting the script again. The 700 / 900 s tiers are kept in the phase-3 validation but -not interpreted: at `--triage-max-fail 128` they stop inside the first expansion. - -## Data - -The ChartQA pool is `examples/benchmark/vlm/_data/triage_pool/chartqa/` (1000 human-authored rows, -seed 5022, frozen from the HF cache with `python -m evalrx.benchmark.tasks.chartqa`), and the -validation-only source `.../triage_pool/chartqa_validation/` is every human row the pool left -(`python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json`). `_data/` is -not committed; `partition_bundle.json` records each manifest's sha1. - -## Usage - -```bash -export PY=/path/to/venv/bin/python TRIAGE_SCRATCH=/path/to/scratch # see _common.sh for the rest -nohup bash examples/benchmark/tools/triage/launch_when_free.sh run_triage18_phase3.sh > launcher.log 2>&1 & -python examples/benchmark/tools/triage/discovery_curve.py --grid 3000 4000 5000 6000 7095 -python -m evalrx.eval_agent.probing.compare /probing/triage_report.rules_full.json \ - /probing/triage_report.scored.scored_full.json -``` diff --git a/examples/benchmark/tools/triage/_common.sh b/examples/benchmark/tools/triage/_common.sh deleted file mode 100644 index 222016dd..00000000 --- a/examples/benchmark/tools/triage/_common.sh +++ /dev/null @@ -1,78 +0,0 @@ -# Shared settings of the triage protocol scripts (sourced by run_*.sh, not run). -# Machine-specific values come from the environment: -# PY python with evalrx and the model stack (default: python; the runs used a vLLM/transformers venv) -# TRIAGE_SCRATCH logs, a private TMPDIR and code snapshots (default: ~/.cache/evalrx/triage) -# TRIAGE_DATA the frozen ChartQA pool (default: /examples/benchmark/vlm/_data/triage_pool) -# TRIAGE_OUT the run-directory root (default: /examples/benchmark/vlm/qwen/host_outputs) -# TRIAGE_SOURCE the validation-only manifest (default: $TRIAGE_DATA/chartqa_validation/manifest.json) -# TRIAGE_MODEL / TRIAGE_DATASET the model spec and task (default: qwen3.5-2b-vl / chartqa) -# JUDGE_FLAGS the judge of the scored_d arms (default: claude-opus-5 through the claude CLI, effort high) -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO=$(cd "$HERE/../../../.." && pwd) -PY=${PY:-python} -SCRATCH=${TRIAGE_SCRATCH:-$HOME/.cache/evalrx/triage} -DATA=${TRIAGE_DATA:-$REPO/examples/benchmark/vlm/_data/triage_pool} -OUT=${TRIAGE_OUT:-$REPO/examples/benchmark/vlm/qwen/host_outputs} -SRC=${TRIAGE_SOURCE:-$DATA/chartqa_validation/manifest.json} -MODEL=${TRIAGE_MODEL:-qwen3.5-2b-vl} -DATASET=${TRIAGE_DATASET:-chartqa} -JUDGE_FLAGS=${JUDGE_FLAGS:---judge-provider claude --judge-model claude-opus-5 --judge-effort high} -mkdir -p "$SCRATCH" - -common_flags() { # : the flags every arm shares (model, data, protocol constants) - echo "--modality vlm --model $MODEL --backend hf_local --dataset $DATASET --data-dir $DATA --run-dir $OUT --run-tag $1 --limit 1000 --no-download --device cuda --attn-impl eager --m1-policy triage_active --triage-n-fail 8 --triage-max-fail $2 --triage-max-actions 30 --triage-chunk 8 $JUDGE_FLAGS" -} -report_name() { # -> the report stem run_triage writes - case $1 in rules) echo triage_report ;; scored|scored_x0) echo triage_report.scored ;; scored_d) echo triage_report.scored_d ;; - random) echo triage_report.random ;; cheapest) echo triage_report.cheapest ;; esac -} -sched_flags() { # -> its flags - case $1 in rules) echo "--triage-scheduler rules" ;; scored) echo "--triage-scheduler scored" ;; - scored_x0) echo "--triage-scheduler scored --triage-explore-share 0" ;; - scored_d) echo "--triage-scheduler scored --triage-explanations judge" ;; - random) echo "--triage-scheduler random" ;; cheapest) echo "--triage-scheduler cheapest" ;; esac -} -budget_flags() { # > - case $1 in b*) echo "--triage-budget-sec ${1#b}" ;; esac -} -arm_names_json() { # -> the JSON list validate_arms.py takes - local s="[" a k b - for a in "$@"; do k=${a%:*}; b=${a#*:}; s="$s[\"${k}_${b}\",\"$(report_name "$k")\"],"; done - echo "${s%,}]" -} -snapshot_code() { # : the code the arms run on, so the working tree can change meanwhile - mkdir -p "$1" || return 1 - if [ "$2" = worktree ]; then (cd "$REPO" && git ls-files -z | rsync -a --files-from=- --from0 ./ "$1"/) - else (cd "$REPO" && git archive "$2") | tar -x -C "$1"; fi -} -prepare_env() { # : one GPU, offline weights, a private TMPDIR - local v - for v in $(env | grep -o '^CLAUDE[^=]*'); do unset "$v"; done # the claude CLI judge must not see a parent session - export CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=$1 HF_HUB_OFFLINE=1 PYTHONPATH=$2 - export TMPDIR=$SCRATCH/tmp_$3; mkdir -p "$TMPDIR" -} -run_arms() { # : each arm once; its report copy marks it done - local log=$1 run=$2 common=$3 a k b arm name flags rc; shift 3 - for a in "$@"; do - k=${a%:*}; b=${a#*:}; arm=${k}_${b}; name=$(report_name "$k"); flags="$(sched_flags "$k") $(budget_flags "$b")" - if [ -f "$run/probing/$name.$arm.json" ]; then echo "SKIP $arm (report copy exists)" >> "$log"; continue; fi - echo "ARM $arm start $(date '+%m-%d %H:%M'): $flags" >> "$log" - $PY -u -m evalrx.benchmark.run $common $flags >> "$log" 2>&1 - rc=$? - if [ $rc -ne 0 ] || [ ! -f "$run/probing/$name.json" ]; then echo "ARM $arm FAILED rc=$rc at $(date '+%m-%d %H:%M')" >> "$log"; return 1; fi - cp "$run/probing/$name.json" "$run/probing/$name.$arm.json"; cp "$run/probing/$name.md" "$run/probing/$name.$arm.md" - echo "ARM $arm done $(date '+%m-%d %H:%M')" >> "$log" - done -} -validate_union() { # : one Stage 0 (plus the source's), then the union validation - echo "VALIDATE start $(date '+%m-%d %H:%M')" >> "$1" - $PY -u "$HERE/validate_arms.py" "$2" -- $3 --triage-validate --triage-validation-source "$SRC" >> "$1" 2>&1 - echo "EXIT validate $? at $(date '+%m-%d %H:%M')" >> "$1" -} -keep_aside() { # : copy the current validation report and frozen family aside, once - local v=$1/validation - if [ -f "$v/validation_report.json" ] && [ ! -f "$v/validation_report.$2.json" ]; then - cp "$v/validation_report.json" "$v/validation_report.$2.json"; cp "$v/validation_report.md" "$v/validation_report.$2.md" - cp "$v/frozen.json" "$v/frozen.$2.json" - fi -} diff --git a/examples/benchmark/tools/triage/discovery_curve.py b/examples/benchmark/tools/triage/discovery_curve.py deleted file mode 100644 index ca3aa2e2..00000000 --- a/examples/benchmark/tools/triage/discovery_curve.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Budget-matched discovery curve of a multi-arm run directory (no model, no GPU). - -For each arm, the number of validation-supported phenomena whose issues the arm had discovered within a -charged budget B. An issue counts as discovered at the charge of its step's last execution on its route (a -battery step: on the whole sample; a route signal: once the five route steps have run), so the curve is -conservative for a chunked step (its last chunk). Charges follow the report: every execution the arm read, -at the cost of its first execution (a read-back at its original cost, once); judge calls are not charged. - -usage: python discovery_curve.py [--arms arm:report_stem ...] [--grid B ...] - e.g. python discovery_curve.py .../chartqa.triage18-chartqa-2b-mf128 --arms rules_full:triage_report \ - scored_full:triage_report.scored --grid 3000 4000 5000 6000 7095 -""" -import argparse -import json -import math -from pathlib import Path - -ROUTE_STEPS = {"answer_extraction_audit", "termination_audit", "modality_ablation", "self_consistency", "prompt_reword"} -DEFAULT_ARMS = ["rules_full:triage_report", "scored_full:triage_report.scored", - "scored_x0_full:triage_report.scored", "scored_d_full:triage_report.scored_d"] -DEFAULT_GRID = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000] - - -def curve_of(run: Path, arm: str, stem: str, report: dict, frozen: dict, grid: list) -> dict: - probing = run / "probing" - phen_of = {iid: p["id"] for p in report["phenomena"] for iid in p["issues"]} - supported = {p["id"] for p in report["phenomena"] if p["verdict"] == "supported"} - issue_by_id = {i["issue_id"]: i for i in report["issues"]} - r = json.loads((probing / f"{stem}.{arm}.json").read_text()) - seen, charge, cum = set(), 0.0, [] - for e in r["executions"]: - aid = e.get("action_id") - if aid is None: - charge += float((e.get("cost") or {}).get("wall_sec") or 0.0) - elif aid not in seen: - seen.add(aid) - f = probing / "observations" / f"{aid}.json" - obs = json.loads(f.read_text()) if f.is_file() else {} - charge += float((obs.get("cost") or e.get("cost") or {}).get("wall_sec") or 0.0) - cum.append((e, charge)) - settled = max((c for e, c in cum if e.get("key") in ROUTE_STEPS), default=0.0) # the routes are known - found_at = {} - for iid in frozen["arms"].get(arm) or []: - i = issue_by_id[iid] - if not i.get("step"): - found_at[iid] = settled # a route signal: known once the route steps ran - continue - # a follow-up is keyed by route; a battery step runs on the whole sample (route None) - last = [c for e, c in cum if e.get("key") == i["step"] and e.get("route") in (i["route"], None)] - if not last: # a reading frozen for a route from a step that ran on another route's cases - last = [c for e, c in cum if e.get("key") == i["step"]] - found_at[iid] = max(last) if last else None - curve = [len({phen_of[iid] for iid, c in found_at.items() - if c is not None and c <= B and phen_of.get(iid) in supported}) for B in grid] - return {"total_charged": round(r["cost"]["charged"]["wall_sec"]), "settled_at": round(settled), "curve": curve, - "found_at": {phen_of.get(k, "?"): (round(v) if v is not None else None) for k, v in found_at.items()}} - - -def main() -> int: - p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - p.add_argument("run", type=Path, help="the run directory (holding probing/ and validation/)") - p.add_argument("--arms", nargs="+", default=DEFAULT_ARMS, metavar="ARM:STEM", - help="arm name and its report stem, e.g. rules_full:triage_report") - p.add_argument("--grid", nargs="+", type=float, default=DEFAULT_GRID, metavar="B", - help="charged budgets (seconds) to count the supported phenomena found within") - a = p.parse_args() - report = json.loads((a.run / "validation" / "validation_report.json").read_text()) - frozen = json.loads((a.run / "validation" / "frozen.json").read_text()) - grid = [*a.grid, math.inf] - for spec in a.arms: - arm, stem = spec.split(":", 1) - row = curve_of(a.run, arm, stem, report, frozen, grid) - print(f"{arm:16s} charged={row['total_charged']:6d} settled={row['settled_at']:6d} " - f"curve@{[int(b) for b in grid[:-1]] + ['total']}: {row['curve']}") - print(" phenomenon -> found at:", dict(sorted(row["found_at"].items(), key=lambda kv: (kv[1] is None, kv[1] or 0)))) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/examples/benchmark/tools/triage/launch_when_free.sh b/examples/benchmark/tools/triage/launch_when_free.sh deleted file mode 100755 index 2ed23f46..00000000 --- a/examples/benchmark/tools/triage/launch_when_free.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -# Poll every 20 s for a GPU with under 3 GB in use and start the given protocol script on it at once (a 60 s -# poll lost a free GPU to another user within the minute). A GPU is never shared. -# usage: launch_when_free.sh [its arguments after the gpu index...] -# e.g. nohup bash launch_when_free.sh run_triage18_phase3.sh > launcher.log 2>&1 & -set -u -SCRIPT=${1:?run script}; shift -HERE=$(cd "$(dirname "$0")" && pwd) -[ -f "$SCRIPT" ] || SCRIPT=$HERE/$SCRIPT -for _ in $(seq 1 4320); do # up to 24 h - free=$(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader,nounits | awk -F', ' '$2 < 3000 {print $1}' | head -1) - if [ -n "$free" ]; then - echo "LAUNCH $(basename "$SCRIPT") on GPU $free at $(date '+%m-%d %H:%M')" - bash "$SCRIPT" "$free" "$@" - echo "RUN_DONE rc=$? at $(date '+%m-%d %H:%M')" - exit 0 - fi - sleep 20 -done -echo "NO_GPU after 24h"; exit 1 diff --git a/examples/benchmark/tools/triage/recount_u.py b/examples/benchmark/tools/triage/recount_u.py deleted file mode 100644 index ec40c7b1..00000000 --- a/examples/benchmark/tools/triage/recount_u.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Re-read a run's stored U evidence under the exact and the tolerant agreement rule (no model, no GPU). - -usage: python recount_u.py - -Reads the self_consistency and prompt_reword observations of the run's probing/ and validation/ ledgers and -re-derives every case's U check with ``triage._u_check`` twice: with key equality (``exact_answer``, the rule up -to rules-4) and with the task's tolerant rule (``tasks.same_answer``, rules-5). Prints the fired/clear/untested -tallies per label and the FAIL cases whose U state flips. The case labels come from the run's baseline.json -(and baseline_validation_source.json for the validation ledger); the task metadata is ChartQA's. -""" -import json -import sys -from collections import Counter -from pathlib import Path -from types import SimpleNamespace - -from evalrx.benchmark import tasks -from evalrx.eval_agent.probing.actions import Observation -from evalrx.eval_agent.probing.triage import _u_check, exact_answer - -D = Path(sys.argv[1]) -META = {"task": "exact_or_numeric", "numeric_tolerance": 0.05} - - -def cases_of(*files): - out = {} - for f in files: - if not (D / f).is_file(): - continue - for r in json.load(open(D / f))["cases"]: - out[r["id"]] = SimpleNamespace(id=r["id"], observed=r["observed"], label=r["label"], metadata=META) - return out - - -def chunks(sub): - root = D / sub / "observations" - idx = [json.loads(line) for line in open(root / "index.jsonl")] - by = {"self_consistency": [], "prompt_reword": []} - for r in dict.fromkeys(x["action_id"] for x in idx): - o = Observation.from_dict(json.load(open(root / f"{r}.json"))) - if o.status != "ok": - continue - if o.analyzer == "self_consistency": - by["self_consistency"].append(o) - elif o.analyzer == "prompt_contrast" and "question_frame" in (o.params.get("strategies") or {}): - by["prompt_reword"].append(o) - return by - - -def for_case(objs, cid): - for o in reversed(objs): - if cid in o.planned_ids: - return o - return None - - -def recount(sub, cases): - by = chunks(sub) - covered = sorted({c for o in by["self_consistency"] for c in o.planned_ids} - | {c for o in by["prompt_reword"] for c in o.planned_ids}) - tally = {} - for rule, agree in (("exact", exact_answer), ("tolerant", tasks.same_answer)): - t = {lab: Counter() for lab in ("fail", "pass")} - for cid in covered: - case = cases.get(cid) - if case is None: - continue - u = _u_check(for_case(by["self_consistency"], cid), for_case(by["prompt_reword"], cid), case, - tasks.answer_key, agree) - lab = t[case.label] - lab["n"] += 1 - lab[f"U_{u['state']}"] += 1 - for part in u["parts"]: - lab[f"{part['part']}_{part['state']}"] += 1 - tally[rule] = {k: dict(v) for k, v in t.items()} - print(sub, json.dumps(tally, indent=1, sort_keys=True)) - flips = Counter() # which FAIL cases change state between the two rules - for cid in covered: - case = cases.get(cid) - if case is None or case.label != "fail": - continue - states = [_u_check(for_case(by["self_consistency"], cid), for_case(by["prompt_reword"], cid), case, - tasks.answer_key, agree)["state"] for agree in (exact_answer, tasks.same_answer)] - flips[f"{states[0]}->{states[1]}"] += 1 - print(sub, "FAIL U transitions", dict(flips)) - - -recount("probing", cases_of("baseline.json")) -recount("validation", cases_of("baseline.json", "baseline_validation_source.json")) diff --git a/examples/benchmark/tools/triage/run_triage17.sh b/examples/benchmark/tools/triage/run_triage17.sh deleted file mode 100755 index c2978c46..00000000 --- a/examples/benchmark/tools/triage/run_triage17.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -# triage17 (10-21/22): triage16's stored arms, validated once more on DIAGNOSTIC_VALIDATION extended by the -# validation-only source (the human rows the pool left: the rest of the test split plus the val split). Only -# the validation runs (two Stage 0 passes: the pool's and the source's); the code is the working tree. -# usage: run_triage17.sh [run tag] [source manifest] -set -u -. "$(dirname "$0")/_common.sh" -GPU=${1:?gpu index} -TAG=${2:-triage17-chartqa-2b-extval} -SRC=${3:-$SRC} -LOG=$SCRATCH/validate_$TAG.log -COMMON=$(common_flags "$TAG" 32) -ARMS="rules:full scored:full scored_x0:full scored_d:full rules:b700 scored:b700 scored_x0:b700 scored_d:b700 rules:b900 scored:b900 scored_x0:b900 scored_d:b900" -prepare_env "$GPU" "$REPO" "$TAG" -cd "$REPO" || exit 1 -echo "START $TAG validation on GPU $GPU at $(date '+%m-%d %H:%M') source=$SRC" >> "$LOG" -validate_union "$LOG" "$(arm_names_json $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/run_triage18.sh b/examples/benchmark/tools/triage/run_triage18.sh deleted file mode 100755 index 1d9ac4eb..00000000 --- a/examples/benchmark/tools/triage/run_triage18.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# triage18 phase 1 (10-22/23): the 12-arm protocol of triage12-16 (rules / scored / scored_x0 / scored_d x -# full / b700 / b900) under rules-5 with --triage-max-fail 128, then the 12 arms validated together on CONFIRM -# plus the validation-only source. The arms run on a code snapshot (the original run: commit 0d01bb6), so the -# working tree can be edited meanwhile; triage17's observation ledgers are copied in for chunk reuse. -# Idempotent: an arm whose report copy exists is skipped. -# usage: run_triage18.sh [git ref to snapshot, default HEAD] -set -u -. "$(dirname "$0")/_common.sh" -GPU=${1:?gpu index}; REF=${2:-HEAD} -TAG=triage18-chartqa-2b-mf128 -RUN=$OUT/$MODEL/$DATASET.$TAG -PREV=$OUT/$MODEL/$DATASET.triage17-chartqa-2b-extval -LOG=$SCRATCH/run_$TAG.log -CODE=$SCRATCH/code_${TAG}_$(date +%s) -COMMON=$(common_flags "$TAG" 128) -ARMS="rules:full scored:full scored_x0:full scored_d:full rules:b700 scored:b700 scored_x0:b700 scored_d:b700 rules:b900 scored:b900 scored_x0:b900 scored_d:b900" - -snapshot_code "$CODE" "$REF" || exit 1 -prepare_env "$GPU" "$CODE" "$TAG" -cd "$CODE" || exit 1 -mkdir -p "$RUN/probing" "$RUN/validation" -[ -d "$RUN/probing/observations" ] || { [ -d "$PREV/probing/observations" ] && cp -r "$PREV/probing/observations" "$RUN/probing/"; } -[ -d "$RUN/validation/observations" ] || { [ -d "$PREV/validation/observations" ] && cp -r "$PREV/validation/observations" "$RUN/validation/"; } -echo "START $TAG on GPU $GPU at $(date '+%m-%d %H:%M') code=$CODE ($REF)" >> "$LOG" -run_arms "$LOG" "$RUN" "$COMMON" $ARMS || exit 1 -validate_union "$LOG" "$(arm_names_json $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/run_triage18_phase2.sh b/examples/benchmark/tools/triage/run_triage18_phase2.sh deleted file mode 100755 index 819e13ab..00000000 --- a/examples/benchmark/tools/triage/run_triage18_phase2.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -# triage18 phase 2 (10-23/24), in the triage18 run directory (shared probing ledger), one GPU, one go: -# 1. the controls at the full budget: random_full, cheapest_full; -# 2. the rescaled budget tiers 4000 / 5500 / 7100 s for all six schedulers = 18 arms (at max_fail 128 the -# 700/900 s tiers stop inside the expansion and are all alike); -# 3. one union validation over all 32 arms (validation ledger reused; the 12-arm report kept as *.12arms.*). -# The arms run on a snapshot of the working tree's tracked files (the original run carried the control -# schedulers before they were committed as 2695741). Idempotent. usage: run_triage18_phase2.sh -set -u -. "$(dirname "$0")/_common.sh" -GPU=${1:?gpu index} -TAG=triage18-chartqa-2b-mf128 -RUN=$OUT/$MODEL/$DATASET.$TAG -LOG=$SCRATCH/run_${TAG}_phase2.log -CODE=$SCRATCH/code_${TAG}_p2_$(date +%s) -COMMON=$(common_flags "$TAG" 128) -PHASE1="rules:full scored:full scored_x0:full scored_d:full rules:b700 scored:b700 scored_x0:b700 scored_d:b700 rules:b900 scored:b900 scored_x0:b900 scored_d:b900" -ARMS="random:full cheapest:full" -for b in 4000 5500 7100; do for k in rules scored scored_x0 scored_d random cheapest; do ARMS="$ARMS $k:b$b"; done; done - -snapshot_code "$CODE" worktree || exit 1 -grep -q '"cheapest"' "$CODE/evalrx/eval_agent/probing/controller.py" || { echo "snapshot has no control schedulers" >> "$LOG"; exit 1; } -[ -f "$RUN/probing/triage_report.rules_full.json" ] || { echo "phase 1 arms missing" >> "$LOG"; exit 1; } -prepare_env "$GPU" "$CODE" "${TAG}_phase2" -cd "$CODE" || exit 1 -echo "START phase2 on GPU $GPU at $(date '+%m-%d %H:%M') code=$CODE (HEAD $(git -C "$REPO" rev-parse --short HEAD) + $(git -C "$REPO" status --short | wc -l) modified files)" >> "$LOG" -echo "ARMS: $ARMS" >> "$LOG" -keep_aside "$RUN" 12arms -run_arms "$LOG" "$RUN" "$COMMON" $ARMS || exit 1 -validate_union "$LOG" "$(arm_names_json $PHASE1 $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/run_triage18_phase3.sh b/examples/benchmark/tools/triage/run_triage18_phase3.sh deleted file mode 100755 index 8f837098..00000000 --- a/examples/benchmark/tools/triage/run_triage18_phase3.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -# triage18 phase 3 (10-24), in the triage18 run directory (shared probing ledger), one GPU, one go: every one -# of the 32 arms again under the step_cost fix (scoring mvp3-score-5: a zero-call audit is priced at what it -# measured, so an expansion's estimate is no longer 3.5-24x its cost), then one union validation over the 32 -# arms. Phase-2 artefacts are kept: arm reports under probing/arms_p2/, the validation as *.32arms_p2.*. -# The arms run on a snapshot of the working tree's tracked files. Idempotent. usage: run_triage18_phase3.sh -set -u -. "$(dirname "$0")/_common.sh" -GPU=${1:?gpu index} -TAG=triage18-chartqa-2b-mf128 -RUN=$OUT/$MODEL/$DATASET.$TAG -LOG=$SCRATCH/run_${TAG}_phase3.log -CODE=$SCRATCH/code_${TAG}_p3_$(date +%s) -COMMON=$(common_flags "$TAG" 128) -ARMS="" -for k in rules scored scored_x0 scored_d random cheapest; do ARMS="$ARMS $k:full"; done -for b in 700 900; do for k in rules scored scored_x0 scored_d; do ARMS="$ARMS $k:b$b"; done; done -for b in 4000 5500 7100; do for k in rules scored scored_x0 scored_d random cheapest; do ARMS="$ARMS $k:b$b"; done; done - -snapshot_code "$CODE" worktree || exit 1 -grep -q 'mvp3-score-5' "$CODE/evalrx/eval_agent/probing/scoring.py" || { echo "snapshot lacks the step_cost fix" >> "$LOG"; exit 1; } -prepare_env "$GPU" "$CODE" "${TAG}_phase3" -cd "$CODE" || exit 1 -echo "START phase3 on GPU $GPU at $(date '+%m-%d %H:%M') code=$CODE (HEAD $(git -C "$REPO" rev-parse --short HEAD) + $(git -C "$REPO" status --short | wc -l) modified files)" >> "$LOG" -echo "ARMS: $ARMS" >> "$LOG" -if [ ! -d "$RUN/probing/arms_p2" ]; then # keep phase 2's arm reports aside, once - mkdir -p "$RUN/probing/arms_p2" - for a in $ARMS; do k=${a%:*}; b=${a#*:}; n=$(report_name "$k"); mv "$RUN/probing/$n.${k}_$b.json" "$RUN/probing/$n.${k}_$b.md" "$RUN/probing/arms_p2/" 2>> "$LOG"; done -fi -keep_aside "$RUN" 32arms_p2 -run_arms "$LOG" "$RUN" "$COMMON" $ARMS || exit 1 -validate_union "$LOG" "$(arm_names_json $ARMS)" "$COMMON" diff --git a/examples/benchmark/tools/triage/validate_arms.py b/examples/benchmark/tools/triage/validate_arms.py deleted file mode 100644 index e94d4d26..00000000 --- a/examples/benchmark/tools/triage/validate_arms.py +++ /dev/null @@ -1,51 +0,0 @@ -"""One Stage 0 (plus the validation source's), then the stored triage arms of a run directory validated together. - -usage: python validate_arms.py '' -- - -Every arm of a comparison runs ``evalrx.benchmark.run`` into the same run directory, each copying its report -aside as ``probing/..json`` (see ``_common.sh``). This driver then runs the benchmark entry -once more with two of the runner's steps replaced: the controller is not run (the first listed arm's stored -report stands in for it), and the runner's ``validate()`` call becomes one over the union of every listed -arm's frozen issues, so the arms share one family, one Bonferroni level and one validation ledger. The -``summary.json`` the runner then overwrites is kept as ``summary.before_validation.json``. -""" -import json -import shutil -import sys - -import evalrx.eval_agent.probing as probing -import evalrx.eval_agent.probing.validation as validation -from evalrx.benchmark import runner -from evalrx.benchmark.run import main - -ARMS = json.loads(sys.argv[1]) -argv = sys.argv[sys.argv.index("--") + 1:] -real_validate = validation.validate -orig = runner._run_triage - - -def arms(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline, **kw): - root = run_dir / "probing" - reports = {arm: json.loads((root / f"{name}.{arm}.json").read_text()) for arm, name in ARMS} - first = next(iter(reports.values())) - if (run_dir / "summary.json").is_file(): - shutil.copy(run_dir / "summary.json", run_dir / "summary.before_validation.json") - - def stored(*_a, **_k): - return first - - def union(model_, discovery, validation_, families_, reports_, **kw_): - # the runner's own entry (the first arm under the scheduler's report name) stays, for its summary - families = {**families_, **{arm: validation.freeze_issues(r) for arm, r in reports.items()}} - return real_validate(model_, discovery, validation_, families, {**reports_, **reports}, **kw_) - - probing.run_triage = stored - validation.validate = union - try: - return orig(args, task, resolved, spec, model, gen_kwargs, cases, ctx, run_dir, baseline, **kw) - finally: - validation.validate = real_validate - - -runner._run_triage = arms -sys.exit(main(argv)) From 58b3d0de29cd45c3c2673352d448044c3fb01f73 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:34:02 -0700 Subject: [PATCH 18/26] triage: every run records the code it ran (code_version) The only version a run kept was tool_version: a hash of the analyzer's own file and analyzers/_internals, part of the action identity. A change anywhere else (a backend, the executor, the scheduler) left no trace, although costs move with it: the 10-22 media-encoder no-grad fix that cut gradcam from 30 s to 9 s a chunk was in hf_local. A ledger shared across invocations could thus hold observations from different code with nothing to tell them apart, which a cross-run record of analyzer cost and yield needs. controller.code_version() (once per process) gives tree a content hash of every evalrx *.py file (no __pycache__, node_modules), parts the same hash per package directory (models, eval_agent/probing, ...; "." = the top-level modules), to tell a backend change from a scheduler one, git the checkout's commit and whether tracked files under evalrx differ from it; in a code snapshot (no .git) the CODE_REF.json the snapshot carries; else null. The triage and validation reports carry it as "code" (their markdown says it in the first lines), the triage summary.json too; every planned trace event and every Stage-0 cost line carry the tree. Observation files are unchanged (join on action_id). It is recorded only, not part of any identity: a change outside the analyzer still reads the ledger back, exactly as before. Tests: the report, the planned events, the Stage-0 lines and the markdown carry it; a different tree reuses every action; per-directory hashes move only where a file changed; a snapshot's CODE_REF.json is read. Full suite 2836 passed / 16 skipped; ruff clean. --- evalrx/benchmark/runner.py | 1 + evalrx/eval_agent/probing/controller.py | 74 ++++++++++++++++++- evalrx/eval_agent/probing/validation.py | 13 +++- tests/test_eval_agent/test_probing_mvp0.py | 44 +++++++++++ .../test_probing_validation.py | 6 ++ 5 files changed, 133 insertions(+), 5 deletions(-) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index bb4adf8b..ebed2018 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -534,6 +534,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "triage_steps": [{k: s.get(k) for k in ("kind", "key", "analyzer", "status", "reused", "n_cases")} for s in report["executions"]], "triage_stop": report["stop"], "triage_scheduler": report["scheduler"], + "code": report["code"], "triage_explanations": args.triage_explanations, **({"validation": {"frozen_sha1": checked["frozen_sha1"], **checked["arms"][name]}} if checked else {}), } diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index cd51768e..3d4cacd9 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -78,7 +78,7 @@ import random import time from collections import Counter -from functools import partial +from functools import lru_cache, partial from pathlib import Path from typing import TYPE_CHECKING, Any, Callable @@ -270,6 +270,70 @@ def tool_version(analyzer: Any) -> str: return h.hexdigest()[:12] +@lru_cache(maxsize=1) +def code_version() -> dict[str, Any]: + """The code this process runs: recorded in the reports and on every planned action. + + ``tree`` hashes every ``*.py`` file of the evalrx package, ``parts`` the same per + package directory (``models``, ``eval_agent/probing``, ...; ``.`` = the top-level + modules), so a reader can tell a backend change from a scheduler change. Neither + enters an action identity (only :func:`tool_version` does): a change outside the + analyzer still reads the ledger back, and these hashes are what tells such + observations apart. ``git`` is the checkout's commit, else the ``CODE_REF.json`` a + code snapshot carries, else ``None``. Computed once per process. + """ + import evalrx + + return _code_version(Path(evalrx.__file__).parent) + + +def _code_version(root: Path) -> dict[str, Any]: + files = [] + for here, dirs, names in os.walk(root): + dirs[:] = [d for d in dirs if d not in ("__pycache__", "node_modules")] + files += [Path(here, n).relative_to(root) for n in names if n.endswith(".py")] + tree = hashlib.sha1() + parts: dict[str, Any] = {} + for rel in sorted(files): + data = (root / rel).read_bytes() + for h in (tree, parts.setdefault(rel.parent.as_posix(), hashlib.sha1())): + h.update(rel.as_posix().encode()) + h.update(data) + return {"tree": tree.hexdigest()[:12], "parts": {k: h.hexdigest()[:12] for k, h in sorted(parts.items())}, + "git": _git_ref(root.parent)} + + +def _git_ref(top: Path) -> "dict[str, Any] | None": + """``{"commit", "dirty"}`` when *top* is a checkout's root (dirty = tracked files under + ``evalrx`` differ from the commit), else what its ``CODE_REF.json`` says.""" + import subprocess + + def git(*args: str) -> str: + return subprocess.run(["git", "-C", str(top), *args], capture_output=True, text=True, + timeout=10, check=True).stdout.strip() + + try: + if Path(git("rev-parse", "--show-toplevel")).resolve() == top.resolve(): + return {"commit": git("rev-parse", "HEAD"), + "dirty": bool(git("status", "--porcelain", "--untracked-files=no", "--", "evalrx"))} + except (OSError, subprocess.SubprocessError): + pass + try: + return json.loads((top / "CODE_REF.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + +def code_label(code: "dict[str, Any] | None") -> str: + """The code line of a markdown report: the tree hash, plus the commit when known.""" + if not code: + return "code not recorded" + git = code.get("git") or {} + return (f"code tree `{code['tree']}`" + + (f", commit `{str(git['commit'])[:10]}`{' + uncommitted changes' if git.get('dirty') else ''}" + if git.get("commit") else ", commit unknown")) + + def output_cap(model_identity: dict[str, Any]) -> "int | None": """The generation cap the host set, per call or in the runtime (``None`` = unknown here).""" for generation in (model_identity.get("generation") or {}, model_identity.get("runtime_generation") or {}): @@ -542,6 +606,7 @@ def _run_part(self, step: PlanStep, target: "list[str]", ev: StepEvidence, base: self.ledger.trace({ **base, "event": "planned", "attempt": attempt, "action": action.to_dict(), "params": canonical(analyzer.get_params()), "tool_version": version, + "code": code_version()["tree"], "fidelity_check": step.fidelity_check, "reuse": step.reuse, "estimate_sec": estimate, **({"previous_attempts_uncertain": prior} if prior else {}), }) @@ -724,7 +789,8 @@ def manifest() -> None: # Every invocation's Stage 0 is spent compute (the runner does not cache # it), even when every action is then read back from an earlier run. n_prior = sum(1 for e in ledger.cost_events() if e.get("kind") == "stage0") - ledger.cost({"kind": "stage0", "shared": True, "invocation": n_prior + 1, **stage0_cost}) + ledger.cost({"kind": "stage0", "shared": True, "invocation": n_prior + 1, + "code": code_version()["tree"], **stage0_cost}) say(f"[triage] sample: {len(draw.fail_ids)} FAIL + {len(draw.pass_ids)} PASS " f"(stratum={stratum}, shortfall={draw.shortfall or 'none'})") @@ -1458,6 +1524,7 @@ def account() -> None: # what an exploration decision spent counts against its "explored": {a: round(v, 6) for a, v in explored.items()}, "min_gain": min_gain, "min_cover": min_cover} if scheduler in VALUE_SCHEDULERS else {}), "rules_version": RULES_VERSION, + "code": code_version(), "model": model_identity, "sample": draw.to_dict(), "settings": {"host_assumed_finish": host_assumed_finish, "answer_contract": answer_contract, @@ -1727,7 +1794,8 @@ def _markdown(report: dict[str, Any]) -> str: s = report["summary"] lines = [ f"# Triage report ({report['policy']}, {report['rules_version']})", "", - f"Model: `{report['model'].get('spec')}` on `{report['model'].get('backend')}`. " + f"Model: `{report['model'].get('spec')}` on `{report['model'].get('backend')}`; " + f"{code_label(report.get('code'))}. " f"Sample: {len(report['sample']['fail_ids'])} FAIL + {len(report['sample']['pass_ids'])} PASS, " f"stratum `{report['sample']['stratum_rule']}`, shortfall {report['sample']['shortfall'] or 'none'}. " f"Stopped: {report['stop']['reason']}" diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py index 986c718a..4c5ec195 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/probing/validation.py @@ -552,7 +552,13 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili battery: "tuple[PlanStep, ...] | None" = None, layers: "tuple[Layer, ...]" = LAYERS, run_logger: Any = None, progress: "Callable[[str], None] | None" = print) -> dict[str, Any]: """Validate the union of the arms' frozen *families* once on *validation*; credit every arm.""" - from evalrx.eval_agent.probing.controller import BATTERY, POLICY_VERSION, _Run, analyzer_extras + from evalrx.eval_agent.probing.controller import ( + BATTERY, + POLICY_VERSION, + _Run, + analyzer_extras, + code_version, + ) battery = battery or BATTERY stale = sorted(arm for arm, r in reports.items() if r.get("rules_version") != RULES_VERSION) @@ -674,6 +680,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili curve = supported_curve(frozen["arms"], {i: r["verdict"] for i, r in results.items()}, links) report = { "version": VALIDATION_VERSION, "frozen_sha1": frozen["sha1"], "alpha": ALPHA, "k": k, "level": level, + "code": code_version(), "partition": frozen["partition"], "sample": draw.to_dict(), "issues": [{**i.to_dict(), "plan": next(p for p in plan if p["issue_id"] == i.issue_id), @@ -760,8 +767,10 @@ def _check_explanations(explanations: dict[str, list[dict[str, Any]]], run: Any, def markdown(report: dict[str, Any]) -> str: + from evalrx.eval_agent.probing.controller import code_label + part = report.get("partition") or {} - lines = [f"# Diagnostic validation ({report['version']})", "", + lines = [f"# Diagnostic validation ({report['version']}; {code_label(report.get('code'))})", "", f"Frozen family sha1 `{report['frozen_sha1']}`: {report['k']} issue(s), intervals at " f"{report['level']:.4f} (one-sided Bonferroni, alpha {report['alpha']}).", f"Partition: {part.get('rule', '-')}; {len(part.get('validation_ids') or [])} validation cases " diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index 8cf2e8cc..9c3337dd 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -625,6 +625,50 @@ def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch assert _steps(second)["attention_knockout"]["action_id"] != _steps(first)["attention_knockout"]["action_id"] +def test_mvp0_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vlm_cases, monkeypatch): + from evalrx.eval_agent.probing import controller + from tests.tiny_whitebox import TinyVLM + + model = TinyVLM("qwen2_5_vl") + kw = dict(out_dir=tmp_path / "c", model_identity={"spec": "tiny"}, n_fail=2, + stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) + first = run_triage(model, vlm_cases, **kw) + code = controller.code_version() + assert first["code"] == code and "eval_agent/probing" in code["parts"] + out = tmp_path / "c" + planned = [json.loads(line) for line in (out / "selection_trace.jsonl").read_text().splitlines() + if '"planned"' in line] + assert planned and all(e["code"] == code["tree"] for e in planned) + assert f"code tree `{code['tree']}`" in (out / "triage_report.md").read_text() + # other code (a backend, the scheduler) changed: the ledger is still read back, the new tree recorded + monkeypatch.setattr(controller, "code_version", lambda: {**code, "tree": "000000000000"}) + second = run_triage(model, vlm_cases, **kw) + assert not _rerun(second) and second["code"]["tree"] == "000000000000" + costs = [json.loads(line) for line in (out / "cost_ledger.jsonl").read_text().splitlines()] + assert [c["code"] for c in costs if c["kind"] == "stage0"] == [code["tree"], "000000000000"] + + +def test_code_version_hashes_per_package_directory_and_reads_a_snapshot_ref(tmp_path): + from evalrx.eval_agent.probing.controller import _code_version, code_label + + root = tmp_path / "evalrx" + for rel, text in {"__init__.py": "", "models/hf.py": "a = 1\n", "eval_agent/probing/rules.py": "b = 2\n", + "reporting/web/node_modules/gyp/x.py": "", "models/__pycache__/hf.py": ""}.items(): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(text) + first = _code_version(root) + assert sorted(first["parts"]) == [".", "eval_agent/probing", "models"] + assert first["git"] is None and code_label(first).endswith("commit unknown") + (root / "models" / "hf.py").write_text("a = 3\n") + (tmp_path / "CODE_REF.json").write_text('{"commit": "0123456789abcdef", "dirty": true}') + second = _code_version(root) + assert second["tree"] != first["tree"] and second["parts"]["models"] != first["parts"]["models"] + assert second["parts"]["eval_agent/probing"] == first["parts"]["eval_agent/probing"] + assert second["git"] == {"commit": "0123456789abcdef", "dirty": True} + assert code_label(second) == f"code tree `{second['tree']}`, commit `0123456789` + uncommitted changes" + assert code_label(None) == "code not recorded" + + def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): from evalrx.eval_agent.probing.ledger import Ledger from tests.tiny_whitebox import TinyVLM diff --git a/tests/test_eval_agent/test_probing_validation.py b/tests/test_eval_agent/test_probing_validation.py index 4b951c31..3b6d59b5 100644 --- a/tests/test_eval_agent/test_probing_validation.py +++ b/tests/test_eval_agent/test_probing_validation.py @@ -196,6 +196,12 @@ def test_an_effect_that_holds_on_new_cases_is_supported_and_frozen_before_valida assert set(out["sample"]["case_ids"]) <= val_ids assert (tmp_path / "validation" / "selection_trace.jsonl").is_file() assert "## Arms" in (tmp_path / "validation" / "validation_report.md").read_text() + # both reports and every planned action say which code ran + from evalrx.eval_agent.probing.controller import code_version + + assert out["code"] == report["code"] == code_version() + assert all(e["code"] == out["code"]["tree"] for e in planned) + assert f"code tree `{out['code']['tree']}`" in (tmp_path / "validation" / "validation_report.md").read_text() def test_an_effect_that_held_only_on_the_discovery_cases_is_refuted(tmp_path, wrapper_on_s): From b1841407945522f4bf0b91cc5480af1d0f196194 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:45:46 -0700 Subject: [PATCH 19/26] triage: steps that compare answers do not run where outputs commit to none On a task whose outputs commit to no categorical answer (open captions: CHAIR, where answer_key gives None) the two U steps of the battery still ran, and every U reading came back untested ("the task has no categorical answer to compare"). U untested kept every FAIL case out of S, so they all landed in X; and the 0.8B CHAIR smoke measured those two steps at about three quarters of the battery's time (512-token captions re-sampled five times and re-asked in three wrappers). PlanStep.needs_answer marks a step whose readings compare the answers outputs commit to: the battery's self_consistency, prompt_reword and prompt_threshold, and the follow-ups describe_first, self_consistency_n10 and format_sensitivity. _Run.inapplicable() is the one place that says why a step has no meaning on a task (other task kinds, or needs_answer where the outputs commit to none), used by gate(), run_step() and the two expansion filters that tested task_kinds inline. triage.commits_to_answers() decides it on the Stage-0 outputs (no model call); run_triage and validate pass it in. In the records U is then not_applicable (both parts, same shape), like N on a case without media: it neither fires nor counts as missing, so S needs H and N alone there. Tasks with an answer key behave as before; no action identity changes (PlanStep fields are not part of it), so existing ledgers read back. Tests: the records (U not applicable, the fully checked FAIL case is S; with a key and no U observations it stays X) and a run on an unkeyed task (the three battery steps not applicable, never executed). Full suite 2838 passed / 16 skipped; ruff clean. --- evalrx/eval_agent/probing/actions.py | 5 +++ evalrx/eval_agent/probing/controller.py | 38 ++++++++++++++------ evalrx/eval_agent/probing/rules.py | 6 ++-- evalrx/eval_agent/probing/triage.py | 19 ++++++++-- evalrx/eval_agent/probing/validation.py | 4 ++- tests/test_eval_agent/test_probing_mvp0.py | 41 ++++++++++++++++++++++ 6 files changed, 96 insertions(+), 17 deletions(-) diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/probing/actions.py index 3c9a5553..2014c5fe 100644 --- a/evalrx/eval_agent/probing/actions.py +++ b/evalrx/eval_agent/probing/actions.py @@ -85,6 +85,10 @@ class PlanStep: ``min_output_tokens``: the step asks for text before the answer (e.g. a description), so a known output cap below this leaves it nothing to read. + ``needs_answer``: the step's readings compare the answers outputs commit to + (the task's answer key), so it is not applicable on a task whose outputs + commit to none (open captions). + ``deferred``: a battery step no route reads (a descriptive reading): the rules run it once the sample has settled, and the scored scheduler takes it as a candidate of the layer it serves instead of running it up front. @@ -108,6 +112,7 @@ class PlanStep: reuse_note: str = "" caveat: str = "" min_output_tokens: int = 0 + needs_answer: bool = False deferred: bool = False evidence: str = "" diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 3d4cacd9..97dc7ef7 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -11,6 +11,8 @@ 4. ``attention_knockout(target="prediction")``: the first N-layer measurement. 5. ``self_consistency``: re-samples each case (U). 6. ``prompt_contrast`` with the question kept verbatim in neutral wrappers (U). + Both compare answers, so neither runs on a task whose outputs commit to + no categorical answer (open captions): U is not applicable there. 7. ``prompt_contrast`` with an instruction not to default to "no" (yes/no tasks only), descriptive S. 8. ``embed_lens(layer=0.9)``: is the case's own question word near the @@ -144,6 +146,7 @@ ) from evalrx.eval_agent.probing.triage import ( ROUTE_STEPS, + commits_to_answers, follow_up_reading, follow_up_values, summarize, @@ -201,16 +204,17 @@ PlanStep("self_consistency", {"n": 5}, "U", "re-sample each case at the host's frozen sampling settings; another answer sampled " "more often than the Stage-0 answer is the U signal", - calls_per_case={"generate": 5}, per_case=True, keep_artifacts=("samples",)), + calls_per_case={"generate": 5}, per_case=True, keep_artifacts=("samples",), needs_answer=True), PlanStep("prompt_contrast", {"strategies": REWORD_STRATEGIES}, "U", "re-ask with the question verbatim inside two neutral wrappers; an answer that " "moves is the U signal", - calls_per_case={"generate": 3}, key="prompt_reword", keep_artifacts=("outputs",)), + calls_per_case={"generate": 3}, key="prompt_reword", keep_artifacts=("outputs",), + needs_answer=True), PlanStep("prompt_contrast", {"strategies": THRESHOLD_STRATEGIES}, "S", "re-ask with an instruction not to default to a negative answer: which errors move, " "and which correct answers it breaks", calls_per_case={"generate": 2}, key="prompt_threshold", keep_artifacts=("outputs",), - task_kinds=("yes_no",)), + task_kinds=("yes_no",), needs_answer=True), PlanStep("embed_lens", {"layer": 0.9}, "S2", "nearest vocabulary words of the media tokens late in the stack: how close the " "case's own question word gets", @@ -349,8 +353,10 @@ class _Run: def __init__(self, model: Any, explore: "CaseBatch", ledger: Ledger, *, context: dict[str, Any], extras: dict[str, dict[str, Any]], task_kind: "str | None", budget_sec: float, price_fn: Any, run_logger: Any, say: Callable[[str], None], - per_call_generation: bool = True, budget_usd: float = 0.0, chunk: int = 0) -> None: + per_call_generation: bool = True, budget_usd: float = 0.0, chunk: int = 0, + answer_keyed: bool = True) -> None: self.model, self.ledger, self.context, self.extras = model, ledger, context, extras + self.answer_keyed = answer_keyed # the task's outputs commit to a categorical answer self.per_call_generation, self.budget_usd, self.chunk = per_call_generation, budget_usd, chunk self.task_kind, self.budget_sec, self.price_fn, self.run_logger, self.say = ( task_kind, budget_sec, price_fn, run_logger, say) @@ -384,10 +390,19 @@ def build(self, step: PlanStep) -> Any: return registry.analyzers.get(step.analyzer)(**self.config(step)) + def inapplicable(self, step: PlanStep) -> "str | None": + """Why *step* has no meaning on this task (``None``: it has one).""" + if step.task_kinds and self.task_kind not in step.task_kinds: + return f"for task kinds {list(step.task_kinds)}; this task is {self.task_kind!r}" + if step.needs_answer and not self.answer_keyed: + return "for tasks whose outputs commit to a categorical answer; this task's do not" + return None + def gate(self, step: PlanStep, ids: "list[str]") -> "tuple[str, str] | None": """Why *step* cannot run on *ids* here — ``(status, reason)`` — before anything is spent.""" - if step.task_kinds and self.task_kind not in step.task_kinds: - return "not_applicable", f"for task kinds {list(step.task_kinds)}; this task is {self.task_kind!r}" + why = self.inapplicable(step) + if why is not None: + return "not_applicable", why cap = self.output_cap(step) if step.min_output_tokens and cap is not None and cap < step.min_output_tokens: return "not_applicable", (f"the output cap of {cap} tokens is below the {step.min_output_tokens} " @@ -518,10 +533,11 @@ def run_step(self, step: PlanStep, target: "list[str]", *, kind: str, revision: ev = self.evidence.setdefault(step.name, StepEvidence(step)) base = {"kind": kind, "revision": revision, "key": step.name, "analyzer": step.analyzer, "rule_id": rule_id, "route": route} - if step.task_kinds and self.task_kind not in step.task_kinds: + why = self.inapplicable(step) + if why is not None: if any(e["key"] == step.name and e["status"] == "not_applicable" for e in self.executions): return None - reason = f"step is for task kinds {list(step.task_kinds)}; this task is {self.task_kind!r}" + reason = f"step is {why}" self.ledger.trace({**base, "event": "not_applicable", "reason": reason}) record = {**base, "status": "not_applicable", "reused": False, "reason": reason} self._log(record) @@ -769,7 +785,7 @@ def run_triage( run = _Run(model, explore, ledger, context={"policy": POLICY_VERSION, "model": model_identity}, extras=extras, task_kind=task_kind, budget_sec=budget_sec, price_fn=price_fn, run_logger=run_logger, say=say, per_call_generation=per_call_generation, budget_usd=budget_usd, - chunk=chunk) + chunk=chunk, answer_keyed=commits_to_answers(explore, answer_fn)) rank_of = partial(rank, seed) triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn, agree_fn=agree_fn, @@ -842,7 +858,7 @@ def expansion_plan() -> "tuple[Any, Any, list[str], float | None] | None": raise RuntimeError("nested sampler returned a draw that does not contain the previous one") new_ids = [cid for cid in bigger_draw.case_ids if cid not in set(draw.case_ids)] estimates = [run.estimate_sec(s, len(new_ids) if s.reuse else len(bigger_draw.case_ids)) - for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] + for s in immediate if run.inapplicable(s) is None] estimate = round(sum(e for e in estimates if e is not None), 1) if any( e is not None for e in estimates) else None return bigger, bigger_draw, new_ids, estimate @@ -1312,7 +1328,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], expansion_note = not_possible(gaps) decide({"kind": "expand_not_possible", "rule_id": "E1", **expansion_note}) else: - steps = [s for s in immediate if not (s.task_kinds and task_kind not in s.task_kinds)] + steps = [s for s in immediate if run.inapplicable(s) is None] qs = [availability(s.analyzer, run.evidence) for s in steps if any(o.status != "unsupported" for o in run.evidence[s.name].chunks)] costs = [step_cost(s, len(plan[2]), run.evidence, axis)[0] for s in steps] diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/probing/rules.py index 6f9cba70..a4822ca4 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/probing/rules.py @@ -72,7 +72,7 @@ def _describe(route: str, question: str) -> PlanStep: "gen_kwargs": {"max_new_tokens": DESCRIBE_OUTPUT_TOKENS}}, route, question, key="describe_first", calls_per_case={"generate": 2}, keep_artifacts=("outputs",), caveat="the runtime's output cap must leave room for the description", - min_output_tokens=128) + min_output_tokens=128, needs_answer=True) @dataclass(frozen=True) @@ -117,10 +117,10 @@ class Layer: calls_per_case={"logprobs": 1}, per_case=True, evidence=TOKEN_PROBABILITIES), PlanStep("self_consistency", {"n": 10}, "U1", "twice the samples: how often the answer moves", key="self_consistency_n10", calls_per_case={"generate": 10}, per_case=True, - keep_artifacts=("samples",), evidence=RESAMPLING))), + keep_artifacts=("samples",), evidence=RESAMPLING, needs_answer=True))), Layer("U2", "U", "with the options rotated, does the answer follow content or position", ( PlanStep("format_sensitivity", {}, "U2", "rotate the options", calls_per_case={"generate": 3}, - task_kinds=("multiple_choice_letter",)),)), + task_kinds=("multiple_choice_letter",), needs_answer=True),)), Layer("Sb", "S", "does a stable error survive when the model first states what it sees", ( _describe("Sb", "describe the media, then answer"),)), Layer("S1", "S", "which image regions the answer margin depends on (no reference regions: " diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index df423859..c60d1d7f 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -22,9 +22,12 @@ control, not an unstable answer). Answers are compared by the task's answer key under its agreement rule (two numbers within the task's tolerance of each other are one answer, as its grader would hold), never graded against the - gold. Any readable answer that differs fires U. + gold. Any readable answer that differs fires U. On a task whose outputs + commit to no categorical answer (open captions) U is not applicable: there + is no answer to compare, and its two steps do not run. * **S** (a stable failure): a FAIL case on which every required check ran and - none fired — H, N (cases with media) and both U parts. S is an + none fired — H, N (cases with media) and both U parts (tasks whose outputs + commit to an answer). S is an investigation route, not a cause; the S readings attached to every case (the threshold instruction, the question word on the media tokens, how early the model's own answer was readable) are descriptive. @@ -82,6 +85,14 @@ def default_answer(case: Any, text: str) -> str: return _norm_answer(str(text or "")) +def commits_to_answers(cases: Any, answer_fn: "AnswerFn | None") -> bool: + """Whether the task's outputs commit to a categorical answer: *answer_fn* gives ``None`` on a task + with none (open captions), whatever the output. Read off the Stage-0 outputs, no model call.""" + answer = answer_fn or default_answer + cases = list(cases) + return not cases or any(answer(c, str(getattr(c, "observed", "") or "")) is not None for c in cases) + + def exact_answer(case: Any, candidate: str, reference: str) -> bool: """Agreement rule when the host gives none: the keys are equal.""" return candidate == reference @@ -309,6 +320,10 @@ def _u_reword(obs: "Observation | None", case: Any, answer_fn: AnswerFn, agree_f def _u_check(sampling: "Observation | None", reword: "Observation | None", case: Any, answer_fn: AnswerFn, agree_fn: AgreeFn) -> dict[str, Any]: """U fires when either part fires; it is clear only when both parts ran and are clear.""" + if answer_fn(case, str(getattr(case, "observed", "") or "")) is None: + why = "the task has no categorical answer to compare" + return {"state": NOT_APPLICABLE, "reason": why, + "parts": [{"part": part, "state": NOT_APPLICABLE, "reason": why} for part in ("sampling", "reword")]} parts = [_u_sampling(sampling, case, answer_fn, agree_fn), _u_reword(reword, case, answer_fn, agree_fn)] states = [p["state"] for p in parts] state = FIRED if FIRED in states else CLEAR if all(st == CLEAR for st in states) else UNTESTED diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py index 4c5ec195..a1284e87 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/probing/validation.py @@ -106,6 +106,7 @@ from evalrx.eval_agent.probing.sampler import matched_sample, rank from evalrx.eval_agent.probing.triage import ( ROUTE_STEPS, + commits_to_answers, difference_interval, follow_up_values, triage_cases, @@ -602,7 +603,8 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili run = _Run(model, validation, Ledger(out), context={"policy": POLICY_VERSION, "model": model_identity, "role": "validation"}, extras=extras, task_kind=task_kind, budget_sec=budget_sec, price_fn=price_fn, - run_logger=run_logger, say=say, per_call_generation=per_call_generation, chunk=chunk) + run_logger=run_logger, say=say, per_call_generation=per_call_generation, chunk=chunk, + answer_keyed=commits_to_answers(validation, answer_fn)) n_fail = sum(1 for c in validation if getattr(getattr(c, "label", None), "value", None) == "fail") sample, draw = matched_sample(validation, n_fail, seed=seed, stratum=stratum) for step in battery: diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index 9c3337dd..93462a17 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -255,6 +255,31 @@ def test_few_answer_tasks_test_n_only_with_counterfactual_donors(): assert donors["fail"]["counterfactual_followed_donor"] == 1 and donors["pass"]["content"] == 1 +def _no_answer(case, output): + """The answer key of a task whose outputs commit to no categorical answer (open captions).""" + return None + + +def test_u_is_not_applicable_where_outputs_commit_to_no_answer_and_s_needs_h_and_n(): + from evalrx.eval_agent.probing.triage import commits_to_answers + + cases = CaseBatch([ + _yn_case("s", Label.FAIL, "Yes", "A cat on a sofa."), # H and N clear: S without U + _yn_case("p", Label.PASS, "Yes", "A dog on a rug."), # a stable control + ]) + obs = _clean_h_and_n([c.id for c in cases], {"s": "No", "p": "No"}) + assert not commits_to_answers(cases, _no_answer) and commits_to_answers(cases, None) + kw = dict(host_assumed_finish=True, answer_contract=False, n_needs_counterfactual=False) + recs = {r["case_id"]: r for r in triage_cases(cases, obs, answer_fn=_no_answer, **kw)} + assert recs["s"]["U"]["state"] == "not_applicable" + assert [(u["part"], u["state"]) for u in recs["s"]["U"]["parts"]] == [("sampling", "not_applicable"), + ("reword", "not_applicable")] + assert recs["s"]["routes"] == ["S"] and recs["s"]["stable"] and recs["p"]["stable"] + # with an answer key and no U observations, U is untested and the case is X + keyed = {r["case_id"]: r for r in triage_cases(cases, obs, **kw)} + assert keyed["s"]["U"]["state"] == "untested" and keyed["s"]["routes"] == ["X"] + + def test_open_answer_records_match_controls_without_the_gold_answer(): from evalrx.eval_agent.probing.rules import matched_controls @@ -648,6 +673,22 @@ def test_mvp0_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vl assert [c["code"] for c in costs if c["kind"] == "stage0"] == [code["tree"], "000000000000"] +def test_mvp0_steps_that_compare_answers_do_not_run_where_outputs_commit_to_none(tmp_path, vlm_cases): + from tests.tiny_whitebox import TinyVLM + + model = TinyVLM("qwen2_5_vl") + report = run_triage(model, vlm_cases, out_dir=tmp_path / "cap", model_identity={"spec": "tiny"}, n_fail=2, + task_kind="chair_caption", answer_fn=_no_answer, progress=None, + analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}) + steps = _steps(report) + for key in ("self_consistency", "prompt_reword", "prompt_threshold"): + assert steps[key]["status"] == "not_applicable" and "cost" not in steps[key] + assert steps["self_consistency"]["reason"] == ("step is for tasks whose outputs commit to a categorical " + "answer; this task's do not") + assert steps["modality_ablation"]["status"] == steps["attention_knockout"]["status"] == OK + assert {r["U"]["state"] for r in report["cases"]} == {"not_applicable"} + + def test_code_version_hashes_per_package_directory_and_reads_a_snapshot_ref(tmp_path): from evalrx.eval_agent.probing.controller import _code_version, code_label From d59b0e11cf9f0e6fe4f60498da14d6e29ee6df25 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:59:19 -0700 Subject: [PATCH 20/26] triage: a swap tests N only with a counterfactual donor on few-answer tasks too N fires when the answer survives a media swap. On yes/no and letter tasks a swap to unrelated media often leaves the right answer unchanged, so there N counts only a counterfactual donor (the same question on other media, gold different from the model's answer) and a content-only swap leaves it untested. Spatial457 (exact_or_numeric) was not treated that way, though its 1837 L5 questions have 39 answers (small/large, 2/3, colours) and no question is asked twice: every donor was content-only, and N fired on PASS cases as often as on FAIL cases (mem1, 10-27: 0.8B 9/37 PASS vs 27/92 FAIL, 2B 14/38 vs 21/91; routing signal about 0). Task.few_answers declares a small closed answer set beyond yes/no and letters; Spatial457 sets it, and runner._needs_counterfactual() is the one rule for n_needs_counterfactual (discovery and validation alike). On Spatial457 N is now untested, so its FAIL cases go to U or X, not N or S. No action identity changes: the swap itself is the same, only its reading is. Tests: pope_adversarial and spatial457 need a counterfactual donor, chartqa does not. Analysis, eval_agent and datasets suites pass; ruff clean. --- evalrx/benchmark/runner.py | 9 ++++++++- evalrx/benchmark/tasks/base.py | 3 +++ evalrx/benchmark/tasks/spatial457.py | 1 + tests/test_analysis/test_run_cli.py | 8 ++++++++ 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index ebed2018..4233c9a9 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -436,6 +436,13 @@ def _validation_source(args, task: T.Task, model, gen_kwargs: dict, protocol, ru return source, manifest +def _needs_counterfactual(task: T.Task) -> bool: + """Whether a triage swap tests N only with a counterfactual donor (the same question on other media, + gold different from the model's answer): tasks whose answers come from a few values, where an + unchanged answer on unrelated media may simply be right.""" + return task.kind in ("yes_no", "multiple_choice_letter") or task.few_answers + + def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, cases, ctx, run_dir: Path, baseline: dict, source=None) -> int: """``--m1-policy triage_active``: the triage battery, rule-chosen expansions and @@ -497,7 +504,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: shared = dict(seed=args.triage_seed, stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), - n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), + n_needs_counterfactual=_needs_counterfactual(task), task_kind=task.kind, answer_fn=T.answer_key, agree_fn=T.same_answer, analyzer_kwargs=extras, price_fn=_price_fn(spec), per_call_generation=sampling is not None, chunk=int(args.triage_chunk)) report = run_triage( diff --git a/evalrx/benchmark/tasks/base.py b/evalrx/benchmark/tasks/base.py index b20ed7d8..b2792a17 100644 --- a/evalrx/benchmark/tasks/base.py +++ b/evalrx/benchmark/tasks/base.py @@ -38,6 +38,9 @@ class Task: max_new_tokens: int = 64 output_contract: dict | None = None # copied into protocol + case metadata when set short_answer: bool = True # terse EOS answers: mark finish_reason="stop" + few_answers: bool = False # answers from a small closed set (beyond yes/no and letters): + # an unchanged answer on unrelated media may be right, so a + # triage swap tests N only with a counterfactual donor source: str = "" # citation / hub id for the README matrix diff --git a/evalrx/benchmark/tasks/spatial457.py b/evalrx/benchmark/tasks/spatial457.py index d376e13e..84c7e967 100644 --- a/evalrx/benchmark/tasks/spatial457.py +++ b/evalrx/benchmark/tasks/spatial457.py @@ -95,5 +95,6 @@ def protocol(model_label: str): download=download, protocol=protocol, pinned_m1=("answer_extraction_audit", "selfcheck_consistency", "coverage_verification_gap"), default_limit=256, val_limit=128, default_seed=457, max_new_tokens=64, + few_answers=True, # 39 answers over 1837 questions (small/large, 2/3, colours); no question asked twice source="RyanWW/Spatial457 (L5_6d_spatial)", ) diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index df886647..c450e791 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -192,6 +192,14 @@ def build(args): runner._triage_explainer(same, spec) +def test_triage_n_needs_a_counterfactual_donor_where_answers_are_few(): + from evalrx.benchmark import tasks as T + + assert runner._needs_counterfactual(T.get("pope_adversarial")) # yes/no + assert runner._needs_counterfactual(T.get("spatial457")) # 39 attribute values, no question twice + assert not runner._needs_counterfactual(T.get("chartqa")) # open answers: other media changes them + + def test_triage_weights_and_exploration_share_parse_and_are_checked(): from evalrx.benchmark.run import main as run_main from evalrx.benchmark.run import triage_weights From f0ed76eed25b456b29cd2dee5de875a401e6316f Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:30:09 -0700 Subject: [PATCH 21/26] triage: a content-only swap does not test N where the answer is a common gold d59b0e1 made N need a counterfactual donor on tasks declared few-answer (Task.few_answers, set on Spatial457 alone). The trouble is per answer, not per dataset: an unchanged answer after a swap to unrelated media is no N evidence when that answer is often right anyway, and ChartQA has such cases too (yes/no and small counts, 12% of the triage pool), while 23% of Spatial457's cases have rare answers a swap still tests. triage.common_answers() takes the golds (as answer keys) at least COMMON_ANSWER_SHARE = 2% of DISCOVERY has, with their shares; never an output. _n_check leaves N untested on a content-only swap when the model's answer agrees (the task's agree_fn) with one of them, says so, and records the match (common_answer). run_triage and validate both read the common answers off DISCOVERY; the triage report keeps them in settings. Yes/no and letter tasks still need a counterfactual donor for every case. The task flag and runner._needs_counterfactual are removed; no action identity changes. On the finished mem1 cells (offline, from their reports) the rule moves N to untested on 60/129 (0.8B) and 77/129 (2B) Spatial457 cases and on 11/64 and 25/256 ChartQA cases, and it removes every N fire on a Spatial457 PASS case (9 and 14): those were the answers that are right on most media anyway. Tests: common_answers' shares and threshold ({} with no answer key); a content swap leaves N untested on a common answer and fires on a rare one. Full suite 2840 passed / 16 skipped; ruff clean. --- evalrx/benchmark/runner.py | 9 +--- evalrx/benchmark/tasks/base.py | 3 -- evalrx/benchmark/tasks/spatial457.py | 1 - evalrx/eval_agent/probing/controller.py | 7 ++- evalrx/eval_agent/probing/triage.py | 50 ++++++++++++++++++++-- evalrx/eval_agent/probing/validation.py | 4 +- tests/test_analysis/test_run_cli.py | 8 ---- tests/test_eval_agent/test_probing_mvp0.py | 32 ++++++++++++++ 8 files changed, 88 insertions(+), 26 deletions(-) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 4233c9a9..ebed2018 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -436,13 +436,6 @@ def _validation_source(args, task: T.Task, model, gen_kwargs: dict, protocol, ru return source, manifest -def _needs_counterfactual(task: T.Task) -> bool: - """Whether a triage swap tests N only with a counterfactual donor (the same question on other media, - gold different from the model's answer): tasks whose answers come from a few values, where an - unchanged answer on unrelated media may simply be right.""" - return task.kind in ("yes_no", "multiple_choice_letter") or task.few_answers - - def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, cases, ctx, run_dir: Path, baseline: dict, source=None) -> int: """``--m1-policy triage_active``: the triage battery, rule-chosen expansions and @@ -504,7 +497,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: shared = dict(seed=args.triage_seed, stratum="gold" if task.kind in ("yes_no", "multiple_choice_letter") else "none", host_assumed_finish=bool(task.short_answer), answer_contract=bool(task.output_contract), - n_needs_counterfactual=_needs_counterfactual(task), + n_needs_counterfactual=task.kind in ("yes_no", "multiple_choice_letter"), task_kind=task.kind, answer_fn=T.answer_key, agree_fn=T.same_answer, analyzer_kwargs=extras, price_fn=_price_fn(spec), per_call_generation=sampling is not None, chunk=int(args.triage_chunk)) report = run_triage( diff --git a/evalrx/benchmark/tasks/base.py b/evalrx/benchmark/tasks/base.py index b2792a17..b20ed7d8 100644 --- a/evalrx/benchmark/tasks/base.py +++ b/evalrx/benchmark/tasks/base.py @@ -38,9 +38,6 @@ class Task: max_new_tokens: int = 64 output_contract: dict | None = None # copied into protocol + case metadata when set short_answer: bool = True # terse EOS answers: mark finish_reason="stop" - few_answers: bool = False # answers from a small closed set (beyond yes/no and letters): - # an unchanged answer on unrelated media may be right, so a - # triage swap tests N only with a counterfactual donor source: str = "" # citation / hub id for the README matrix diff --git a/evalrx/benchmark/tasks/spatial457.py b/evalrx/benchmark/tasks/spatial457.py index 84c7e967..d376e13e 100644 --- a/evalrx/benchmark/tasks/spatial457.py +++ b/evalrx/benchmark/tasks/spatial457.py @@ -95,6 +95,5 @@ def protocol(model_label: str): download=download, protocol=protocol, pinned_m1=("answer_extraction_audit", "selfcheck_consistency", "coverage_verification_gap"), default_limit=256, val_limit=128, default_seed=457, max_new_tokens=64, - few_answers=True, # 39 answers over 1837 questions (small/large, 2/3, colours); no question asked twice source="RyanWW/Spatial457 (L5_6d_spatial)", ) diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/probing/controller.py index 97dc7ef7..af163657 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/probing/controller.py @@ -147,6 +147,7 @@ from evalrx.eval_agent.probing.triage import ( ROUTE_STEPS, commits_to_answers, + common_answers, follow_up_reading, follow_up_values, summarize, @@ -712,7 +713,9 @@ def run_triage( answer_contract: the task declares an answer tag or output contract. n_needs_counterfactual: few-answer task (yes/no, letters): a swap only tests N with a counterfactual donor. Donors are drawn from the - whole of *explore*, never from outside it. + whole of *explore*, never from outside it. Elsewhere the + same holds per case for an answer that is a common gold + of *explore* (:func:`~.triage.common_answers`). task_kind: the task's kind; steps limited to other kinds are recorded as ``not_applicable`` and not run. answer_fn: ``(case, output) -> answer key`` (``""`` = no readable @@ -789,6 +792,7 @@ def run_triage( rank_of = partial(rank, seed) triage = partial(triage_cases, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, answer_fn=answer_fn, agree_fn=agree_fn, + common=common_answers(explore, answer_fn), stratum=stratum) sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) @@ -1545,6 +1549,7 @@ def account() -> None: # what an exploration decision spent counts against its "sample": draw.to_dict(), "settings": {"host_assumed_finish": host_assumed_finish, "answer_contract": answer_contract, "n_needs_counterfactual": n_needs_counterfactual, "budget_sec": budget_sec, + "common_answers": common_answers(explore, answer_fn), "task_kind": task_kind, "answer_fn": canonical(answer_fn), "agree_fn": canonical(agree_fn), "n_fail": n_fail, "max_fail": max_fail, "max_actions": max_actions, "min_route_fail": min_route_fail, diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/probing/triage.py index c60d1d7f..c6fcdd01 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/probing/triage.py @@ -14,6 +14,10 @@ swap with a non-empty baseline answer counts, and on few-answer tasks only a counterfactual donor (the same question's gold on that media differs from the model's answer); a content-only swap there, or a swap that fell back to drop, leaves N untested. + On other tasks a content-only swap counts unless the model's answer is a + common gold (:func:`common_answers`: at least 2% of DISCOVERY has it, as + yes/no or a small count does on ChartQA): on unrelated media such an answer + may well be right again, so N stays untested on that case. * **U** (an answer that moves): two parts, both required. ``self_consistency`` samples at the host's sampling settings against the Stage-0 answer (greedy settings leave it untested: identical samples are not a measurement), and @@ -93,6 +97,30 @@ def commits_to_answers(cases: Any, answer_fn: "AnswerFn | None") -> bool: return not cases or any(answer(c, str(getattr(c, "observed", "") or "")) is not None for c in cases) +#: A gold answer at least this share of DISCOVERY has is common: on unrelated media it may well be the +#: right answer again, so an unchanged one after a content-only swap is no N evidence. +COMMON_ANSWER_SHARE = 0.02 + + +def common_answers(cases: Any, answer_fn: "AnswerFn | None" = None, + share: float = COMMON_ANSWER_SHARE) -> dict[str, float]: + """The gold answers (as answer keys) that at least *share* of *cases* have, with their shares. + + Read off the cases' golds, never an output; ``{}`` on a task with no categorical answer. + """ + answer = answer_fn or default_answer + cases = list(cases) + keys: Counter = Counter() + for case in cases: + gold = (getattr(case, "metadata", None) or {}).get("gold", getattr(case, "expected", None)) + if isinstance(gold, (list, tuple)): + gold = gold[0] if gold else None + key = None if gold is None else answer(case, str(gold)) + if key: + keys[key] += 1 + return {k: round(n / len(cases), 4) for k, n in sorted(keys.items()) if n / len(cases) >= share} + + def exact_answer(case: Any, candidate: str, reference: str) -> bool: """Agreement rule when the host gives none: the keys are equal.""" return candidate == reference @@ -176,7 +204,9 @@ def _combine(fields: list[dict[str, Any]]) -> str: return UNTESTED -def _n_check(obs: "Observation | None", case: Any, needs_counterfactual: bool) -> dict[str, Any]: +def _n_check(obs: "Observation | None", case: Any, needs_counterfactual: bool, + common: "dict[str, float] | None" = None, answer_fn: "AnswerFn | None" = None, + agree_fn: "AgreeFn | None" = None) -> dict[str, Any]: cid = str(case.id) if not _has_media(case): return {"state": NOT_APPLICABLE, "reason": "the case has no media to swap"} @@ -192,6 +222,10 @@ def _n_check(obs: "Observation | None", case: Any, needs_counterfactual: bool) - out["base_answer"] = row.get("ablation_base_answer") if not str(out["base_answer"] or "").strip(): return {**out, "state": UNTESTED, "reason": "empty baseline answer; the comparison is not reliable"} + base_key = answer_fn(case, str(out["base_answer"])) if common and answer_fn else None + hit = next((g for g in common or {} if base_key and agree_fn(case, base_key, g)), None) + if hit is not None: + out["common_answer"] = {"answer": base_key, "gold": hit, "share": common[hit]} slots = [] for key in sorted(row): if not key.startswith("grounded_in_"): @@ -217,6 +251,11 @@ def _n_check(obs: "Observation | None", case: Any, needs_counterfactual: bool) - reason="no counterfactual donor in the partition (same question, different " "media, gold different from the model's answer); on a few-answer task " "an unchanged answer after a content-only swap may simply be correct") + elif hit is not None: + entry.update(state=UNTESTED, + reason=f"no counterfactual donor in the partition, and the model's answer is a " + f"common gold ({common[hit]:.1%} of DISCOVERY): an unchanged answer after a " + f"content-only swap may simply be correct") else: entry.update(state=FIRED if row[key] is False else CLEAR, assumption="open-answer task: different media is assumed to change the answer") @@ -379,7 +418,7 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence host_assumed_finish: bool, answer_contract: bool, n_needs_counterfactual: bool = False, answer_fn: "AnswerFn | None" = None, agree_fn: "AgreeFn | None" = None, - stratum: str = "gold") -> list[dict[str, Any]]: + stratum: str = "gold", common: "dict[str, float] | None" = None) -> list[dict[str, Any]]: """One record per case: label, stratum, every H/N/U check, routes, knockout and S readings. *observations* are keyed by plan step (``prompt_reword`` and @@ -390,7 +429,9 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence *n_needs_counterfactual* (few-answer tasks: yes/no, letters): a swap only tests N when its donor is a counterfactual — the same question's gold on that media differs from the model's answer — because a content-only swap there often leaves the - correct answer unchanged. + correct answer unchanged. *common* (:func:`common_answers` of DISCOVERY) does the + same per case elsewhere: a content-only swap does not test N on a case whose answer + is a common gold. *answer_fn* ``(case, output) -> key`` reads the answer an output commits to (``""``: none; ``None``: the task has no categorical answer); default @@ -432,7 +473,8 @@ def triage_cases(cases: Any, observations: "dict[str, Observation | StepEvidence "fields": h_fields, "disagreements": disagreements, } - n = _n_check(pick(observations, "modality_ablation", cid), case, n_needs_counterfactual) + n = _n_check(pick(observations, "modality_ablation", cid), case, n_needs_counterfactual, common, + answer, agree) u = _u_check(pick(observations, "self_consistency", cid), pick(observations, "prompt_reword", cid), case, answer, agree) label = getattr(getattr(case, "label", None), "value", None) diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/probing/validation.py index a1284e87..1d6c20cc 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/probing/validation.py @@ -107,6 +107,7 @@ from evalrx.eval_agent.probing.triage import ( ROUTE_STEPS, commits_to_answers, + common_answers, difference_interval, follow_up_values, triage_cases, @@ -612,7 +613,8 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili run.run_step(step, list(draw.case_ids), kind="validation", revision=0) records = triage_cases(sample, run.evidence, host_assumed_finish=host_assumed_finish, answer_contract=answer_contract, n_needs_counterfactual=n_needs_counterfactual, - answer_fn=answer_fn, agree_fn=agree_fn, stratum=stratum) + answer_fn=answer_fn, agree_fn=agree_fn, stratum=stratum, + common=common_answers(discovery, answer_fn)) rank_of = partial(rank, seed) by_rule = {x.rule_id: x for x in layers} steps = {s.name: s for s in (*battery, *candidate_steps(layers))} diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index c450e791..df886647 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -192,14 +192,6 @@ def build(args): runner._triage_explainer(same, spec) -def test_triage_n_needs_a_counterfactual_donor_where_answers_are_few(): - from evalrx.benchmark import tasks as T - - assert runner._needs_counterfactual(T.get("pope_adversarial")) # yes/no - assert runner._needs_counterfactual(T.get("spatial457")) # 39 attribute values, no question twice - assert not runner._needs_counterfactual(T.get("chartqa")) # open answers: other media changes them - - def test_triage_weights_and_exploration_share_parse_and_are_checked(): from evalrx.benchmark.run import main as run_main from evalrx.benchmark.run import triage_weights diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_probing_mvp0.py index 93462a17..df20527a 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_probing_mvp0.py @@ -280,6 +280,38 @@ def test_u_is_not_applicable_where_outputs_commit_to_no_answer_and_s_needs_h_and assert keyed["s"]["U"]["state"] == "untested" and keyed["s"]["routes"] == ["X"] +def test_common_answers_are_the_golds_a_share_of_discovery_has(): + from evalrx.eval_agent.probing.triage import common_answers + + golds = ["small"] * 3 + ["large"] * 2 + [f"x{i}" for i in range(95)] + cases = CaseBatch([FailureCase(id=f"c{i}", inputs=Inputs(prompt="q"), expected=g, observed=g, label=Label.PASS) + for i, g in enumerate(golds)]) + assert common_answers(cases) == {"large": 0.02, "small": 0.03} + assert common_answers(cases, share=0.025) == {"small": 0.03} + assert common_answers(cases, _no_answer) == {} + + +def test_a_content_swap_does_not_test_n_where_the_answer_is_a_common_gold(): + cases = CaseBatch([ + FailureCase(id="c", inputs=Inputs(prompt="What size is it?", image="c.png"), expected="large", + observed="small", label=Label.FAIL), + FailureCase(id="r", inputs=Inputs(prompt="How many are there?", image="r.png"), expected="7", + observed="5", label=Label.FAIL), + ]) + swap = _obs("modality_ablation", [ + {"sample_id": i, "ablation_base_answer": a, "grounded_in_image": False, "ablation_image_is_swap": True, + "ablation_image_donor": "d", "ablation_image_answer": a, "ablation_image_donor_kind": "content"} + for i, a in (("c", "small"), ("r", "5"))], params={"mode": "swap"}) + kw = dict(host_assumed_finish=True, answer_contract=False, stratum="none") + recs = {r["case_id"]: r for r in triage_cases(cases, {"modality_ablation": swap}, common={"small": 0.16}, **kw)} + # "small" survived other media, but it is the gold of 16% of DISCOVERY: it may simply be right there + assert recs["c"]["N"]["state"] == "untested" and "common gold (16.0% of DISCOVERY)" in recs["c"]["N"]["reason"] + assert recs["c"]["N"]["common_answer"] == {"answer": "small", "gold": "small", "share": 0.16} + assert recs["r"]["N"]["state"] == "fired" # a rare answer that survived other media + before = {r["case_id"]: r for r in triage_cases(cases, {"modality_ablation": swap}, **kw)} + assert before["c"]["N"]["state"] == before["r"]["N"]["state"] == "fired" + + def test_open_answer_records_match_controls_without_the_gold_answer(): from evalrx.eval_agent.probing.rules import matched_controls From fd9c5d6f7720c0c4eda2a4a578417db995efcd5d Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:23:32 -0700 Subject: [PATCH 22/26] Sample when a call names a temperature on a model deployed greedy The local backends merge a call's kwargs over RuntimeConfig.sampling key by key. A greedy benchmark cell deploys do_sample=False, so a re-sampling probe that asked for temperature=1.0 kept it and drew the greedy answer every time: self_consistency returned five identical samples on every case, and the triage's re-sampling check could not fire. A call that names a temperature and no do_sample is now read by its temperature alone (backends.base.call_sampling; hf_local, jax_local, vllm_offline). A call that names neither keeps the deployed decoding. --- CHANGELOG.md | 12 ++++++++++++ evalrx/models/backends/base.py | 15 +++++++++++++++ evalrx/models/backends/hf/model.py | 4 ++-- evalrx/models/backends/jax/backend.py | 4 ++-- evalrx/models/backends/vllm_offline.py | 4 ++-- tests/test_models/test_jax_local.py | 4 ++++ tests/test_models/test_wrap.py | 20 ++++++++++++++++++++ 7 files changed, 57 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b10d311c..42ed20a4 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -514,6 +514,18 @@ bookkeeping in one `evalrx.eval_agent.policy.RunState` (the agentic - `evalrx.agent_runtime.json_shape.validate_json_shape`: output models validate with pydantic. +### Fixed — a re-sampling probe ran greedy on a model deployed greedy + +Since the local backends apply the deployed decoding (`RuntimeConfig.sampling`) to +every call, a benchmark cell with greedy Stage 0 deploys `do_sample=False`, and a call +that asked for `temperature=1.0` kept it: `self_consistency` and +`coverage_verification_gap` drew the greedy answer every time (Qwen3.5-2B on ChartQA's +machine questions: five identical samples on each of 112 cases, where 14 of the 32 +measured before the backends changed had varied), so the triage's re-sampling check +never fired and M1 read every case as fully consistent. A call that names a temperature and no `do_sample` is now read by its +temperature alone (`backends.base.call_sampling`, used by `hf_local`, `jax_local` and +`vllm_offline`); a call that names neither keeps the deployed decoding. + ### Changed — probing after the 0.2.0 reorganisation and the batch calls The triage follows the package's new layout (`loop.partition.split_cases` for the diff --git a/evalrx/models/backends/base.py b/evalrx/models/backends/base.py index 2ce36553..2973cf01 100755 --- a/evalrx/models/backends/base.py +++ b/evalrx/models/backends/base.py @@ -21,6 +21,21 @@ from evalrx.core.spec import ModelSpec +def call_sampling(deployed: dict[str, Any], call: dict[str, Any]) -> dict[str, Any]: + """The decoding of one generate call: its own kwargs over the deployed ones. + + ``do_sample`` and ``temperature`` say one thing between them. A call that + names a temperature and no ``do_sample`` is read by its temperature alone: + a re-sampling probe at ``temperature=1.0`` samples on a model deployed + greedy (``do_sample=False``), where merging key by key left the deployed + ``do_sample=False`` in force and every sample came back the greedy answer. + """ + merged = {**deployed, **call} + if "temperature" in call and "do_sample" not in call: + merged.pop("do_sample", None) + return merged + + @dataclass class RuntimeConfig: """How to run a model — orthogonal to *which* model (that's the spec).""" diff --git a/evalrx/models/backends/hf/model.py b/evalrx/models/backends/hf/model.py index 119f7de5..614e4f3a 100755 --- a/evalrx/models/backends/hf/model.py +++ b/evalrx/models/backends/hf/model.py @@ -29,7 +29,7 @@ from evalrx.core.spec import AttnSemantics from evalrx.core.tool import ChatTurn from evalrx.models._media import AUDIO_SAMPLE_RATE, resolve_audio -from evalrx.models.backends.base import Backend, RuntimeConfig +from evalrx.models.backends.base import Backend, RuntimeConfig, call_sampling from evalrx.models.backends.hf._util import ( # noqa: F401 _check_audio_duration, _collect_message_images, @@ -458,7 +458,7 @@ def _decoding(self, tok: Any, kwargs: dict[str, Any]) -> dict[str, Any]: The call's own *kwargs* win over ``runtime.sampling``, the decoding the model is deployed with. """ - kwargs = {**self.runtime.sampling, **kwargs} + kwargs = call_sampling(self.runtime.sampling, kwargs) # "max_tokens" is the OpenAI-style name FixAgent's judge-proposed L2 # PipelineSpecs use (see fix_tools._safe_generation_kwargs and the # _L2_PROMPT schema); transformers' generate() only recognises diff --git a/evalrx/models/backends/jax/backend.py b/evalrx/models/backends/jax/backend.py index 792e3a62..2000faf8 100644 --- a/evalrx/models/backends/jax/backend.py +++ b/evalrx/models/backends/jax/backend.py @@ -43,7 +43,7 @@ from evalrx.core.model import Model, TokenLogprob, Trace from evalrx.core.tokentype import TokenTypeMap from evalrx.core.tool import ChatTurn -from evalrx.models.backends.base import Backend, RuntimeConfig +from evalrx.models.backends.base import Backend, RuntimeConfig, call_sampling from evalrx.models.backends.jax.protocol import ( CAPTURE_ATTN, CAPTURE_HIDDEN, @@ -172,7 +172,7 @@ def _sampling(self, kwargs: dict) -> SamplingParams: ``max_tokens``; ``temperature <= 0`` (or ``do_sample=False``) is greedy; ``do_sample=True`` without a temperature samples at 1.0. The call's own kwargs win over ``runtime.sampling``.""" - kwargs = {**self.runtime.sampling, **kwargs} + kwargs = call_sampling(self.runtime.sampling, kwargs) max_new = kwargs.pop("max_new_tokens", None) if max_new is None: max_new = kwargs.pop("max_tokens", self.runtime.max_new_tokens) diff --git a/evalrx/models/backends/vllm_offline.py b/evalrx/models/backends/vllm_offline.py index 236307c0..419e7537 100755 --- a/evalrx/models/backends/vllm_offline.py +++ b/evalrx/models/backends/vllm_offline.py @@ -22,7 +22,7 @@ from evalrx.core.case import Inputs from evalrx.core.model import Model, TokenLogprob, Trace from evalrx.core.tool import ChatTurn -from evalrx.models.backends.base import Backend, RuntimeConfig +from evalrx.models.backends.base import Backend, RuntimeConfig, call_sampling class VLLMOfflineModel(Model): @@ -65,7 +65,7 @@ def _sampling(self, *, logprobs: int | None = None, **kwargs: Any): when ``do_sample`` is False or the temperature is not positive).""" from vllm import SamplingParams - kwargs = {**self.runtime.sampling, **kwargs} + kwargs = call_sampling(self.runtime.sampling, kwargs) max_tokens = kwargs.get("max_new_tokens") or kwargs.get("max_tokens") or self.runtime.max_new_tokens temperature = float(kwargs.get("temperature") or 0.0) if kwargs.get("do_sample") is False: diff --git a/tests/test_models/test_jax_local.py b/tests/test_models/test_jax_local.py index 6a3ee334..7d5edeb5 100644 --- a/tests/test_models/test_jax_local.py +++ b/tests/test_models/test_jax_local.py @@ -223,6 +223,10 @@ def test_generate_kwargs_map_to_sampling_params(): assert m._sampling({"do_sample": True}).temperature == 1.0 assert m._sampling({"temperature": 0.7, "do_sample": False}).greedy assert m._sampling({"max_new_tokens": 2, "max_tokens": 9}).max_new_tokens == 2 + m.runtime.sampling = {"do_sample": False} # deployed greedy + assert m._sampling({}).greedy and m._sampling({"top_p": 0.9}).greedy + assert m._sampling({"temperature": 1.0}).temperature == 1.0 # a call's own temperature samples + assert m._sampling({"temperature": 0.0}).greedy class ScopedToyAdapter(ToyAdapter): diff --git a/tests/test_models/test_wrap.py b/tests/test_models/test_wrap.py index 5767cbc8..e8edabe5 100755 --- a/tests/test_models/test_wrap.py +++ b/tests/test_models/test_wrap.py @@ -490,6 +490,26 @@ def test_hf_local_uses_the_runtime_sampling_unless_the_call_passes_its_own(): assert not {"temperature", "top_p"} & set(lm.calls[-1]) +def test_hf_local_samples_when_a_call_names_a_temperature_on_a_greedy_runtime(): + m = evalrx.wrap(FakeCausalLM(), FakeTokenizer()) + m.runtime.sampling = {"do_sample": False} # how a greedy benchmark cell deploys the model + lm = _RecordingLM() + m._hf = (lm, FakeTokenizer()) + + m.generate(Inputs(prompt="hi")) + assert lm.calls[-1]["do_sample"] is False + + m.generate(Inputs(prompt="hi"), temperature=1.0, top_p=0.95) # a re-sampling probe + assert {k: lm.calls[-1][k] for k in ("do_sample", "temperature", "top_p")} == { + "do_sample": True, "temperature": 1.0, "top_p": 0.95} + + m.generate(Inputs(prompt="hi"), top_p=0.9) # no temperature of its own: still greedy + assert lm.calls[-1]["do_sample"] is False + + m.generate(Inputs(prompt="hi"), temperature=0.0) + assert lm.calls[-1]["do_sample"] is False + + def test_vllm_offline_hands_the_engine_every_prompt_at_once(monkeypatch): import sys import types From 802bd71e5884a776041df19b1d80a0b25ccb28fe Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:11:11 -0700 Subject: [PATCH 23/26] Rename the triage controller package to evalrx.eval_agent.triage evalrx/eval_agent/probing held the triage controller, next to main's evalrx/probing (probe catalog and router), which is a different thing. The package is now evalrx/eval_agent/triage, and its triage.py, which assigns the routes, is routes.py. The tests follow: test_probing_{mvp0,mvp2,mvp3,mvp3b} become test_triage_{routes,expansion,scoring,explanations}, and test_probing_{chunks,alternatives,validation} become test_triage_*. Only paths, import lines and import order change. A run still writes to /probing/ under the same file names; the code label in a report names the package directory, so its key reads eval_agent/triage. --- evalrx/benchmark/runner.py | 14 +++---- .../{probing => triage}/__init__.py | 10 ++--- .../eval_agent/{probing => triage}/actions.py | 0 .../eval_agent/{probing => triage}/compare.py | 4 +- .../{probing => triage}/controller.py | 42 +++++++++---------- .../{probing => triage}/evidence.py | 2 +- .../{probing => triage}/executor.py | 6 +-- .../{probing => triage}/explanations.py | 4 +- .../eval_agent/{probing => triage}/ledger.py | 2 +- .../{probing => triage}/metering.py | 0 .../{probing => triage}/partition.py | 4 +- .../{probing/triage.py => triage/routes.py} | 6 +-- .../eval_agent/{probing => triage}/rules.py | 4 +- .../eval_agent/{probing => triage}/sampler.py | 0 .../eval_agent/{probing => triage}/scoring.py | 4 +- .../{probing => triage}/validation.py | 30 ++++++------- tests/test_analysis/test_run_cli.py | 2 +- ...natives.py => test_triage_alternatives.py} | 14 +++---- ...robing_chunks.py => test_triage_chunks.py} | 10 ++--- ...obing_mvp2.py => test_triage_expansion.py} | 24 +++++------ ...g_mvp3b.py => test_triage_explanations.py} | 32 +++++++------- ..._probing_mvp0.py => test_triage_routes.py} | 34 +++++++-------- ...probing_mvp3.py => test_triage_scoring.py} | 18 ++++---- ...alidation.py => test_triage_validation.py} | 16 +++---- 24 files changed, 141 insertions(+), 141 deletions(-) rename evalrx/eval_agent/{probing => triage}/__init__.py (86%) rename evalrx/eval_agent/{probing => triage}/actions.py (100%) rename evalrx/eval_agent/{probing => triage}/compare.py (97%) rename evalrx/eval_agent/{probing => triage}/controller.py (99%) rename evalrx/eval_agent/{probing => triage}/evidence.py (97%) rename evalrx/eval_agent/{probing => triage}/executor.py (97%) rename evalrx/eval_agent/{probing => triage}/explanations.py (99%) rename evalrx/eval_agent/{probing => triage}/ledger.py (98%) rename evalrx/eval_agent/{probing => triage}/metering.py (100%) rename evalrx/eval_agent/{probing => triage}/partition.py (95%) rename evalrx/eval_agent/{probing/triage.py => triage/routes.py} (99%) rename evalrx/eval_agent/{probing => triage}/rules.py (99%) rename evalrx/eval_agent/{probing => triage}/sampler.py (100%) rename evalrx/eval_agent/{probing => triage}/scoring.py (99%) rename evalrx/eval_agent/{probing => triage}/validation.py (99%) rename tests/test_eval_agent/{test_probing_alternatives.py => test_triage_alternatives.py} (96%) rename tests/test_eval_agent/{test_probing_chunks.py => test_triage_chunks.py} (97%) rename tests/test_eval_agent/{test_probing_mvp2.py => test_triage_expansion.py} (96%) rename tests/test_eval_agent/{test_probing_mvp3b.py => test_triage_explanations.py} (96%) rename tests/test_eval_agent/{test_probing_mvp0.py => test_triage_routes.py} (97%) rename tests/test_eval_agent/{test_probing_mvp3.py => test_triage_scoring.py} (95%) rename tests/test_eval_agent/{test_probing_validation.py => test_triage_validation.py} (97%) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index c7ef6c21..14453916 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -190,7 +190,7 @@ def _sampling_kwargs(resolved: Resolved, args) -> "dict | None": def _usage_cost(model, before: "dict | None") -> dict: """Provider usage since *before* and its listed-price USD (``{}`` for a model with no counters).""" - from evalrx.eval_agent.probing.metering import usage_counters, usage_delta + from evalrx.eval_agent.triage.metering import usage_counters, usage_delta from evalrx.models.backends.api.prices import usd usage = usage_delta(before, usage_counters(model)) @@ -691,7 +691,7 @@ def _triage_explainer(args, spec): Triage runs no coding stage, so the judge is built without the coder checks the Gemini judge otherwise needs. The judge must not be the model under test.""" - from evalrx.eval_agent.probing.explanations import Explainer + from evalrx.eval_agent.triage.explanations import Explainer from evalrx.models.backends.api.prices import usd if args.triage_scheduler != "scored": @@ -748,9 +748,9 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: the issues the report supports are frozen and validated once on DIAGNOSTIC_VALIDATION (``/validation/``). """ - from evalrx.eval_agent.probing import explore_confirm_split, run_triage - from evalrx.eval_agent.probing.scoring import Weights - from evalrx.eval_agent.probing.validation import freeze_issues, partition_bundle, validate + from evalrx.eval_agent.triage import explore_confirm_split, run_triage + from evalrx.eval_agent.triage.scoring import Weights + from evalrx.eval_agent.triage.validation import freeze_issues, partition_bundle, validate from .run import triage_weights @@ -813,7 +813,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "confirm_visible_to_controller": False}, run_logger=ctx.logger, **shared, ) - from evalrx.eval_agent.probing.controller import report_name + from evalrx.eval_agent.triage.controller import report_name name = report_name(args.triage_scheduler, explainer is not None) checked = None @@ -892,7 +892,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: batch_case_ids=[c.id for c in candidates], ) - from evalrx.eval_agent.probing.metering import usage_counters + from evalrx.eval_agent.triage.metering import usage_counters usage_before = usage_counters(model) discovery, elapsed = _discover(discovery_model, candidates, protocol, gen_kwargs, args, task) diff --git a/evalrx/eval_agent/probing/__init__.py b/evalrx/eval_agent/triage/__init__.py similarity index 86% rename from evalrx/eval_agent/probing/__init__.py rename to evalrx/eval_agent/triage/__init__.py index 7fecf36b..8680e48b 100644 --- a/evalrx/eval_agent/probing/__init__.py +++ b/evalrx/eval_agent/triage/__init__.py @@ -34,11 +34,11 @@ from __future__ import annotations -from evalrx.eval_agent.probing.actions import Observation, PlanStep, ProbeAction -from evalrx.eval_agent.probing.controller import BATTERY, POLICY_VERSION, run_triage -from evalrx.eval_agent.probing.partition import explore_confirm_split -from evalrx.eval_agent.probing.rules import LAYERS, RULES_VERSION -from evalrx.eval_agent.probing.sampler import SampleDraw, matched_sample +from evalrx.eval_agent.triage.actions import Observation, PlanStep, ProbeAction +from evalrx.eval_agent.triage.controller import BATTERY, POLICY_VERSION, run_triage +from evalrx.eval_agent.triage.partition import explore_confirm_split +from evalrx.eval_agent.triage.rules import LAYERS, RULES_VERSION +from evalrx.eval_agent.triage.sampler import SampleDraw, matched_sample __all__ = [ "BATTERY", diff --git a/evalrx/eval_agent/probing/actions.py b/evalrx/eval_agent/triage/actions.py similarity index 100% rename from evalrx/eval_agent/probing/actions.py rename to evalrx/eval_agent/triage/actions.py diff --git a/evalrx/eval_agent/probing/compare.py b/evalrx/eval_agent/triage/compare.py similarity index 97% rename from evalrx/eval_agent/probing/compare.py rename to evalrx/eval_agent/triage/compare.py index 0f4c9d6a..845347af 100644 --- a/evalrx/eval_agent/probing/compare.py +++ b/evalrx/eval_agent/triage/compare.py @@ -14,7 +14,7 @@ from pathlib import Path from typing import Any -from evalrx.eval_agent.probing.explanations import CARDS, primary_readings, verdict +from evalrx.eval_agent.triage.explanations import CARDS, primary_readings, verdict def discrimination(explained: dict[str, Any], report: dict[str, Any]) -> dict[str, Any]: @@ -117,7 +117,7 @@ def markdown(diff: dict[str, Any]) -> str: def main(argv: "list[str] | None" = None) -> int: - """``python -m evalrx.eval_agent.probing.compare [--json]``: two arms' + """``python -m evalrx.eval_agent.triage.compare [--json]``: two arms' triage reports side by side, as Markdown (default) or as the JSON diff.""" p = argparse.ArgumentParser(description="two triage reports side by side: selection order, evidence cost, " "coverage and, with an explaining run, the explanations told apart") diff --git a/evalrx/eval_agent/probing/controller.py b/evalrx/eval_agent/triage/controller.py similarity index 99% rename from evalrx/eval_agent/probing/controller.py rename to evalrx/eval_agent/triage/controller.py index 9a1bf135..9cde3d43 100644 --- a/evalrx/eval_agent/probing/controller.py +++ b/evalrx/eval_agent/triage/controller.py @@ -45,7 +45,7 @@ check is X). 3. **Follow-ups.** Each active route proposes its next layer's candidate (see - :mod:`~evalrx.eval_agent.probing.rules`), and the candidate runs on the + :mod:`~evalrx.eval_agent.triage.rules`), and the candidate runs on the route's FAIL cases plus matched PASS controls. Every decision is a trace event that names its rule, the condition it read, @@ -85,7 +85,7 @@ from typing import TYPE_CHECKING, Any, Callable, cast from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES -from evalrx.eval_agent.probing.actions import ( +from evalrx.eval_agent.triage.actions import ( FAILED, OK, SKIPPED, @@ -93,9 +93,9 @@ ProbeAction, canonical, ) -from evalrx.eval_agent.probing.evidence import StepEvidence -from evalrx.eval_agent.probing.executor import execute, gate -from evalrx.eval_agent.probing.explanations import ( +from evalrx.eval_agent.triage.evidence import StepEvidence +from evalrx.eval_agent.triage.executor import execute, gate +from evalrx.eval_agent.triage.explanations import ( CARDS, EXPLAIN_VERSION, Explainer, @@ -110,9 +110,18 @@ outcome, restates_route, ) -from evalrx.eval_agent.probing.explanations import spread as reading_spread -from evalrx.eval_agent.probing.ledger import Ledger -from evalrx.eval_agent.probing.rules import ( +from evalrx.eval_agent.triage.explanations import spread as reading_spread +from evalrx.eval_agent.triage.ledger import Ledger +from evalrx.eval_agent.triage.routes import ( + ROUTE_STEPS, + commits_to_answers, + common_answers, + follow_up_reading, + follow_up_values, + summarize, + triage_cases, +) +from evalrx.eval_agent.triage.rules import ( LAYER_READOUT, LAYERS, MEDIA_ATTENTION_CUT, @@ -130,8 +139,8 @@ route_fail_ids, route_states, ) -from evalrx.eval_agent.probing.sampler import matched_sample, rank -from evalrx.eval_agent.probing.scoring import ( +from evalrx.eval_agent.triage.sampler import matched_sample, rank +from evalrx.eval_agent.triage.scoring import ( SCORING_VERSION, Scored, Weights, @@ -144,15 +153,6 @@ step_cost, value, ) -from evalrx.eval_agent.probing.triage import ( - ROUTE_STEPS, - commits_to_answers, - common_answers, - follow_up_reading, - follow_up_values, - summarize, - triage_cases, -) if TYPE_CHECKING: from evalrx.core.case import CaseBatch @@ -280,7 +280,7 @@ def code_version() -> dict[str, Any]: """The code this process runs: recorded in the reports and on every planned action. ``tree`` hashes every ``*.py`` file of the evalrx package, ``parts`` the same per - package directory (``models``, ``eval_agent/probing``, ...; ``.`` = the top-level + package directory (``models``, ``eval_agent/triage``, ...; ``.`` = the top-level modules), so a reader can tell a backend change from a scheduler change. Neither enters an action identity (only :func:`tool_version` does): a change outside the analyzer still reads the ledger back, and these hashes are what tells such @@ -715,7 +715,7 @@ def run_triage( with a counterfactual donor. Donors are drawn from the whole of *explore*, never from outside it. Elsewhere the same holds per case for an answer that is a common gold - of *explore* (:func:`~.triage.common_answers`). + of *explore* (:func:`~.routes.common_answers`). task_kind: the task's kind; steps limited to other kinds are recorded as ``not_applicable`` and not run. answer_fn: ``(case, output) -> answer key`` (``""`` = no readable diff --git a/evalrx/eval_agent/probing/evidence.py b/evalrx/eval_agent/triage/evidence.py similarity index 97% rename from evalrx/eval_agent/probing/evidence.py rename to evalrx/eval_agent/triage/evidence.py index 9ecbfd86..62c30ba0 100644 --- a/evalrx/eval_agent/probing/evidence.py +++ b/evalrx/eval_agent/triage/evidence.py @@ -21,7 +21,7 @@ from dataclasses import dataclass, field from typing import Any, Iterable -from evalrx.eval_agent.probing.actions import OK, UNFAITHFUL, Observation, PlanStep +from evalrx.eval_agent.triage.actions import OK, UNFAITHFUL, Observation, PlanStep @dataclass diff --git a/evalrx/eval_agent/probing/executor.py b/evalrx/eval_agent/triage/executor.py similarity index 97% rename from evalrx/eval_agent/probing/executor.py rename to evalrx/eval_agent/triage/executor.py index e21925bc..b2d82d61 100644 --- a/evalrx/eval_agent/probing/executor.py +++ b/evalrx/eval_agent/triage/executor.py @@ -1,4 +1,4 @@ -"""Strict execution of one :class:`~evalrx.eval_agent.probing.actions.ProbeAction`. +"""Strict execution of one :class:`~evalrx.eval_agent.triage.actions.ProbeAction`. Unlike ``ProbeAgent.probe``, nothing here selects, filters, backfills, caps or generates: the analyzer runs once on exactly the planned cases, and the @@ -25,7 +25,7 @@ import time from typing import TYPE_CHECKING, Any, cast -from evalrx.eval_agent.probing.actions import ( +from evalrx.eval_agent.triage.actions import ( FAILED, OK, UNFAITHFUL, @@ -34,7 +34,7 @@ ProbeAction, canonical, ) -from evalrx.eval_agent.probing.metering import ( +from evalrx.eval_agent.triage.metering import ( MeteredModel, gpu_peak_mb, gpu_peak_reset, diff --git a/evalrx/eval_agent/probing/explanations.py b/evalrx/eval_agent/triage/explanations.py similarity index 99% rename from evalrx/eval_agent/probing/explanations.py rename to evalrx/eval_agent/triage/explanations.py index 73a9d714..30d0ab59 100644 --- a/evalrx/eval_agent/probing/explanations.py +++ b/evalrx/eval_agent/triage/explanations.py @@ -83,8 +83,8 @@ from pathlib import Path from typing import Any, Callable, Iterable -from evalrx.eval_agent.probing.metering import usage_counters, usage_delta -from evalrx.eval_agent.probing.triage import difference_interval +from evalrx.eval_agent.triage.metering import usage_counters, usage_delta +from evalrx.eval_agent.triage.routes import difference_interval EXPLAIN_VERSION = "mvp4-explain-6" DIRECTIONS = ("up", "down", "same", "unknown") diff --git a/evalrx/eval_agent/probing/ledger.py b/evalrx/eval_agent/triage/ledger.py similarity index 98% rename from evalrx/eval_agent/probing/ledger.py rename to evalrx/eval_agent/triage/ledger.py index 3270744c..19f8b999 100644 --- a/evalrx/eval_agent/probing/ledger.py +++ b/evalrx/eval_agent/triage/ledger.py @@ -25,7 +25,7 @@ from pathlib import Path from typing import Any -from evalrx.eval_agent.probing.actions import TERMINAL, Observation, canonical +from evalrx.eval_agent.triage.actions import TERMINAL, Observation, canonical class Ledger: diff --git a/evalrx/eval_agent/probing/metering.py b/evalrx/eval_agent/triage/metering.py similarity index 100% rename from evalrx/eval_agent/probing/metering.py rename to evalrx/eval_agent/triage/metering.py diff --git a/evalrx/eval_agent/probing/partition.py b/evalrx/eval_agent/triage/partition.py similarity index 95% rename from evalrx/eval_agent/probing/partition.py rename to evalrx/eval_agent/triage/partition.py index 55b7fbff..6d2b5a5a 100644 --- a/evalrx/eval_agent/probing/partition.py +++ b/evalrx/eval_agent/triage/partition.py @@ -7,7 +7,7 @@ ``by="media"`` is the triage protocol's own variant: the cases are grouped by their media content and whole groups go to one side, so DISCOVERY and CONFIRM -never share an image and :func:`~evalrx.eval_agent.probing.validation.partition_bundle` +never share an image and :func:`~evalrx.eval_agent.triage.validation.partition_bundle` leaves nothing out (under the per-case split 207 of ChartQA's 500 CONFIRM cases shared a chart with DISCOVERY and were dropped). A judge-driven run still splits by case, so the two policies are compared case for case under ``by="case"`` only. @@ -45,7 +45,7 @@ def split_by_media(data: "CaseBatch", confirm_split: float, seed: int) -> "tuple 4 cases or when a side would be empty (then ``(data, None)``).""" from evalrx.core.case import CaseBatch from evalrx.eval_agent.loop.partition import _strat_key - from evalrx.eval_agent.probing.validation import source_key + from evalrx.eval_agent.triage.validation import source_key from evalrx.stats.subset_sampling import stratified_subset cases = list(data) diff --git a/evalrx/eval_agent/probing/triage.py b/evalrx/eval_agent/triage/routes.py similarity index 99% rename from evalrx/eval_agent/probing/triage.py rename to evalrx/eval_agent/triage/routes.py index f8da0cec..5cc7c188 100644 --- a/evalrx/eval_agent/probing/triage.py +++ b/evalrx/eval_agent/triage/routes.py @@ -52,8 +52,8 @@ from evalrx.analyzers.perturbation.prompt_contrast import _norm_answer from evalrx.core.case import MEDIA_SLOTS -from evalrx.eval_agent.probing.actions import OK, Observation -from evalrx.eval_agent.probing.evidence import StepEvidence, pick +from evalrx.eval_agent.triage.actions import OK, Observation +from evalrx.eval_agent.triage.evidence import StepEvidence, pick FIRED, CLEAR, UNTESTED, NOT_APPLICABLE = "fired", "clear", "untested", "not_applicable" @@ -461,7 +461,7 @@ def triage_cases(cases: Any, observations: "Mapping[str, Observation | StepEvide stratum, so it must be the rule the sample was drawn with. Open-answer tasks draw with ``"none"``; a gold stratum there leaves almost no PASS case with a FAIL case's gold to serve as its control. """ - from evalrx.eval_agent.probing.sampler import STRATA + from evalrx.eval_agent.triage.sampler import STRATA answer, agree = answer_fn or default_answer, agree_fn or exact_answer stratum_of = STRATA[stratum] diff --git a/evalrx/eval_agent/probing/rules.py b/evalrx/eval_agent/triage/rules.py similarity index 99% rename from evalrx/eval_agent/probing/rules.py rename to evalrx/eval_agent/triage/rules.py index 67fd3661..e076c3db 100644 --- a/evalrx/eval_agent/probing/rules.py +++ b/evalrx/eval_agent/triage/rules.py @@ -44,8 +44,8 @@ from typing import Any, Callable from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES -from evalrx.eval_agent.probing.actions import PlanStep -from evalrx.eval_agent.probing.evidence import StepEvidence +from evalrx.eval_agent.triage.actions import PlanStep +from evalrx.eval_agent.triage.evidence import StepEvidence RULES_VERSION = "mvp4-rules-5" ROUTE_ORDER = ("H", "N", "U", "S", "X") diff --git a/evalrx/eval_agent/probing/sampler.py b/evalrx/eval_agent/triage/sampler.py similarity index 100% rename from evalrx/eval_agent/probing/sampler.py rename to evalrx/eval_agent/triage/sampler.py diff --git a/evalrx/eval_agent/probing/scoring.py b/evalrx/eval_agent/triage/scoring.py similarity index 99% rename from evalrx/eval_agent/probing/scoring.py rename to evalrx/eval_agent/triage/scoring.py index 369cd273..8c86d36a 100644 --- a/evalrx/eval_agent/probing/scoring.py +++ b/evalrx/eval_agent/triage/scoring.py @@ -92,8 +92,8 @@ from dataclasses import dataclass, field from typing import Any -from evalrx.eval_agent.probing.actions import OK, UNSUPPORTED, PlanStep -from evalrx.eval_agent.probing.evidence import StepEvidence +from evalrx.eval_agent.triage.actions import OK, UNSUPPORTED, PlanStep +from evalrx.eval_agent.triage.evidence import StepEvidence SCORING_VERSION = "mvp3-score-5" diff --git a/evalrx/eval_agent/probing/validation.py b/evalrx/eval_agent/triage/validation.py similarity index 99% rename from evalrx/eval_agent/probing/validation.py rename to evalrx/eval_agent/triage/validation.py index 5e04f329..27af4354 100644 --- a/evalrx/eval_agent/probing/validation.py +++ b/evalrx/eval_agent/triage/validation.py @@ -81,8 +81,8 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Callable -from evalrx.eval_agent.probing.actions import PlanStep -from evalrx.eval_agent.probing.explanations import ( +from evalrx.eval_agent.triage.actions import PlanStep +from evalrx.eval_agent.triage.explanations import ( CARDS, MIN_N, Metric, @@ -94,17 +94,8 @@ verdict, z_quantile, ) -from evalrx.eval_agent.probing.ledger import Ledger -from evalrx.eval_agent.probing.rules import ( - LAYERS, - RULES_VERSION, - Layer, - candidate_steps, - matched_controls, - route_fail_ids, -) -from evalrx.eval_agent.probing.sampler import matched_sample, rank -from evalrx.eval_agent.probing.triage import ( +from evalrx.eval_agent.triage.ledger import Ledger +from evalrx.eval_agent.triage.routes import ( ROUTE_STEPS, commits_to_answers, common_answers, @@ -112,6 +103,15 @@ follow_up_values, triage_cases, ) +from evalrx.eval_agent.triage.rules import ( + LAYERS, + RULES_VERSION, + Layer, + candidate_steps, + matched_controls, + route_fail_ids, +) +from evalrx.eval_agent.triage.sampler import matched_sample, rank if TYPE_CHECKING: from evalrx.core.case import CaseBatch @@ -554,7 +554,7 @@ def validate(model: Any, discovery: "CaseBatch", validation: "CaseBatch", famili battery: "tuple[PlanStep, ...] | None" = None, layers: "tuple[Layer, ...]" = LAYERS, run_logger: Any = None, progress: "Callable[[str], None] | None" = print) -> dict[str, Any]: """Validate the union of the arms' frozen *families* once on *validation*; credit every arm.""" - from evalrx.eval_agent.probing.controller import ( + from evalrx.eval_agent.triage.controller import ( BATTERY, POLICY_VERSION, _Run, @@ -771,7 +771,7 @@ def _check_explanations(explanations: dict[str, list[dict[str, Any]]], run: Any, def markdown(report: dict[str, Any]) -> str: - from evalrx.eval_agent.probing.controller import code_label + from evalrx.eval_agent.triage.controller import code_label part = report.get("partition") or {} lines = [f"# Diagnostic validation ({report['version']}; {code_label(report.get('code'))})", "", diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index 8eac96f9..ac9c2505 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -168,7 +168,7 @@ def run(loop, data): def test_triage_explainer_is_the_chain_judge_and_never_the_model_under_test(monkeypatch): - from evalrx.eval_agent.probing.explanations import Explainer + from evalrx.eval_agent.triage.explanations import Explainer seen = {} diff --git a/tests/test_eval_agent/test_probing_alternatives.py b/tests/test_eval_agent/test_triage_alternatives.py similarity index 96% rename from tests/test_eval_agent/test_probing_alternatives.py rename to tests/test_eval_agent/test_triage_alternatives.py index 54dd6e93..089bbf9e 100644 --- a/tests/test_eval_agent/test_probing_alternatives.py +++ b/tests/test_eval_agent/test_triage_alternatives.py @@ -17,13 +17,13 @@ import pytest -import evalrx.eval_agent.probing.controller as controller -from evalrx.eval_agent.probing import LAYERS, run_triage -from evalrx.eval_agent.probing.actions import PlanStep -from evalrx.eval_agent.probing.explanations import CARDS, Explainer, Metric -from evalrx.eval_agent.probing.rules import Layer -from evalrx.eval_agent.probing.scoring import Weights -from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table +import evalrx.eval_agent.triage.controller as controller +from evalrx.eval_agent.triage import LAYERS, run_triage +from evalrx.eval_agent.triage.actions import PlanStep +from evalrx.eval_agent.triage.explanations import CARDS, Explainer, Metric +from evalrx.eval_agent.triage.rules import Layer +from evalrx.eval_agent.triage.scoring import Weights +from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _Table def _wrapper(key, text, evidence): diff --git a/tests/test_eval_agent/test_probing_chunks.py b/tests/test_eval_agent/test_triage_chunks.py similarity index 97% rename from tests/test_eval_agent/test_probing_chunks.py rename to tests/test_eval_agent/test_triage_chunks.py index b78b9c30..dfe30834 100644 --- a/tests/test_eval_agent/test_probing_chunks.py +++ b/tests/test_eval_agent/test_triage_chunks.py @@ -16,9 +16,9 @@ import pytest -import evalrx.eval_agent.probing.controller as controller -from evalrx.eval_agent.probing import run_triage -from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _strip, _Table +import evalrx.eval_agent.triage.controller as controller +from evalrx.eval_agent.triage import run_triage +from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _strip, _Table DESCRIBE_SEC = 10.0 # an expensive step whose cost no prior knows @@ -116,8 +116,8 @@ def test_further_chunks_of_a_taken_step_do_not_use_up_max_actions(tmp_path): def test_the_control_schedulers_run_over_the_scored_pool_and_never_explore(tmp_path): import pytest - from evalrx.eval_agent.probing.controller import report_name - from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table + from evalrx.eval_agent.triage.controller import report_name + from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _Table cases, table = _pope_like() reports = {} diff --git a/tests/test_eval_agent/test_probing_mvp2.py b/tests/test_eval_agent/test_triage_expansion.py similarity index 96% rename from tests/test_eval_agent/test_probing_mvp2.py rename to tests/test_eval_agent/test_triage_expansion.py index 1ec8887a..5d42f057 100644 --- a/tests/test_eval_agent/test_probing_mvp2.py +++ b/tests/test_eval_agent/test_triage_expansion.py @@ -18,17 +18,17 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.model import Model -from evalrx.eval_agent.probing import BATTERY, LAYERS, run_triage -from evalrx.eval_agent.probing.actions import FAILED, OK, UNFAITHFUL, Observation -from evalrx.eval_agent.probing.evidence import StepEvidence -from evalrx.eval_agent.probing.rules import ( +from evalrx.eval_agent.triage import BATTERY, LAYERS, run_triage +from evalrx.eval_agent.triage.actions import FAILED, OK, UNFAITHFUL, Observation +from evalrx.eval_agent.triage.evidence import StepEvidence +from evalrx.eval_agent.triage.routes import difference_interval +from evalrx.eval_agent.triage.rules import ( active_routes, candidate_steps, expansion_gaps, next_for_route, next_size, ) -from evalrx.eval_agent.probing.triage import difference_interval OBJECTS = ("cat", "dog", "car", "cup") @@ -179,8 +179,8 @@ def generate(self, inputs, **kwargs): # dropped per call (an OpenAI-compatible endpoint): the step runs without its # gen_kwargs, so the host's 16-token cap applies and leaves no room - from evalrx.eval_agent.probing.controller import _Run - from evalrx.eval_agent.probing.ledger import Ledger + from evalrx.eval_agent.triage.controller import _Run + from evalrx.eval_agent.triage.ledger import Ledger step, ids = _step("describe_first"), [str(c.id) for c in cases][:4] for per_call, expected in ((True, None), (False, "not_applicable")): @@ -290,7 +290,7 @@ def test_a_refusal_on_any_chunk_refuses_the_step_on_every_case(): plain = StepEvidence(_step("self_consistency"), [_obs("sc", ["a", "b"]), _obs("sc", ["c"], status=FAILED)]) assert plain.for_case("a").status == OK and plain.for_case("c").status == FAILED assert plain.todo(["a", "b", "c", "d"]) == ["d"] - from evalrx.eval_agent.probing.actions import PlanStep + from evalrx.eval_agent.triage.actions import PlanStep batchy = StepEvidence(PlanStep("x", {}, "S", "reads the batch", reuse=False, reuse_note="test"), [_obs("el", ["a", "b"])]) @@ -321,8 +321,8 @@ def summary(k_fail, k_pass, n): def test_budget_estimates_come_from_the_same_steps_earlier_seconds_and_charge_the_evidence(tmp_path): - from evalrx.eval_agent.probing.controller import _Run - from evalrx.eval_agent.probing.ledger import Ledger + from evalrx.eval_agent.triage.controller import _Run + from evalrx.eval_agent.triage.ledger import Ledger cases, table = _pope_like() ledger = Ledger(tmp_path / "b") @@ -367,7 +367,7 @@ def test_every_reuse_step_is_covered_by_a_decomposability_check(): def _rows(result): - from evalrx.eval_agent.probing.actions import canonical + from evalrx.eval_agent.triage.actions import canonical findings = canonical(result.findings or {}) rows = {str(r["sample_id"]): r for r in findings.get("per_case") or []} @@ -453,7 +453,7 @@ def generate(self, inputs, **kwargs): def test_a_layer_that_narrows_its_route_states_its_filter(): - from evalrx.eval_agent.probing.rules import public, route_states + from evalrx.eval_agent.triage.rules import public, route_states records = _records() + [{"case_id": f"x{i}", "label": "fail", "stratum": "no", "routes": ["X"], "stable": False, "N": {"state": "untested", "reason": "no counterfactual donor"}} for i in range(3)] diff --git a/tests/test_eval_agent/test_probing_mvp3b.py b/tests/test_eval_agent/test_triage_explanations.py similarity index 96% rename from tests/test_eval_agent/test_probing_mvp3b.py rename to tests/test_eval_agent/test_triage_explanations.py index c19b1a1b..cd893491 100644 --- a/tests/test_eval_agent/test_probing_mvp3b.py +++ b/tests/test_eval_agent/test_triage_explanations.py @@ -17,8 +17,8 @@ import pytest -from evalrx.eval_agent.probing import run_triage -from evalrx.eval_agent.probing.explanations import ( +from evalrx.eval_agent.triage import run_triage +from evalrx.eval_agent.triage.explanations import ( CARDS, Explainer, Hypothesis, @@ -31,7 +31,7 @@ parse, verdict, ) -from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table +from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _Table def test_verdicts_follow_the_interval_against_the_predicted_region(): @@ -79,7 +79,7 @@ def test_disagreement_is_the_share_of_live_pairs_whose_predictions_conflict(): def test_decidability_asks_whether_the_routes_cases_can_settle_a_conflict(): - from evalrx.eval_agent.probing.explanations import ( + from evalrx.eval_agent.triage.explanations import ( cases_needed, decidability, half_width, @@ -263,9 +263,9 @@ def test_scored_run_asks_once_the_sample_settles_and_resumes_without_asking(tmp_ def _wrapper_on_s(monkeypatch): """The layers with an S step the table model ignores: prompt_sensitivity is 0 on every case, so an "up" prediction on it misses at once.""" - from evalrx.eval_agent.probing import LAYERS - from evalrx.eval_agent.probing.actions import PlanStep - from evalrx.eval_agent.probing.rules import Layer + from evalrx.eval_agent.triage import LAYERS + from evalrx.eval_agent.triage.actions import PlanStep + from evalrx.eval_agent.triage.rules import Layer monkeypatch.setitem(CARDS, "wrapped", (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) step = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "w": "Q: {prompt}"}}, "Z1", @@ -292,7 +292,7 @@ def test_a_decided_prediction_that_thins_a_route_asks_the_judge_again(tmp_path, def test_a_route_left_with_only_steps_the_judge_is_not_asked_about_does_not_ask_again(tmp_path, monkeypatch): - import evalrx.eval_agent.probing.controller as controller + import evalrx.eval_agent.triage.controller as controller judge = _Judge(primary={"wrapped"}) # every S step re-measures S's cut here, the wrapper too once the judge has been asked: after the @@ -321,7 +321,7 @@ def test_the_rules_scheduler_does_not_take_an_explainer(tmp_path): def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence(tmp_path, capsys): - from evalrx.eval_agent.probing.compare import compare, main, markdown + from evalrx.eval_agent.triage.compare import compare, main, markdown out = tmp_path / "c" rules = run_triage(_Table(_pope_like()[1]), _pope_like()[0], **_kw(out, max_fail=8, min_route_fail=1)) @@ -341,7 +341,7 @@ def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence( @pytest.mark.parametrize("scheduler", ["rules", "scored"]) def test_a_budgeted_rerun_on_the_same_ledger_decides_as_the_run_that_executed(tmp_path, monkeypatch, scheduler): - import evalrx.eval_agent.probing.controller as controller + import evalrx.eval_agent.triage.controller as controller real = controller.execute @@ -379,9 +379,9 @@ def propose(self, root, revision, context, offered): def test_a_judge_call_is_asked_only_while_its_estimate_fits_the_budget(tmp_path, monkeypatch): - from evalrx.eval_agent.probing import LAYERS - from evalrx.eval_agent.probing.actions import PlanStep - from evalrx.eval_agent.probing.rules import Layer + from evalrx.eval_agent.triage import LAYERS + from evalrx.eval_agent.triage.actions import PlanStep + from evalrx.eval_agent.triage.rules import Layer # the re-ask scenario: two asks when nothing binds; the evidence costs milliseconds monkeypatch.setitem(CARDS, "wrapped", (Metric("prompt_sensitivity", "the answer moves with a wrapper", 0.1),)) @@ -435,7 +435,7 @@ def _offered_on(out): def test_the_judge_is_not_asked_to_predict_the_check_a_route_is_cut_on(tmp_path, monkeypatch): - import evalrx.eval_agent.probing.controller as controller + import evalrx.eval_agent.triage.controller as controller with monkeypatch.context() as m: m.setattr(controller, "restates_route", lambda route, step: False) @@ -445,7 +445,7 @@ def test_the_judge_is_not_asked_to_predict_the_check_a_route_is_cut_on(tmp_path, def test_a_route_with_nothing_left_to_run_is_explained_on_the_tools_already_run(tmp_path): - from evalrx.eval_agent.probing.explanations import restates_route + from evalrx.eval_agent.triage.explanations import restates_route report, judge = _wavering(tmp_path / "w") (prompt,) = judge.prompts @@ -461,7 +461,7 @@ def test_a_route_with_nothing_left_to_run_is_explained_on_the_tools_already_run( def test_a_new_ask_keeps_the_live_explanations_and_adds_only_competing_ones(): - from evalrx.eval_agent.probing.explanations import carry_over + from evalrx.eval_agent.triage.explanations import carry_over on = (("gradcam", "gc_top5_share"),) kept = [Hypothesis("S.h2", "S", "flat", {"gradcam": {"gc_top5_share": "same"}}, primary=on)] diff --git a/tests/test_eval_agent/test_probing_mvp0.py b/tests/test_eval_agent/test_triage_routes.py similarity index 97% rename from tests/test_eval_agent/test_probing_mvp0.py rename to tests/test_eval_agent/test_triage_routes.py index 08ca0481..150182fb 100644 --- a/tests/test_eval_agent/test_probing_mvp0.py +++ b/tests/test_eval_agent/test_triage_routes.py @@ -18,8 +18,8 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.model import Model -from evalrx.eval_agent.probing import explore_confirm_split, matched_sample, run_triage -from evalrx.eval_agent.probing.actions import ( +from evalrx.eval_agent.triage import explore_confirm_split, matched_sample, run_triage +from evalrx.eval_agent.triage.actions import ( FAILED, OK, UNFAITHFUL, @@ -27,8 +27,8 @@ Observation, ProbeAction, ) -from evalrx.eval_agent.probing.executor import execute -from evalrx.eval_agent.probing.triage import summarize, triage_cases +from evalrx.eval_agent.triage.executor import execute +from evalrx.eval_agent.triage.routes import summarize, triage_cases def _cases(n_fail=6, n_pass=8, gold_fail="No"): @@ -261,7 +261,7 @@ def _no_answer(case, output): def test_u_is_not_applicable_where_outputs_commit_to_no_answer_and_s_needs_h_and_n(): - from evalrx.eval_agent.probing.triage import commits_to_answers + from evalrx.eval_agent.triage.routes import commits_to_answers cases = CaseBatch([ _yn_case("s", Label.FAIL, "Yes", "A cat on a sofa."), # H and N clear: S without U @@ -281,7 +281,7 @@ def test_u_is_not_applicable_where_outputs_commit_to_no_answer_and_s_needs_h_and def test_common_answers_are_the_golds_a_share_of_discovery_has(): - from evalrx.eval_agent.probing.triage import common_answers + from evalrx.eval_agent.triage.routes import common_answers golds = ["small"] * 3 + ["large"] * 2 + [f"x{i}" for i in range(95)] cases = CaseBatch([FailureCase(id=f"c{i}", inputs=Inputs(prompt="q"), expected=g, observed=g, label=Label.PASS) @@ -313,7 +313,7 @@ def test_a_content_swap_does_not_test_n_where_the_answer_is_a_common_gold(): def test_open_answer_records_match_controls_without_the_gold_answer(): - from evalrx.eval_agent.probing.rules import matched_controls + from evalrx.eval_agent.triage.rules import matched_controls cases = CaseBatch([ FailureCase(id="f1", inputs=Inputs(prompt="q1"), expected="1.577", observed="1.5", label=Label.FAIL), @@ -474,7 +474,7 @@ def test_u_and_s_compare_answers_under_the_tasks_tolerance(): """ChartQA grades 12.6 against 12.5 as right (5 %), so the triage must not call them two answers: the host's agreement rule (``agree_fn``) decides, and the samples are clustered by it.""" from evalrx.benchmark import tasks - from evalrx.eval_agent.probing.triage import _contrast_values + from evalrx.eval_agent.triage.routes import _contrast_values cases = CaseBatch([_num_case("r", "100"), _num_case("p", "12.5"), _num_case("w", "12.4")]) ids = [c.id for c in cases] @@ -668,7 +668,7 @@ def _rerun(report): def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch): - from evalrx.eval_agent.probing import controller + from evalrx.eval_agent.triage import controller from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") @@ -683,7 +683,7 @@ def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch def test_mvp0_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vlm_cases, monkeypatch): - from evalrx.eval_agent.probing import controller + from evalrx.eval_agent.triage import controller from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") @@ -691,7 +691,7 @@ def test_mvp0_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vl stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) first = run_triage(model, vlm_cases, **kw) code = controller.code_version() - assert first["code"] == code and "eval_agent/probing" in code["parts"] + assert first["code"] == code and "eval_agent/triage" in code["parts"] out = tmp_path / "c" planned = [json.loads(line) for line in (out / "selection_trace.jsonl").read_text().splitlines() if '"planned"' in line] @@ -722,28 +722,28 @@ def test_mvp0_steps_that_compare_answers_do_not_run_where_outputs_commit_to_none def test_code_version_hashes_per_package_directory_and_reads_a_snapshot_ref(tmp_path): - from evalrx.eval_agent.probing.controller import _code_version, code_label + from evalrx.eval_agent.triage.controller import _code_version, code_label root = tmp_path / "evalrx" - for rel, text in {"__init__.py": "", "models/hf.py": "a = 1\n", "eval_agent/probing/rules.py": "b = 2\n", + for rel, text in {"__init__.py": "", "models/hf.py": "a = 1\n", "eval_agent/triage/rules.py": "b = 2\n", "reporting/web/node_modules/gyp/x.py": "", "models/__pycache__/hf.py": ""}.items(): (root / rel).parent.mkdir(parents=True, exist_ok=True) (root / rel).write_text(text) first = _code_version(root) - assert sorted(first["parts"]) == [".", "eval_agent/probing", "models"] + assert sorted(first["parts"]) == [".", "eval_agent/triage", "models"] assert first["git"] is None and code_label(first).endswith("commit unknown") (root / "models" / "hf.py").write_text("a = 3\n") (tmp_path / "CODE_REF.json").write_text('{"commit": "0123456789abcdef", "dirty": true}') second = _code_version(root) assert second["tree"] != first["tree"] and second["parts"]["models"] != first["parts"]["models"] - assert second["parts"]["eval_agent/probing"] == first["parts"]["eval_agent/probing"] + assert second["parts"]["eval_agent/triage"] == first["parts"]["eval_agent/triage"] assert second["git"] == {"commit": "0123456789abcdef", "dirty": True} assert code_label(second) == f"code tree `{second['tree']}`, commit `0123456789` + uncommitted changes" assert code_label(None) == "code not recorded" def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): - from evalrx.eval_agent.probing.ledger import Ledger + from evalrx.eval_agent.triage.ledger import Ledger from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") @@ -868,7 +868,7 @@ def test_per_call_sampling_is_requested_only_where_the_backend_honours_it(): def test_metered_model_counts_batch_calls_per_input(): - from evalrx.eval_agent.probing.metering import MeteredModel + from evalrx.eval_agent.triage.metering import MeteredModel class Batched: def generate_batch(self, inputs, **kwargs): diff --git a/tests/test_eval_agent/test_probing_mvp3.py b/tests/test_eval_agent/test_triage_scoring.py similarity index 95% rename from tests/test_eval_agent/test_probing_mvp3.py rename to tests/test_eval_agent/test_triage_scoring.py index 4070630c..691957cb 100644 --- a/tests/test_eval_agent/test_probing_mvp3.py +++ b/tests/test_eval_agent/test_triage_scoring.py @@ -13,12 +13,12 @@ import json -from evalrx.eval_agent.probing import BATTERY, LAYERS, run_triage -from evalrx.eval_agent.probing.actions import OK, UNFAITHFUL, UNSUPPORTED, Observation -from evalrx.eval_agent.probing.compare import compare -from evalrx.eval_agent.probing.evidence import StepEvidence -from evalrx.eval_agent.probing.rules import candidate_steps -from evalrx.eval_agent.probing.scoring import ( +from evalrx.eval_agent.triage import BATTERY, LAYERS, run_triage +from evalrx.eval_agent.triage.actions import OK, UNFAITHFUL, UNSUPPORTED, Observation +from evalrx.eval_agent.triage.compare import compare +from evalrx.eval_agent.triage.evidence import StepEvidence +from evalrx.eval_agent.triage.rules import candidate_steps +from evalrx.eval_agent.triage.scoring import ( Scored, availability, choose, @@ -26,7 +26,7 @@ per_case_costs, step_cost, ) -from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _Table +from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _Table def _step(key): @@ -158,8 +158,8 @@ def test_scored_run_is_traceable_deterministic_on_resume_and_comparable_with_the def test_scored_runs_a_batch_dependent_step_once_after_the_last_expansion(tmp_path): - from evalrx.eval_agent.probing.actions import PlanStep - from evalrx.eval_agent.probing.rules import Layer + from evalrx.eval_agent.triage.actions import PlanStep + from evalrx.eval_agent.triage.rules import Layer cases, table = _pope_like() batchy = PlanStep("prompt_contrast", {"strategies": {"baseline": "{prompt}", "q": "Q: {prompt}"}}, "Z", diff --git a/tests/test_eval_agent/test_probing_validation.py b/tests/test_eval_agent/test_triage_validation.py similarity index 97% rename from tests/test_eval_agent/test_probing_validation.py rename to tests/test_eval_agent/test_triage_validation.py index 3b6d59b5..78355c20 100644 --- a/tests/test_eval_agent/test_probing_validation.py +++ b/tests/test_eval_agent/test_triage_validation.py @@ -21,11 +21,11 @@ import pytest -from evalrx.eval_agent.probing import LAYERS, explore_confirm_split, run_triage -from evalrx.eval_agent.probing.controller import BATTERY -from evalrx.eval_agent.probing.explanations import CARDS, Metric, label_bound -from evalrx.eval_agent.probing.rules import Layer, candidate_steps -from evalrx.eval_agent.probing.validation import ( +from evalrx.eval_agent.triage import LAYERS, explore_confirm_split, run_triage +from evalrx.eval_agent.triage.controller import BATTERY +from evalrx.eval_agent.triage.explanations import CARDS, Metric, label_bound +from evalrx.eval_agent.triage.rules import Layer, candidate_steps +from evalrx.eval_agent.triage.validation import ( ALPHA, IssueRecord, credit_arms, @@ -37,8 +37,8 @@ validate, within_group_rho, ) -from tests.test_eval_agent.test_probing_alternatives import FIRST, _Flipper -from tests.test_eval_agent.test_probing_mvp2 import _kw, _pope_like, _yes_no +from tests.test_eval_agent.test_triage_alternatives import FIRST, _Flipper +from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _yes_no SEED = 7 @@ -197,7 +197,7 @@ def test_an_effect_that_holds_on_new_cases_is_supported_and_frozen_before_valida assert (tmp_path / "validation" / "selection_trace.jsonl").is_file() assert "## Arms" in (tmp_path / "validation" / "validation_report.md").read_text() # both reports and every planned action say which code ran - from evalrx.eval_agent.probing.controller import code_version + from evalrx.eval_agent.triage.controller import code_version assert out["code"] == report["code"] == code_version() assert all(e["code"] == out["code"]["tree"] for e in planned) From e17ffc7fc4f62ba499f9290950f04dbf6a5c87ab Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:11:12 -0700 Subject: [PATCH 24/26] Drop the triage's comparison-only switches and default to the scored scheduler The switches that existed to compare schedulers against each other are gone: --triage-scheduler random|cheapest, --triage-explore-from and --triage-weights (run_triage keeps its weights argument), and with them the report comparison module (eval_agent.triage.compare). The rules scheduler and the judge's competing explanations stay. Defaults are the configuration the comparisons settled on: --triage-scheduler scored (was rules), --triage-max-fail 128 (was 32), --triage-max-actions 30 (was 12). The interval and rank statistics the triage carried move to evalrx/stats/intervals.py: z_quantile, t_quantile, wilson_interval, newcombe_interval (was difference_interval), average_ranks and within_group_spearman (was within_group_rho). Version strings lose their milestone prefixes (rules-5, score-5, explain-6, validate-5, policy-2), and a report no longer has an explore_from key. --- evalrx/benchmark/run.py | 40 ++---- evalrx/benchmark/runner.py | 10 +- evalrx/eval_agent/triage/__init__.py | 16 +-- evalrx/eval_agent/triage/actions.py | 2 +- evalrx/eval_agent/triage/compare.py | 135 ------------------ evalrx/eval_agent/triage/controller.py | 76 ++++------ evalrx/eval_agent/triage/explanations.py | 80 +---------- evalrx/eval_agent/triage/routes.py | 22 +-- evalrx/eval_agent/triage/rules.py | 13 +- evalrx/eval_agent/triage/scoring.py | 51 ++----- evalrx/eval_agent/triage/validation.py | 48 +------ evalrx/stats/intervals.py | 130 +++++++++++++++++ tests/test_analysis/test_run_cli.py | 13 +- .../test_triage_alternatives.py | 12 +- tests/test_eval_agent/test_triage_chunks.py | 31 ---- .../test_eval_agent/test_triage_expansion.py | 13 +- .../test_triage_explanations.py | 21 +-- tests/test_eval_agent/test_triage_routes.py | 28 ++-- tests/test_eval_agent/test_triage_scoring.py | 70 +++------ .../test_eval_agent/test_triage_validation.py | 10 +- tests/test_stats/test_intervals.py | 50 +++++++ 21 files changed, 312 insertions(+), 559 deletions(-) delete mode 100644 evalrx/eval_agent/triage/compare.py create mode 100644 evalrx/stats/intervals.py create mode 100644 tests/test_stats/test_intervals.py diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 1dd718e1..0bbbb189 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -155,24 +155,24 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP p.add_argument("--m1-policy", choices=["judge", "triage_active"], default="judge", help="judge = the current diagnosis (decision judge over M1-M4, then M5/fix); " "triage_active = triage controller: after Stage 0, run the triage battery " - "strictly on a matched EXPLORE sample, expand it and run route follow-ups " - "chosen by fixed rules, write the trace, cost ledger and triage report " + "strictly on a matched EXPLORE sample, then expand it and run route follow-ups one " + "action at a time (--triage-scheduler), write the trace, cost ledger and triage report " "under /probing/, and stop. M2-M5 do not run; a judge is built only with " "--triage-explanations judge; the controller never sees CONFIRM (only " "--triage-validate reads it, after the stop)") p.add_argument("--triage-n-fail", type=int, default=8, help="triage_active: FAIL cases in the sample (PASS controls are matched per gold answer)") - p.add_argument("--triage-max-fail", type=int, default=32, + p.add_argument("--triage-max-fail", type=int, default=128, help="triage_active: the most FAIL cases the expansion rule may grow the sample to " "(doubling from --triage-n-fail; a value at or below it disables expansion)") - p.add_argument("--triage-max-actions", type=int, default=12, + p.add_argument("--triage-max-actions", type=int, default=30, help="triage_active: decisions after the battery (expansions + route follow-ups; the " "scored scheduler's further chunks of a step it already took do not count)") - p.add_argument("--triage-scheduler", choices=["rules", "scored", "random", "cheapest"], default="rules", - help="triage_active: rules = MVP-2 fixed rounds over the routes' layers; scored = MVP-3 " - "value per cost, U = q*[D+T+C-R]+/(c+eps) (report: triage_report.scored.*); random / " - "cheapest = controls over the scored candidates and stop rules that differ in the pick " - "only (a seeded uniform draw, or the lowest cost), never exploring") + p.add_argument("--triage-scheduler", choices=["scored", "rules"], default="scored", + help="triage_active: scored = the candidate with the highest value per cost, " + "U = q*[D+T+C-R]+/(c+eps), with a share of the spending for exploration (report: " + "triage_report.scored.*); rules = fixed rounds over the routes' layers, no value " + "estimate and no exploration (report: triage_report.*)") p.add_argument("--triage-budget-usd", type=float, default=0.0, help="triage_active: USD cap on priced API models (0 = none), charged like " "--triage-budget-sec") @@ -185,16 +185,9 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "--judge-model judge proposes competing explanations with predictions once the " "sample has settled (and again when the evidence thins them), giving D (none = D " "stays 0, no judge is built)") - p.add_argument("--triage-weights", default="d=1,t=1,c=1,r=1", - help="triage_active with --triage-scheduler scored: the weights of D, T, C and R in U, " - "as k=v pairs (keys left out keep 1; an ablation sets one to 0)") p.add_argument("--triage-explore-share", type=float, default=0.1, help="triage_active with --triage-scheduler scored: the share of the evidence spending " "exploration may take (0 = none)") - p.add_argument("--triage-explore-from", choices=["targets", "candidates"], default="targets", - help="triage_active with --triage-scheduler scored: what exploration draws from: targets = " - "inactive routes' next candidates and other routes' representatives (actions the value " - "never takes); candidates = the candidates other than the best (an ablation)") p.add_argument("--triage-validate", action=argparse.BooleanOptionalAction, default=False, help="triage_active: freeze the issues the triage report supports and validate them once on " "the CONFIRM cases whose media EXPLORE does not contain (/validation/)") @@ -287,7 +280,6 @@ def run_args(args) -> int: if triage and args.triage_max_actions < 0: raise ValueError("--triage-max-actions must be non-negative") if triage: - triage_weights(args.triage_weights) if not 0.0 <= args.triage_explore_share < 1.0: raise ValueError("--triage-explore-share must be in [0, 1)") dataset = args.dataset or T.DEFAULT_TASK[args.modality] @@ -301,19 +293,5 @@ def run_args(args) -> int: return run(args, task, resolved) -def triage_weights(text: str) -> dict[str, float]: - """``"d=1,t=1,c=0"`` -> ``{"d": 1.0, "t": 1.0, "c": 0.0, "r": 1.0}``: the scored scheduler's weights.""" - out = {"d": 1.0, "t": 1.0, "c": 1.0, "r": 1.0} - for part in filter(None, (x.strip() for x in str(text).split(","))): - key, sep, value = part.partition("=") - key = key.strip().lower() - if not sep or key not in out: - raise ValueError(f"--triage-weights: {part!r} is not one of d=, t=, c=, r=") - out[key] = float(value) - if out[key] < 0: - raise ValueError(f"--triage-weights: {key} must be non-negative") - return out - - if __name__ == "__main__": raise SystemExit(main()) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 14453916..add5f508 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -733,8 +733,8 @@ def _validation_source(args, task: T.Task, model, gen_kwargs: dict, protocol, ru def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: dict, cases, ctx, run_dir: Path, baseline: dict, source=None) -> int: - """``--m1-policy triage_active``: the triage battery, rule-chosen expansions and - follow-ups on EXPLORE, then stop. + """``--m1-policy triage_active``: the triage battery, then expansions and + follow-ups on EXPLORE one action at a time, then stop. Same Stage 0 and the same EXPLORE/CONFIRM split as the diagnosis loop; the controller sees EXPLORE only and runs no M2-M5; it calls the judge only with @@ -749,11 +749,8 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: DIAGNOSTIC_VALIDATION (``/validation/``). """ from evalrx.eval_agent.triage import explore_confirm_split, run_triage - from evalrx.eval_agent.triage.scoring import Weights from evalrx.eval_agent.triage.validation import freeze_issues, partition_bundle, validate - from .run import triage_weights - explore, confirm = explore_confirm_split(cases, float(args.confirm_split), CONFIRM_SPLIT_SEED, by=args.confirm_split_by) bundle, validation = partition_bundle(explore, confirm, seed=CONFIRM_SPLIT_SEED, @@ -803,8 +800,7 @@ def _run_triage(args, task: T.Task, resolved: Resolved, spec, model, gen_kwargs: "n_cases": baseline["n"], **{k: baseline[k] for k in ("api_usage", "usd") if k in baseline}}, scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, - weights=Weights(**triage_weights(args.triage_weights)), explore_share=float(args.triage_explore_share), - explore_from=args.triage_explore_from, + explore_share=float(args.triage_explore_share), partition={"confirm_split": float(args.confirm_split), "split_by": args.confirm_split_by, "seed": CONFIRM_SPLIT_SEED, "n_explore": len(explore), "n_confirm": len(confirm) if confirm is not None else 0, diff --git a/evalrx/eval_agent/triage/__init__.py b/evalrx/eval_agent/triage/__init__.py index 8680e48b..5f77ecbd 100644 --- a/evalrx/eval_agent/triage/__init__.py +++ b/evalrx/eval_agent/triage/__init__.py @@ -2,17 +2,18 @@ The default M1 lets the decision judge pick a batch of analyzers, which ``ProbeAgent`` may then backfill, cap, or extend with generated probes. This -package is the opt-in alternative from ``evalsmith/probing/probing_design_mix.md``: +package is the opt-in alternative (``docs/agentic_benchmark.md`` describes a run): a host-side controller that runs one explicit action at a time, on exactly the cases and configuration it planned, and records why each action ran, what it cost, and whether its measurement can be trusted. A run draws a matched, nested sample of EXPLORE, runs a fixed battery on it, and then decides one action at a time between expanding the sample and the routes' -follow-ups: by fixed rules, by value (optionally with competing explanations a -judge proposes, which give the value its D), or by the random and cheapest-first -controls. The issues a report supports can be frozen and validated once on cases -the controller never saw. +follow-ups: by value (optionally with competing explanations a judge proposes, +which give the value its D) or by fixed rules. The issues a report supports can +be frozen and validated once on cases the controller never saw. + +Not :mod:`evalrx.probing`, the probe catalog and router the judge-driven M1 calls. partition.py the EXPLORE/CONFIRM split the diagnosis loop uses, or one by media content sampler.py matched, nested FAIL/PASS sample (S8 ⊆ S16 ⊆ S32 ...) @@ -21,13 +22,12 @@ executor.py strict execution: capability gate, typed outcome, no backfill ledger.py append-only selection_trace.jsonl / cost_ledger.jsonl + resume evidence.py one step's observations over a growing sample (per-case reuse) - triage.py H/N/U/S/X route labels traced back to case, field and action + routes.py H/N/U/S/X route labels traced back to case, field and action rules.py route layers, follow-up choice, and the expansion rule - scoring.py the scored scheduler's value of a candidate, and the controls' pick + scoring.py the scored scheduler's value of a candidate and its pick explanations.py competing explanations, their predictions and D controller.py the battery, the schedulers and run_triage() validation.py the data roles, frozen issues and their one validation - compare.py two arms' reports side by side (also a CLI) Nothing here is imported by the default ``judge`` path. """ diff --git a/evalrx/eval_agent/triage/actions.py b/evalrx/eval_agent/triage/actions.py index 2014c5fe..f0f275f8 100644 --- a/evalrx/eval_agent/triage/actions.py +++ b/evalrx/eval_agent/triage/actions.py @@ -147,7 +147,7 @@ class ProbeAction: case_ids: tuple[str, ...] route: str purpose: str - source: str = "mvp0_fixed_order" + source: str = "battery" reserve: dict[str, int] = field(default_factory=dict) def identity(self, context: dict[str, Any]) -> str: diff --git a/evalrx/eval_agent/triage/compare.py b/evalrx/eval_agent/triage/compare.py deleted file mode 100644 index 845347af..00000000 --- a/evalrx/eval_agent/triage/compare.py +++ /dev/null @@ -1,135 +0,0 @@ -"""Two schedulers' runs side by side: what each chose, in what order, at what evidence cost. - -Both runs may share one ledger, so a scheduler that runs second reads most -observations back. Cost is therefore compared on the evidence each report -was built from, at the cost the observation had when it was first executed -(``cost.evidence``), not on what the second invocation happened to spend. -""" - -from __future__ import annotations - -import argparse -import json -from itertools import combinations -from pathlib import Path -from typing import Any - -from evalrx.eval_agent.triage.explanations import CARDS, primary_readings, verdict - - -def discrimination(explained: dict[str, Any], report: dict[str, Any]) -> dict[str, Any]: - """How many pairs of *explained*'s last explanations (per route) with conflicting predictions - *report*'s evidence tells apart: one of the pair misses on a reading they conflict on. - - Applies one run's explanations to another run's final ``outcomes``, so two - schedulers are compared on the same explanations whichever of them asked.""" - sets = [s for s in (explained.get("explanations") or {}).get("sets") or [] if s["hypotheses"]] - if not sets: - return {"revision": None, "n_conflicting_pairs": 0, "n_resolved": 0, "pairs": []} - last, outcomes = sets[-1], report.get("outcomes") or {} - bands = {(key, m.field): m.band for key, ms in CARDS.items() for m in ms} - pairs = [] - for a, b in combinations(last["hypotheses"], 2): - if a["route"] != b["route"]: - continue - decisive = primary_readings(a) | primary_readings(b) - on = [(step, f) for step in sorted(set(a["predictions"]) & set(b["predictions"])) - for f in sorted(set(a["predictions"][step]) & set(b["predictions"][step])) - if a["predictions"][step][f] != b["predictions"][step][f] and (step, f) in decisive] - if not on: - continue - resolved = [f"{step}.{f}" for step, f in on - if any(verdict(h["predictions"][step][f], - ((outcomes.get(a["route"]) or {}).get(step) or {}).get(f, {}).get("ci95"), - bands[(step, f)]) == "miss" for h in (a, b))] - pairs.append({"route": a["route"], "pair": [a["id"], b["id"]], "on": [f"{s}.{f}" for s, f in on], - "resolved_on": resolved}) - return {"revision": last["revision"], "n_conflicting_pairs": len(pairs), - "n_resolved": sum(1 for x in pairs if x["resolved_on"]), "pairs": pairs} - - -def _followed(report: dict[str, Any]) -> list[tuple[str, str, str]]: - return [(d.get("route") or "-", d.get("rule_id") or "-", d.get("key") or d["kind"]) - for d in report["decisions"] if d["kind"] in ("expand", "follow_up", "extend", "battery")] - - -def compare(baseline: dict[str, Any], other: dict[str, Any]) -> dict[str, Any]: - """Selection and cost differences of *other* against the *baseline* run (both triage reports).""" - a, b = _followed(baseline), _followed(other) - def open_units(r: dict[str, Any]) -> list[dict[str, Any]]: # units some tool could still close here - return [u for u in (r.get("coverage") or {}).values() if u.get("layer_state") != "exhausted"] - - gap = {name: sum(u["gap"] for u in open_units(r)) for name, r in (("baseline", baseline), ("other", other))} - units = {name: len(open_units(r)) for name, r in (("baseline", baseline), ("other", other))} - out = { - "schedulers": [baseline.get("scheduler", "rules"), other.get("scheduler", "rules")], - "same_sample": baseline["sample"]["case_ids"] == other["sample"]["case_ids"], - "actions": {"baseline": a, "other": b}, - "only_baseline": [x for x in a if x not in b], - "only_other": [x for x in b if x not in a], - "same_order": a == b, - "evidence_cost": {"baseline": (baseline.get("cost") or {}).get("evidence"), - "other": (other.get("cost") or {}).get("evidence")}, - "charged": {"baseline": (baseline.get("cost") or {}).get("charged"), - "other": (other.get("cost") or {}).get("charged")}, - "judge": {"baseline": (baseline.get("cost") or {}).get("judge"), - "other": (other.get("cost") or {}).get("judge")}, - "controller_sec": {"baseline": (baseline.get("cost") or {}).get("controller_sec"), - "other": (other.get("cost") or {}).get("controller_sec")}, - "coverage_gap": gap, "coverage_units": units, - "alternatives": {name: [f"{d['route']}:{d['rule_id']}:{d['key']} (to {d['alternative_to']})" - for d in r["decisions"] if d.get("alternative_to") and d["kind"] == "follow_up"] - for name, r in (("baseline", baseline), ("other", other))}, - "explored": {name: {"decisions": sum(1 for d in r["decisions"] if d.get("choice") == "explore"), - **(r.get("explored") or {})} for name, r in (("baseline", baseline), ("other", other))}, - "stop": {"baseline": baseline["stop"], "other": other["stop"]}, - } - source = next((r for r in (other, baseline) if r.get("explanations")), None) - if source is not None: # both runs' evidence, on the same explanations - out["discrimination"] = {"baseline": discrimination(source, baseline), "other": discrimination(source, other)} - return out - - -def markdown(diff: dict[str, Any]) -> str: - a_name, b_name = diff["schedulers"] - lines = [f"# Scheduler comparison: {a_name} vs {b_name}", "", - f"Same final sample: {diff['same_sample']}. Same actions in the same order: {diff['same_order']}.", "", - f"| | {a_name} | {b_name} |", "|---|---|---|"] - rows = max(len(diff["actions"]["baseline"]), len(diff["actions"]["other"])) - for i in range(rows): - cells = [":".join(x[i]) if i < len(x) else "" for x in (diff["actions"]["baseline"], diff["actions"]["other"])] - lines.append(f"| {i} | {cells[0]} | {cells[1]} |") - ev = diff["evidence_cost"] - lines += ["", f"Evidence cost (first execution of every observation read): {a_name} {ev['baseline']}; " - f"{b_name} {ev['other']}.", - f"Charged against the budget (evidence plus judge calls): {diff['charged']}; judge: {diff['judge']}.", - f"Controller time outside the actions and the judge: {diff['controller_sec']}.", - f"Coverage gap left on units some tool can close here (sum): {diff['coverage_gap']} of " - f"{diff['coverage_units']} units.", - f"Alternatives run on answered layers: {diff['alternatives']}; exploration: {diff['explored']}.", - f"Stop: {diff['stop']}.", ""] - if "discrimination" in diff: - d = diff["discrimination"] - lines += [f"Pairs of competing explanations (the explaining run's last set) each run's evidence tells " - f"apart: {a_name} {d['baseline']['n_resolved']}/{d['baseline']['n_conflicting_pairs']}, " - f"{b_name} {d['other']['n_resolved']}/{d['other']['n_conflicting_pairs']}.", ""] - return "\n".join(lines) - - -def main(argv: "list[str] | None" = None) -> int: - """``python -m evalrx.eval_agent.triage.compare [--json]``: two arms' - triage reports side by side, as Markdown (default) or as the JSON diff.""" - p = argparse.ArgumentParser(description="two triage reports side by side: selection order, evidence cost, " - "coverage and, with an explaining run, the explanations told apart") - p.add_argument("baseline", type=Path, help="the baseline arm's triage_report*.json") - p.add_argument("other", type=Path, help="the other arm's triage_report*.json") - p.add_argument("--json", action="store_true", help="print the diff as JSON instead of Markdown") - args = p.parse_args(argv) - diff = compare(json.loads(args.baseline.read_text(encoding="utf-8")), - json.loads(args.other.read_text(encoding="utf-8"))) - print(json.dumps(diff, indent=2, default=str) if args.json else markdown(diff)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/evalrx/eval_agent/triage/controller.py b/evalrx/eval_agent/triage/controller.py index 9cde3d43..66e7ed9f 100644 --- a/evalrx/eval_agent/triage/controller.py +++ b/evalrx/eval_agent/triage/controller.py @@ -57,16 +57,16 @@ step's own measured cost per case, else the most expensive case measured in this run; there is no per-analyzer cost prior). -Four schedulers decide after the battery (``scheduler``): ``rules`` (rounds over -the routes' soft layer order; no judge, no hypothesis), ``scored`` (the candidate -of highest value, :mod:`.scoring`), and the controls ``random`` and ``cheapest`` -over the same candidates. The scored scheduler may take an explainer: the judge +Two schedulers decide after the battery (``scheduler``): ``scored`` (the candidate +of highest value, :mod:`.scoring`; the default) and ``rules`` (rounds over the +routes' soft layer order; no value estimate, no judge, no hypothesis). The scored +scheduler may take an explainer: the judge then proposes competing explanations once the sample has settled, and their predictions give each candidate its D (:mod:`.explanations`); no explanation is a finding. CONFIRM never enters the controller (:mod:`.validation` reads it after the stop, when asked). Outputs land in ``out_dir``:: - split_manifest.json triage_report[.[_d]].json triage_report[.[_d]].md + split_manifest.json triage_report[.scored[_d]].json triage_report[.scored[_d]].md selection_trace.jsonl cost_ledger.jsonl observations/.json explanations/.json (with an explainer: each judge call's prompt, reply and cost) """ @@ -159,11 +159,9 @@ #: Part of every action identity (with the model identity and the tool version): bumped only #: when the controller changes what an action executes or records, never for a rename, since a -#: bump re-executes every stored observation on resume. The label dates from MVP-2. -POLICY_VERSION = "mvp2-0" -SCHEDULERS = ("rules", "scored", "random", "cheapest") -#: The schedulers that decide over the scored candidate pool: the value, or a control differing in the pick only. -VALUE_SCHEDULERS = ("scored", "random", "cheapest") +#: bump re-executes every stored observation on resume. +POLICY_VERSION = "policy-2" +SCHEDULERS = ("scored", "rules") #: Neutral wrappers around the question, kept verbatim (with its output #: contract): the meaning cannot change, only the surface. A wrapper whose @@ -659,7 +657,7 @@ def run_triage( model_identity: dict[str, Any], n_fail: int = 8, max_fail: "int | None" = None, - max_actions: int = 12, + max_actions: int = 30, min_route_fail: int = 3, min_cohort: int = 8, seed: int = 0, @@ -678,10 +676,9 @@ def run_triage( stage0_cost: "dict[str, Any] | None" = None, partition: "dict[str, Any] | None" = None, per_call_generation: bool = True, - scheduler: str = "rules", + scheduler: str = "scored", weights: "Weights | None" = None, explore_share: float = 0.1, - explore_from: str = "targets", min_gain: float = 0.01, min_cover: int = 8, budget_usd: float = 0.0, @@ -715,7 +712,7 @@ def run_triage( with a counterfactual donor. Donors are drawn from the whole of *explore*, never from outside it. Elsewhere the same holds per case for an answer that is a common gold - of *explore* (:func:`~.routes.common_answers`). + of *explore* (:func:`~.triage.common_answers`). task_kind: the task's kind; steps limited to other kinds are recorded as ``not_applicable`` and not run. answer_fn: ``(case, output) -> answer key`` (``""`` = no readable @@ -739,20 +736,14 @@ def run_triage( OpenAI-compatible endpoint drops them): when it does not, steps run without their ``gen_kwargs`` and are gated on the host's output cap. - scheduler: ``"rules"`` (MVP-2: rounds over the routes' soft layer order); - ``"random"`` / ``"cheapest"``: controls over the scored scheduler's - candidates and stop rules, differing in the pick only (a seeded - uniform draw, or the lowest cost); they never explore and take no - explainer (report ``triage_report.random`` / ``.cheapest``) - or ``"scored"`` (MVP-3: the candidate with the highest - U = q·[D+T+C−R]₊/(c+ε), see :mod:`.scoring`). Both share - the ledger; the scored report is ``triage_report.scored``. + scheduler: ``"scored"`` (the candidate with the highest + U = q·[D+T+C−R]₊/(c+ε), see :mod:`.scoring`; report + ``triage_report.scored``) or ``"rules"`` (fixed rounds over the + routes' layers in their soft order, no value estimate; report + ``triage_report``). Both share the ledger. weights, explore_share, min_gain, min_cover: the scored scheduler's weights, exploration's share of the evidence spending, value floor and per-unit coverage target. - explore_from: ``"targets"`` (exploration takes inactive routes' next candidates - and other routes' representatives, see :mod:`.scoring`) or - ``"candidates"`` (an ablation: the candidates other than the top). budget_usd: USD cap (0 = none), charged like ``budget_sec`` and checked with the step's earlier USD per case. chunk: cases per chunk of a ``reuse`` step (FAIL and PASS alternating; @@ -771,9 +762,7 @@ def run_triage( raise ValueError(f"scheduler must be one of {SCHEDULERS}; got {scheduler!r}") if explainer is not None and scheduler != "scored": raise ValueError("explanations give D to the scored scheduler; the other schedulers do not read them") - share = float(explore_share) if scheduler == "scored" else 0.0 # the controls never explore - if explore_from not in ("targets", "candidates"): - raise ValueError(f"explore_from must be 'targets' or 'candidates'; got {explore_from!r}") + share = float(explore_share) if scheduler == "scored" else 0.0 # the fixed rounds never explore weights = weights or Weights() started = time.monotonic() say = progress or (lambda _msg: None) @@ -849,7 +838,7 @@ def n_actions() -> int: """What ``max_actions`` caps: expansions, follow-ups and scheduled battery steps. The scored scheduler's further chunks of a step it already took (``extend``) do not count: chunking a step must not use up the cap a whole step used before.""" - kinds = ("expand", "follow_up", "battery") if scheduler in VALUE_SCHEDULERS else spending + kinds = ("expand", "follow_up", "battery") if scheduler == "scored" else spending return sum(1 for d in decisions if d["kind"] in kinds) def expansion_plan() -> "tuple[Any, Any, list[str], float | None] | None": @@ -1348,8 +1337,7 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], return pool, filtered, axis explored: dict[str, float] = {} # what exploration decisions spent, per cost axis - if scheduler in VALUE_SCHEDULERS: - policy = "value" if scheduler == "scored" else scheduler + if scheduler == "scored": current: "ExplanationSet | None" = None while stop is None: records = triage(sample, run.evidence) @@ -1371,17 +1359,13 @@ def scored_pool(records: list[dict[str, Any]], gaps: list[dict[str, Any]], current.decided_at_ask = _decided(verdicts) live = [h for h in (current.hypotheses if current is not None else []) if verdicts[h.id]["state"] == "live"] pool, filtered, axis = scored_pool(records, gaps, states, options, growing, live, outcome_of) - targets: "list[Scored] | None" = None - held_targets: list[dict[str, Any]] = [] - if explore_from == "targets" and policy == "value": - targets, completions, held, held_targets = exploration_targets(records, states, growing, axis, - outcome_of) - pool, filtered = pool + completions, filtered + held + targets, completions, held, held_targets = exploration_targets(records, states, growing, axis, + outcome_of) + pool, filtered = pool + completions, filtered + held # exploration's share is of the evidence: the judge's calls are not an opportunity to explore spent = run.charged(axis) - float(run.judge_cost.get(axis) or 0.0) pick, why = choose(pool, decision_no=n_spent(), seed=seed, explore_share=share, - explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain, targets=targets, - policy=policy) + explored=explored.get(axis, 0.0), spent=spent, min_gain=min_gain, targets=targets) if pick is None: over = [f for f in filtered if not f["reason"].startswith("batch-dependent")] # a candidate the budget filtered out binds before the gain floor does @@ -1441,7 +1425,7 @@ def account() -> None: # what an exploration decision spent counts against its elif record["status"] == SKIPPED: stop = {"reason": "budget", "detail": record.get("reason")} break - if why == "explore" and targets is not None and pick in targets: + if why == "explore" and pick in targets: explored_on.add((pick.route, pick.key)) if pick.kind != "battery": step_done = (cast(str, pick.route), cast(str, pick.rule_id), pick.key) # a follow-up has both @@ -1542,9 +1526,8 @@ def account() -> None: # what an exploration decision spent counts against its "policy": POLICY_VERSION, "scheduler": scheduler, **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_share": share, - "explore_from": explore_from, "explored": {a: round(v, 6) for a, v in explored.items()}, - "min_gain": min_gain, "min_cover": min_cover} if scheduler in VALUE_SCHEDULERS else {}), + "min_gain": min_gain, "min_cover": min_cover} if scheduler == "scored" else {}), "rules_version": RULES_VERSION, "code": code_version(), "model": model_identity, @@ -1595,18 +1578,13 @@ def _scored_rationale(pick: Scored, why: str, explored: float, spent: float, sha target = f" of {pick.note}" if pick.note else "" return (f"exploration{target} ({explored:.4g} of the {spent:.4g} spent on evidence so far went to " f"exploration; share {share}): " + terms) - if why == "random": - return f"control: a seeded uniform draw among the candidates at or above the gain floor: {terms}" - if why == "cheapest": - return f"control: the cheapest candidate at or above the gain floor: {terms}" alt = f"; an alternative to {pick.alternative_to}" if pick.alternative_to else "" return f"highest value: {terms}{alt}" def report_name(scheduler: str, explained: bool = False) -> str: - """``triage_report`` (rules), ``triage_report.scored``, ``triage_report.scored_d`` (with D), or - ``triage_report.random`` / ``triage_report.cheapest`` (the controls): the arms of a comparison can - share one probing directory and its ledger.""" + """``triage_report.scored``, ``triage_report.scored_d`` (with D) or ``triage_report`` (rules): + runs under different schedulers can share one output directory and its ledger.""" if scheduler == "rules": return "triage_report" return f"triage_report.{scheduler}" + ("_d" if explained else "") diff --git a/evalrx/eval_agent/triage/explanations.py b/evalrx/eval_agent/triage/explanations.py index 30d0ab59..31043ae4 100644 --- a/evalrx/eval_agent/triage/explanations.py +++ b/evalrx/eval_agent/triage/explanations.py @@ -1,4 +1,4 @@ -"""MVP-3b: competing explanations, their predictions per tool, and the D they give a candidate. +"""Competing explanations, their predictions per tool, and the D they give a candidate. The chain's judge (the model ``runner.build_judge`` builds for M1-M5) is asked, for every active route, for up to ``max_per_route`` local explanations of why @@ -84,9 +84,9 @@ from typing import Any, Callable, Iterable from evalrx.eval_agent.triage.metering import usage_counters, usage_delta -from evalrx.eval_agent.triage.routes import difference_interval +from evalrx.stats.intervals import newcombe_interval, t_quantile, z_quantile -EXPLAIN_VERSION = "mvp4-explain-6" +EXPLAIN_VERSION = "explain-6" DIRECTIONS = ("up", "down", "same", "unknown") _ALIASES = {"↑": "up", "↓": "down", "≈": "same", "=": "same", "~": "same", "?": "unknown", "higher": "up", "lower": "down", "increase": "up", "decrease": "down", "none": "unknown"} @@ -216,72 +216,6 @@ def _rate(field_: str, meaning: str, band: float = 0.1) -> Metric: # -- checking predictions -------------------------------------------------------------------- -_T975 = (12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, - 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, - 2.045, 2.042) - - -def _t975(df: float) -> float: - """Two-sided 95% Student-t quantile at ``floor(df)`` (conservative), normal beyond 120.""" - k = max(1, int(math.floor(df))) - if k <= 30: - return _T975[k - 1] - return 2.021 if k < 60 else 2.000 if k < 120 else 1.960 - - -def z_quantile(level: float) -> float: - """Two-sided normal quantile: ``z`` with ``P(|Z| <= z) = level``.""" - from statistics import NormalDist - - return NormalDist().inv_cdf(0.5 + level / 2) - - -def _betacf(a: float, b: float, x: float) -> float: - """Continued fraction of the regularised incomplete beta function (modified Lentz).""" - tiny, qab, qap, qam = 1e-300, a + b, a + 1.0, a - 1.0 - c, d = 1.0, 1.0 - qab * x / qap - d = 1.0 / (d if abs(d) > tiny else tiny) - h = d - for m in range(1, 300): - m2 = 2 * m - for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))): - d = 1.0 + aa * d - d = 1.0 / (d if abs(d) > tiny else tiny) - c = 1.0 + aa / c - c = c if abs(c) > tiny else tiny - h *= d * c - if abs(d * c - 1.0) < 1e-14: - break - return h - - -def _t_two_sided(t: float, k: int) -> float: - """``P(|T| <= t)`` for Student's t with *k* degrees of freedom: ``1 - I_{k/(k+t^2)}(k/2, 1/2)``.""" - x = k / (k + t * t) - a, b = k / 2.0, 0.5 - front = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)) - ibeta = front * _betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1.0 - front * _betacf(b, a, 1 - x) / b - return 1.0 - ibeta - - -def t_quantile(level: float, df: float) -> float: - """Two-sided Student-t quantile at ``floor(df)`` degrees of freedom (conservative): the table - above at 95%, else the CDF (incomplete beta) inverted by bisection, e.g. for a family-wise - adjusted interval.""" - if abs(level - 0.95) < 1e-12: - return _t975(df) - k = max(1, int(math.floor(df))) - lo, hi = 0.0, 1.0 - while _t_two_sided(hi, k) < level: - hi *= 2.0 - for _ in range(200): - mid = (lo + hi) / 2 - lo, hi = (mid, hi) if _t_two_sided(mid, k) < level else (lo, mid) - if hi - lo < 1e-10: - break - return hi - - def _mean(xs: list[float]) -> float: return sum(xs) / len(xs) @@ -293,8 +227,8 @@ def difference(fail: list[float], control: list[float], kind: str, return None diff = _mean(fail) - _mean(control) if kind == "rate": - ci = difference_interval(sum(1 for x in fail if x >= 0.5), len(fail), - sum(1 for x in control if x >= 0.5), len(control), z=z_quantile(level)) + ci = newcombe_interval(sum(1 for x in fail if x >= 0.5), len(fail), + sum(1 for x in control if x >= 0.5), len(control), z=z_quantile(level)) return diff, list(ci or [diff, diff]) vf = sum((x - _mean(fail)) ** 2 for x in fail) / (len(fail) - 1) / len(fail) vc = sum((x - _mean(control)) ** 2 for x in control) / (len(control) - 1) / len(control) @@ -361,7 +295,7 @@ def take(ids: list[str]) -> list[float]: def half_width(n: int) -> float: """The verdict interval's half-width in standard deviations of the reading, with *n* cases on each side of equal spread (Welch's degrees of freedom are then ``2n - 2``).""" - return _t975(2 * n - 2) * math.sqrt(2.0 / n) + return t_quantile(0.95, 2 * n - 2) * math.sqrt(2.0 / n) def spread(groups: "list[list[float]]", kind: str) -> "float | None": @@ -446,7 +380,7 @@ def to_dict(self) -> dict[str, Any]: def primary_readings(h: dict[str, Any]) -> set[tuple[str, str]]: """The (step, reading) pairs an explanation (as a dict) stands or falls on. One written before - explanations named them (``mvp4-explain-3`` and earlier) stands on every explicit prediction.""" + explanations named them stands on every explicit prediction.""" preds = h.get("predictions") or {} named = h.get("primary") if not named: diff --git a/evalrx/eval_agent/triage/routes.py b/evalrx/eval_agent/triage/routes.py index 5cc7c188..427acaa1 100644 --- a/evalrx/eval_agent/triage/routes.py +++ b/evalrx/eval_agent/triage/routes.py @@ -54,6 +54,7 @@ from evalrx.core.case import MEDIA_SLOTS from evalrx.eval_agent.triage.actions import OK, Observation from evalrx.eval_agent.triage.evidence import StepEvidence, pick +from evalrx.stats.intervals import newcombe_interval FIRED, CLEAR, UNTESTED, NOT_APPLICABLE = "fired", "clear", "untested", "not_applicable" @@ -643,25 +644,6 @@ def _s_readings(records: list[dict[str, Any]]) -> dict[str, Any]: return out -def _wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]: - p, z2 = k / n, z * z - centre = (p + z2 / (2 * n)) / (1 + z2 / n) - half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n) - return max(0.0, centre - half), min(1.0, centre + half) - - -def difference_interval(k1: int, n1: int, k2: int, n2: int, z: float = 1.96) -> "list[float] | None": - """Interval of ``k1/n1 - k2/n2`` (Newcombe's hybrid score method; 95% at the default *z*), - ``None`` if a side is empty.""" - if not n1 or not n2: - return None - p1, p2 = k1 / n1, k2 / n2 - (l1, u1), (l2, u2) = _wilson(k1, n1, z), _wilson(k2, n2, z) - d = p1 - p2 - return [round(d - math.sqrt((p1 - l1) ** 2 + (u2 - p2) ** 2), 4), - round(d + math.sqrt((u1 - p1) ** 2 + (p2 - l2) ** 2), 4)] - - def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: """Per-route FAIL/PASS rates on this sample, the S cohort and its descriptive readings. @@ -682,7 +664,7 @@ def summarize(records: list[dict[str, Any]]) -> dict[str, Any]: signal = (round(max(0.0, fail["rate"] - pas["rate"]), 4) if fail["rate"] is not None and pas["rate"] is not None else None) out[tag] = {"fail": fail, "pass": pas, "routing_signal": signal, - "signal_ci95": difference_interval(fail["n_fired"], fail["n_tested"], + "signal_ci95": newcombe_interval(fail["n_fired"], fail["n_tested"], pas["n_fired"], pas["n_tested"])} out["H_any_audit_only"] = { label: _rate(records, label, lambda r: r["H"]["state"]) for label in ("fail", "pass") diff --git a/evalrx/eval_agent/triage/rules.py b/evalrx/eval_agent/triage/rules.py index e076c3db..28a2faec 100644 --- a/evalrx/eval_agent/triage/rules.py +++ b/evalrx/eval_agent/triage/rules.py @@ -1,8 +1,9 @@ -"""MVP-2 rules: what each route runs next, and when the sample is expanded. +"""The rules: what each route runs next, and when the sample is expanded. -Fixed rules, no scores (scoring candidates against each other is MVP-3). They -write down the cold-start prior of the design's method table, so a different -choice is a new rule version rather than an unrecorded preference. +Fixed rules, no scores (:mod:`.scoring` ranks the candidates they offer). They +write down a cold-start prior, the order a route's questions are asked in with +no evidence yet, so a different choice is a new rule version rather than an +unrecorded preference. **Layers.** Each route has ordered layers (the soft layer order). A layer is one question; its candidates are the default representative, then its @@ -47,7 +48,7 @@ from evalrx.eval_agent.triage.actions import PlanStep from evalrx.eval_agent.triage.evidence import StepEvidence -RULES_VERSION = "mvp4-rules-5" +RULES_VERSION = "rules-5" ROUTE_ORDER = ("H", "N", "U", "S", "X") DESCRIBE_STRATEGIES = {"baseline": "{prompt}", "describe_first": _PROMPT_STRATEGIES["describe_first"]} @@ -91,7 +92,7 @@ class Layer: served_by: tuple[str, ...] = () case_filter: "Callable[[dict[str, Any]], bool] | None" = None filter_note: str = "" - source: str = "probing_design_mix.md method table (cold-start prior)" + source: str = "cold-start prior (rules.LAYERS)" LAYERS: tuple[Layer, ...] = ( diff --git a/evalrx/eval_agent/triage/scoring.py b/evalrx/eval_agent/triage/scoring.py index 8c86d36a..446103d2 100644 --- a/evalrx/eval_agent/triage/scoring.py +++ b/evalrx/eval_agent/triage/scoring.py @@ -1,4 +1,4 @@ -"""MVP-3: the value of a candidate action and the scored scheduler's choice. +"""The value of a candidate action and the scored scheduler's choice. U(a | E) = q(a) · [w_D·D(a) + w_T·T(a) + w_C·C(a) − w_R·R(a)]₊ / (c(a) + ε) @@ -73,21 +73,11 @@ reading outside its band: then the step has found something, and its completion is an incomplete step that T values like any other. A gain below ``min_gain`` is not worth an action: the run stops once no candidate reaches it -and no target fits (the minimum exploration is met). ``explore_from="candidates"`` -(an ablation) draws from the candidates other than the top one instead, -alternatives included. - -**Controls.** Two schedulers take the scored scheduler's candidates and stop -rules and differ only in the pick, so a comparison with them isolates the -value ordering: ``random`` draws uniformly (seeded) among the candidates at or -above the gain floor, ``cheapest`` takes the lowest-cost one (an unpriced -candidate last, ties by soft order). Neither explores or reads explanations -(D is 0): their nearest value arm is the scored scheduler without exploration. +and no target fits (the minimum exploration is met). """ from __future__ import annotations -import math import random from dataclasses import dataclass, field from typing import Any @@ -95,7 +85,7 @@ from evalrx.eval_agent.triage.actions import OK, UNSUPPORTED, PlanStep from evalrx.eval_agent.triage.evidence import StepEvidence -SCORING_VERSION = "mvp3-score-5" +SCORING_VERSION = "score-5" @dataclass(frozen=True) @@ -266,40 +256,17 @@ def value(s: Scored, weights: Weights, axis: str) -> Scored: return s -#: How a decision picks among the scored candidates: the value (the scored scheduler) or a control. -POLICIES = ("value", "random", "cheapest") - - def choose(candidates: list[Scored], *, decision_no: int, seed: int, explore_share: float, explored: float, - spent: float, min_gain: float, targets: "list[Scored] | None" = None, - policy: str = "value") -> "tuple[Scored | None, str]": - """The candidate to run, and why: ``best`` / ``explore`` / ``random`` / ``cheapest`` / - ``below_threshold`` / ``none``. + spent: float, min_gain: float, targets: "list[Scored]") -> "tuple[Scored | None, str]": + """The candidate to run, and why: ``best`` / ``explore`` / ``below_threshold`` / ``none``. *explored* and *spent* are what exploration and the run's evidence have cost so far, on the - candidates' cost axis. Exploration draws from *targets*, the candidates only it takes; with - ``targets=None`` it draws from the other candidates instead (below the gain floor, from all - of them). A seeded draw among those that keep exploration within *explore_share* of the - spending runs instead of the best. - - *policy* ``"value"`` is the scored scheduler. The controls take the candidates at or above the - gain floor and never explore: ``"random"`` a seeded uniform draw among them, ``"cheapest"`` - the lowest-cost one (an unpriced candidate last, ties by soft order).""" - if policy not in POLICIES: - raise ValueError(f"policy must be one of {POLICIES}; got {policy!r}") - if policy != "value": - eligible = [s for s in candidates if s.gain >= min_gain] - if not eligible: - return None, "below_threshold" if candidates else "none" - if policy == "random": - return random.Random(f"{seed}:{decision_no}").choice(eligible), "random" - return min(eligible, key=lambda s: (s.cost if s.cost is not None else math.inf, s.order)), "cheapest" + candidates' cost axis. Exploration draws from *targets*, the candidates only it takes: a + seeded draw among those that keep exploration within *explore_share* of the spending runs + instead of the best.""" ranked = sorted(candidates, key=lambda s: (-s.U, s.order)) best = ranked[0] if ranked else None - if targets is None: - others = ranked[1:] if best is not None and best.gain >= min_gain else ranked - else: - others = sorted(targets, key=lambda s: s.order) + others = sorted(targets, key=lambda s: s.order) fits = [s for s in others if explored + (s.cost or 0.0) <= explore_share * (spent + (s.cost or 0.0))] if explore_share > 0 and fits: return random.Random(f"{seed}:{decision_no}").choice(fits), "explore" diff --git a/evalrx/eval_agent/triage/validation.py b/evalrx/eval_agent/triage/validation.py index 27af4354..3f733477 100644 --- a/evalrx/eval_agent/triage/validation.py +++ b/evalrx/eval_agent/triage/validation.py @@ -1,4 +1,4 @@ -"""MVP-4: issues frozen from a diagnosis, validated once on cases the diagnosis never saw. +"""Issues frozen from a diagnosis, validated once on cases the diagnosis never saw. **Partition.** :func:`partition_bundle` fixes the data roles before the controller sees any case. DISCOVERY is the EXPLORE partition the controller @@ -90,16 +90,13 @@ outcome, primary_readings, restates_route, - t_quantile, verdict, - z_quantile, ) from evalrx.eval_agent.triage.ledger import Ledger from evalrx.eval_agent.triage.routes import ( ROUTE_STEPS, commits_to_answers, common_answers, - difference_interval, follow_up_values, triage_cases, ) @@ -112,11 +109,12 @@ route_fail_ids, ) from evalrx.eval_agent.triage.sampler import matched_sample, rank +from evalrx.stats.intervals import newcombe_interval, t_quantile, within_group_spearman, z_quantile if TYPE_CHECKING: from evalrx.core.case import CaseBatch -VALIDATION_VERSION = "mvp4-validate-5" +VALIDATION_VERSION = "validate-5" ALPHA = 0.05 #: A route signal is a difference of shares of cases: the band the CARDS use for shares. ROUTE_BAND = 0.1 @@ -411,8 +409,8 @@ def _route_signal(records: list[dict[str, Any]], tag: str, level: float) -> dict out: dict[str, Any] = {"fail": f"{kf}/{nf}", "pass": f"{kp}/{np_}", "n": [nf, np_]} if nf < MIN_N or np_ < MIN_N: return {**out, "verdict": "unavailable", "reason": f"fewer than {MIN_N} tested cases a side"} - ci = difference_interval(kf, nf, kp, np_, z=z_quantile(level)) - ci95 = difference_interval(kf, nf, kp, np_) + ci = newcombe_interval(kf, nf, kp, np_, z=z_quantile(level)) + ci95 = newcombe_interval(kf, nf, kp, np_) return {**out, "diff": round(kf / nf - kp / np_, 4), "ci": ci, "ci95": ci95, "verdict": _verdict("up", ci, ROUTE_BAND)} @@ -420,40 +418,6 @@ def _route_signal(records: list[dict[str, Any]], tag: str, level: float) -> dict # -- phenomena ------------------------------------------------------------------------------------------ -def _ranks(xs: list[float]) -> list[float]: - """Ranks with ties averaged.""" - order = sorted(range(len(xs)), key=lambda i: xs[i]) - out = [0.0] * len(xs) - i = 0 - while i < len(order): - j = i - while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]: - j += 1 - for k in range(i, j + 1): - out[order[k]] = (i + j) / 2 - i = j + 1 - return out - - -def within_group_rho(a: dict[str, float], b: dict[str, float], groups: list[list[str]]) -> "float | None": - """Spearman correlation of two per-case readings inside each group of cases, pooled: ranks are - taken and centred within a group, so a shift between the groups does not count. ``None`` when no - group has ``MIN_PAIRED`` cases with both readings, or a reading is constant within every group.""" - sxy = sxx = syy = 0.0 - for ids in groups: - both = [c for c in ids if c in a and c in b] - if len(both) < MIN_PAIRED: - continue - ra, rb = _ranks([a[c] for c in both]), _ranks([b[c] for c in both]) - ma, mb = sum(ra) / len(ra), sum(rb) / len(rb) - sxy += sum((x - ma) * (y - mb) for x, y in zip(ra, rb)) - sxx += sum((x - ma) ** 2 for x in ra) - syy += sum((y - mb) ** 2 for y in rb) - if sxx <= 0 or syy <= 0: - return None - return sxy / math.sqrt(sxx * syy) - - def group_phenomena(family: list[IssueRecord], results: dict[str, dict[str, Any]], per_case: dict[str, tuple[dict[str, float], list[str], list[str]]] ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: @@ -467,7 +431,7 @@ def group_phenomena(family: list[IssueRecord], results: dict[str, dict[str, Any] if a.route != b.route: continue va, fail_ids, controls = per_case[a.issue_id] - rho = within_group_rho(va, per_case[b.issue_id][0], [fail_ids, controls]) + rho = within_group_spearman(va, per_case[b.issue_id][0], [fail_ids, controls], min_pairs=MIN_PAIRED) if rho is not None: links.append({"issues": [a.issue_id, b.issue_id], "rho": round(rho, 3)}) root = _components([i.issue_id for i in family], links, SAME_PHENOMENON_RHO) diff --git a/evalrx/stats/intervals.py b/evalrx/stats/intervals.py new file mode 100644 index 00000000..23221d41 --- /dev/null +++ b/evalrx/stats/intervals.py @@ -0,0 +1,130 @@ +"""Closed-form intervals and quantiles, in the standard library only. + +For code that needs an interval at a level other than 95% (a family-wise adjusted one) +without resampling: the two-sided normal and Student-t quantiles, the Wilson interval of +a rate, Newcombe's interval of a difference of two rates, and a rank correlation taken +within groups. +""" + +from __future__ import annotations + +import math +from statistics import NormalDist + +_T975 = (12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, + 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, + 2.045, 2.042) + + +def _t975(df: float) -> float: + """Two-sided 95% Student-t quantile at ``floor(df)`` (conservative), normal beyond 120.""" + k = max(1, int(math.floor(df))) + if k <= 30: + return _T975[k - 1] + return 2.021 if k < 60 else 2.000 if k < 120 else 1.960 + + +def z_quantile(level: float) -> float: + """Two-sided normal quantile: ``z`` with ``P(|Z| <= z) = level``.""" + return NormalDist().inv_cdf(0.5 + level / 2) + + +def _betacf(a: float, b: float, x: float) -> float: + """Continued fraction of the regularised incomplete beta function (modified Lentz).""" + tiny, qab, qap, qam = 1e-300, a + b, a + 1.0, a - 1.0 + c, d = 1.0, 1.0 - qab * x / qap + d = 1.0 / (d if abs(d) > tiny else tiny) + h = d + for m in range(1, 300): + m2 = 2 * m + for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))): + d = 1.0 + aa * d + d = 1.0 / (d if abs(d) > tiny else tiny) + c = 1.0 + aa / c + c = c if abs(c) > tiny else tiny + h *= d * c + if abs(d * c - 1.0) < 1e-14: + break + return h + + +def _t_two_sided(t: float, k: int) -> float: + """``P(|T| <= t)`` for Student's t with *k* degrees of freedom: ``1 - I_{k/(k+t^2)}(k/2, 1/2)``.""" + x = k / (k + t * t) + a, b = k / 2.0, 0.5 + front = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)) + ibeta = front * _betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1.0 - front * _betacf(b, a, 1 - x) / b + return 1.0 - ibeta + + +def t_quantile(level: float, df: float) -> float: + """Two-sided Student-t quantile at ``floor(df)`` degrees of freedom (conservative): the table + above at 95%, else the CDF (incomplete beta) inverted by bisection, e.g. for a family-wise + adjusted interval.""" + if abs(level - 0.95) < 1e-12: + return _t975(df) + k = max(1, int(math.floor(df))) + lo, hi = 0.0, 1.0 + while _t_two_sided(hi, k) < level: + hi *= 2.0 + for _ in range(200): + mid = (lo + hi) / 2 + lo, hi = (mid, hi) if _t_two_sided(mid, k) < level else (lo, mid) + if hi - lo < 1e-10: + break + return hi + + +def wilson_interval(k: int, n: int, z: float = 1.96) -> tuple[float, float]: + """Wilson score interval of the rate ``k/n`` (95% at the default *z*).""" + p, z2 = k / n, z * z + centre = (p + z2 / (2 * n)) / (1 + z2 / n) + half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n) + return max(0.0, centre - half), min(1.0, centre + half) + + +def newcombe_interval(k1: int, n1: int, k2: int, n2: int, z: float = 1.96) -> "list[float] | None": + """Interval of ``k1/n1 - k2/n2`` (Newcombe's hybrid score method; 95% at the default *z*), + ``None`` if a side is empty.""" + if not n1 or not n2: + return None + p1, p2 = k1 / n1, k2 / n2 + (l1, u1), (l2, u2) = wilson_interval(k1, n1, z), wilson_interval(k2, n2, z) + d = p1 - p2 + return [round(d - math.sqrt((p1 - l1) ** 2 + (u2 - p2) ** 2), 4), + round(d + math.sqrt((u1 - p1) ** 2 + (p2 - l2) ** 2), 4)] + + +def average_ranks(xs: list[float]) -> list[float]: + """Ranks with ties averaged.""" + order = sorted(range(len(xs)), key=lambda i: xs[i]) + out = [0.0] * len(xs) + i = 0 + while i < len(order): + j = i + while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]: + j += 1 + for k in range(i, j + 1): + out[order[k]] = (i + j) / 2 + i = j + 1 + return out + + +def within_group_spearman(a: dict[str, float], b: dict[str, float], groups: list[list[str]], *, + min_pairs: int = 5) -> "float | None": + """Spearman correlation of two per-case readings inside each group of cases, pooled: ranks are + taken and centred within a group, so a shift between the groups does not count. ``None`` when no + group has *min_pairs* cases with both readings, or a reading is constant within every group.""" + sxy = sxx = syy = 0.0 + for ids in groups: + both = [c for c in ids if c in a and c in b] + if len(both) < min_pairs: + continue + ra, rb = average_ranks([a[c] for c in both]), average_ranks([b[c] for c in both]) + ma, mb = sum(ra) / len(ra), sum(rb) / len(rb) + sxy += sum((x - ma) * (y - mb) for x, y in zip(ra, rb)) + sxx += sum((x - ma) ** 2 for x in ra) + syy += sum((y - mb) ** 2 for y in rb) + if sxx <= 0 or syy <= 0: + return None + return sxy / math.sqrt(sxx * syy) diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index ac9c2505..0a6a00cd 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -183,7 +183,7 @@ def build(args): explainer = runner._triage_explainer(args, spec) assert isinstance(explainer, Explainer) and seen == {'allow_codegen': False, 'skip_m5': True} assert explainer.identity == {'provider': 'gemini', 'model': 'gemini-2.5-flash', 'effort': 'medium'} - rules = build_parser().parse_args(['--triage-explanations', 'judge']) + rules = build_parser().parse_args(['--triage-scheduler', 'rules', '--triage-explanations', 'judge']) with pytest.raises(SystemExit, match='--triage-scheduler scored'): runner._triage_explainer(rules, spec) same = build_parser().parse_args(['--judge-provider', 'gemini', '--judge-model', 'Qwen/Qwen3.5-0.8B', @@ -192,17 +192,12 @@ def build(args): runner._triage_explainer(same, spec) -def test_triage_weights_and_exploration_share_parse_and_are_checked(): +def test_triage_defaults_are_the_scored_scheduler_and_the_exploration_share_is_checked(): from evalrx.benchmark.run import main as run_main - from evalrx.benchmark.run import triage_weights - assert triage_weights('d=1,t=1,c=1,r=1') == {'d': 1.0, 't': 1.0, 'c': 1.0, 'r': 1.0} - assert triage_weights('c=0, r=0.5') == {'d': 1.0, 't': 1.0, 'c': 0.0, 'r': 0.5} # left out = 1 - for bad in ('x=1', 'd', 'd=-1'): - with pytest.raises(ValueError, match='--triage-weights'): - triage_weights(bad) args = build_parser().parse_args([]) - assert (args.triage_weights, args.triage_explore_share) == ('d=1,t=1,c=1,r=1', 0.1) + assert (args.triage_scheduler, args.triage_max_fail, args.triage_max_actions, args.triage_explore_share) == ( + 'scored', 128, 30, 0.1) with pytest.raises(ValueError, match='--triage-explore-share'): run_main(['--modality', 'vlm', '--model', 'qwen3.5-0.8b', '--m1-policy', 'triage_active', '--triage-explore-share', '1.0']) diff --git a/tests/test_eval_agent/test_triage_alternatives.py b/tests/test_eval_agent/test_triage_alternatives.py index 089bbf9e..a168e7db 100644 --- a/tests/test_eval_agent/test_triage_alternatives.py +++ b/tests/test_eval_agent/test_triage_alternatives.py @@ -7,8 +7,7 @@ * exploration spends at most its share of the evidence and draws only from its targets, the actions the value never takes (an inactive route's next candidate, another route's representative); what it started on a route is - completed on value (T); ``explore_from="candidates"`` (ablation) draws from - the candidates other than the best instead, alternatives included. + completed on value (T). """ from __future__ import annotations @@ -144,7 +143,7 @@ def test_exploration_takes_its_targets_within_its_share_and_pays_for_completing_ # one case a chunk, so that an explored step has chunks left on the route report = _run(tmp_path / "e", wrappers, explore_share=0.3, chunk=1) explored = [d for d in report["decisions"] if d.get("choice") == "explore"] - assert explored and report["explore_share"] == 0.3 and report["explore_from"] == "targets" + assert explored and report["explore_share"] == 0.3 # within the share, but for the one chunk whose estimate fell short assert 0 < report["explored"]["wall_sec"] <= 0.3 * report["cost"]["evidence"]["wall_sec"] + 2.0 for d in explored: # a target, never a candidate the value could take, and never an alternative @@ -184,10 +183,3 @@ def test_exploration_takes_a_route_too_small_to_be_active(tmp_path, wrappers, me assert small == ["N"] assert any(d.get("choice") == "explore" and d["route"] == "N" and "too small" in d["explore_target"] for d in report["decisions"]) - - -def test_the_candidates_ablation_explores_the_other_candidates_alternatives_included(tmp_path, wrappers, metered): - report = _run(tmp_path / "c", wrappers, explore_share=0.3, chunk=2, explore_from="candidates") - explored = {d["key"] for d in report["decisions"] if d.get("choice") == "explore"} - assert explored & {"wrap_b", "wrap_c"} and report["explore_from"] == "candidates" - assert not any(d.get("explore_targets") for d in report["decisions"]) diff --git a/tests/test_eval_agent/test_triage_chunks.py b/tests/test_eval_agent/test_triage_chunks.py index dfe30834..260c3ac4 100644 --- a/tests/test_eval_agent/test_triage_chunks.py +++ b/tests/test_eval_agent/test_triage_chunks.py @@ -113,37 +113,6 @@ def test_further_chunks_of_a_taken_step_do_not_use_up_max_actions(tmp_path): assert layer["state"] == "done" # the step ran on all of its route's cases -def test_the_control_schedulers_run_over_the_scored_pool_and_never_explore(tmp_path): - import pytest - - from evalrx.eval_agent.triage.controller import report_name - from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _Table - - cases, table = _pope_like() - reports = {} - for scheduler in ("random", "cheapest"): - reports[scheduler] = run_triage(_Table(table), cases, **_kw(tmp_path / scheduler, max_fail=4, min_route_fail=1, - chunk=2, scheduler=scheduler, explore_share=0.5)) - for scheduler, report in reports.items(): - assert report["scheduler"] == scheduler and report["explore_share"] == 0.0 and report["explored"] == {} - chosen = [d for d in report["decisions"] if "choice" in d] - assert chosen and {d["choice"] for d in chosen} == {scheduler} - assert all(d["rationale"].startswith("control:") for d in chosen) - assert report["stop"]["reason"] in ("below_threshold", "no_candidate", "max_actions", "budget") - assert report_name(scheduler) == f"triage_report.{scheduler}" - # the cheapest control takes the lowest-cost candidate at or above the gain floor at every decision - floor = reports["cheapest"]["min_gain"] - steps = [d for d in reports["cheapest"]["decisions"] - if d.get("choice") == "cheapest" and d["kind"] in ("follow_up", "battery", "extend")] - assert steps - for d in steps: - priced = [c for c in d["candidates"] if c["cost"] is not None and c["gain"] >= floor] - taken = next(c for c in priced if c["key"] == d["key"] and c.get("route") == d.get("route")) - assert taken["cost"] == min(c["cost"] for c in priced) - with pytest.raises(ValueError): - run_triage(_Table(table), cases, **_kw(tmp_path / "x", scheduler="random", explainer=object())) - - EXPANSION_SEC = 4.0 # an expansion's cases cost four times what the first draw's did diff --git a/tests/test_eval_agent/test_triage_expansion.py b/tests/test_eval_agent/test_triage_expansion.py index 5d42f057..99890c09 100644 --- a/tests/test_eval_agent/test_triage_expansion.py +++ b/tests/test_eval_agent/test_triage_expansion.py @@ -1,4 +1,4 @@ -"""MVP-2 triage: nested expansion with per-case reuse, and follow-ups chosen by fixed rules. +"""Nested expansion with per-case reuse, and follow-ups chosen by fixed rules. * expanding 4 -> 8 FAIL cases gives every case the same record as drawing 8 at once, for the same model calls: only the new cases run; @@ -21,7 +21,6 @@ from evalrx.eval_agent.triage import BATTERY, LAYERS, run_triage from evalrx.eval_agent.triage.actions import FAILED, OK, UNFAITHFUL, Observation from evalrx.eval_agent.triage.evidence import StepEvidence -from evalrx.eval_agent.triage.routes import difference_interval from evalrx.eval_agent.triage.rules import ( active_routes, candidate_steps, @@ -29,6 +28,7 @@ next_for_route, next_size, ) +from evalrx.stats.intervals import newcombe_interval OBJECTS = ("cat", "dog", "car", "cup") @@ -80,6 +80,7 @@ def _kw(out, **over): kw = dict(out_dir=out, model_identity={"spec": "table"}, n_fail=4, seed=0, host_assumed_finish=True, n_needs_counterfactual=True, task_kind="yes_no", answer_fn=_yes_no, min_cohort=100, analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, progress=None, + scheduler="rules", # the fixed rounds, unless a test names the scored scheduler explore_share=0.0) # the scored scheduler explores only in the tests about exploration return {**kw, **over} @@ -298,15 +299,15 @@ def test_a_refusal_on_any_chunk_refuses_the_step_on_every_case(): def test_expansion_gaps_and_sizes(): - lo, hi = difference_interval(3, 8, 0, 8) + lo, hi = newcombe_interval(3, 8, 0, 8) assert lo < 0 < hi # 3/8 vs 0/8: not sure the difference is not zero - assert difference_interval(13, 32, 1, 32)[0] > 0 - assert difference_interval(1, 0, 0, 4) is None + assert newcombe_interval(13, 32, 1, 32)[0] > 0 + assert newcombe_interval(1, 0, 0, 4) is None def summary(k_fail, k_pass, n): rate = {"fail": {"n_fired": k_fail, "n_tested": n}, "pass": {"n_fired": k_pass, "n_tested": n}} d = (k_fail - k_pass) / n - return {"U": {**rate, "routing_signal": max(0.0, d), "signal_ci95": difference_interval(k_fail, n, k_pass, n)}, + return {"U": {**rate, "routing_signal": max(0.0, d), "signal_ci95": newcombe_interval(k_fail, n, k_pass, n)}, "N": {**rate, "routing_signal": 0.0, "signal_ci95": None}, "H_label_free": {**rate, "routing_signal": None, "signal_ci95": None}} diff --git a/tests/test_eval_agent/test_triage_explanations.py b/tests/test_eval_agent/test_triage_explanations.py index cd893491..1d5cbde1 100644 --- a/tests/test_eval_agent/test_triage_explanations.py +++ b/tests/test_eval_agent/test_triage_explanations.py @@ -1,4 +1,4 @@ -"""MVP-3b: D from competing explanations the judge proposes, checked by code. +"""D from competing explanations the judge proposes, checked by code. * a prediction is a hit when the 95% interval of FAIL - control lies in its region, a miss when it lies outside, undetermined otherwise; @@ -320,25 +320,6 @@ def test_the_rules_scheduler_does_not_take_an_explainer(tmp_path): **_kw(tmp_path / "r", explainer=Explainer(_Judge(), identity={}))) -def test_compare_applies_the_explaining_runs_explanations_to_both_runs_evidence(tmp_path, capsys): - from evalrx.eval_agent.triage.compare import compare, main, markdown - - out = tmp_path / "c" - rules = run_triage(_Table(_pope_like()[1]), _pope_like()[0], **_kw(out, max_fail=8, min_route_fail=1)) - explained = _explained(out, _Judge()) - diff = compare(rules, explained) - d = diff["discrimination"] - assert d["baseline"]["revision"] == d["other"]["revision"] == explained["explanations"]["sets"][-1]["revision"] - assert d["other"]["n_conflicting_pairs"] >= 1 and d["baseline"]["n_conflicting_pairs"] == d["other"][ - "n_conflicting_pairs"] - assert diff["judge"]["other"]["n_calls"] == 1 and "tells apart" in markdown(diff) - json.dumps(diff) - a, b = tmp_path / "a.json", tmp_path / "b.json" - a.write_text(json.dumps(rules, default=str)), b.write_text(json.dumps(explained, default=str)) - assert main([str(a), str(b)]) == 0 and "tells apart" in capsys.readouterr().out - assert main([str(a), str(b), "--json"]) == 0 and json.loads(capsys.readouterr().out)["same_sample"] is True - - @pytest.mark.parametrize("scheduler", ["rules", "scored"]) def test_a_budgeted_rerun_on_the_same_ledger_decides_as_the_run_that_executed(tmp_path, monkeypatch, scheduler): import evalrx.eval_agent.triage.controller as controller diff --git a/tests/test_eval_agent/test_triage_routes.py b/tests/test_eval_agent/test_triage_routes.py index 150182fb..4063372e 100644 --- a/tests/test_eval_agent/test_triage_routes.py +++ b/tests/test_eval_agent/test_triage_routes.py @@ -1,4 +1,4 @@ -"""MVP-0 triage controller (``--m1-policy triage_active``): the acceptance behaviours. +"""The triage controller (``--m1-policy triage_active``): the battery, the routes and the ledger. * the planned actions run exactly as planned (no backfill, cap or codegen); * unsupported / failed / unfaithful outcomes carry a reason and never a zero; @@ -593,12 +593,12 @@ def _steps(report): return {e["key"]: e for e in report["executions"] if e["kind"] == "battery"} -def test_mvp0_end_to_end_and_resume(tmp_path, vlm_cases): +def test_triage_end_to_end_and_resume(tmp_path, vlm_cases): from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") ident = {"spec": model.spec.key, "backend": "tiny"} - kw = dict(out_dir=tmp_path / "probing", model_identity=ident, n_fail=2, seed=0, + kw = dict(out_dir=tmp_path / "probing", model_identity=ident, n_fail=2, seed=0, scheduler="rules", host_assumed_finish=True, n_needs_counterfactual=True, task_kind="yes_no", analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) @@ -667,12 +667,12 @@ def _rerun(report): return [s["key"] for s in report["executions"] if s["status"] != "not_applicable" and not s["reused"]] -def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch): +def test_triage_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch): from evalrx.eval_agent.triage import controller from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") - kw = dict(out_dir=tmp_path / "v", model_identity={"spec": "tiny"}, n_fail=2, progress=None) + kw = dict(out_dir=tmp_path / "v", model_identity={"spec": "tiny"}, n_fail=2, progress=None, scheduler="rules") first = run_triage(model, vlm_cases, **kw) real = controller.tool_version monkeypatch.setattr(controller, "tool_version", @@ -682,12 +682,12 @@ def test_mvp0_changed_tool_code_is_a_new_action(tmp_path, vlm_cases, monkeypatch assert _steps(second)["attention_knockout"]["action_id"] != _steps(first)["attention_knockout"]["action_id"] -def test_mvp0_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vlm_cases, monkeypatch): +def test_triage_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vlm_cases, monkeypatch): from evalrx.eval_agent.triage import controller from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") - kw = dict(out_dir=tmp_path / "c", model_identity={"spec": "tiny"}, n_fail=2, + kw = dict(out_dir=tmp_path / "c", model_identity={"spec": "tiny"}, n_fail=2, scheduler="rules", stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}}, progress=None) first = run_triage(model, vlm_cases, **kw) code = controller.code_version() @@ -705,12 +705,12 @@ def test_mvp0_code_version_is_recorded_but_not_part_of_the_identity(tmp_path, vl assert [c["code"] for c in costs if c["kind"] == "stage0"] == [code["tree"], "000000000000"] -def test_mvp0_steps_that_compare_answers_do_not_run_where_outputs_commit_to_none(tmp_path, vlm_cases): +def test_triage_steps_that_compare_answers_do_not_run_where_outputs_commit_to_none(tmp_path, vlm_cases): from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") report = run_triage(model, vlm_cases, out_dir=tmp_path / "cap", model_identity={"spec": "tiny"}, n_fail=2, - task_kind="chair_caption", answer_fn=_no_answer, progress=None, + task_kind="chair_caption", answer_fn=_no_answer, progress=None, scheduler="rules", analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}) steps = _steps(report) for key in ("self_consistency", "prompt_reword", "prompt_threshold"): @@ -742,12 +742,12 @@ def test_code_version_hashes_per_package_directory_and_reads_a_snapshot_ref(tmp_ assert code_label(None) == "code not recorded" -def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): +def test_triage_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): from evalrx.eval_agent.triage.ledger import Ledger from tests.tiny_whitebox import TinyVLM model = TinyVLM("qwen2_5_vl") - kw = dict(out_dir=tmp_path / "p", model_identity={"spec": "tiny"}, n_fail=2, progress=None) + kw = dict(out_dir=tmp_path / "p", model_identity={"spec": "tiny"}, n_fail=2, progress=None, scheduler="rules") first = run_triage(model, vlm_cases, **kw) ko_id = _steps(first)["attention_knockout"]["action_id"] ledger = Ledger(tmp_path / "p") @@ -759,10 +759,10 @@ def test_mvp0_uncertain_attempt_gets_a_new_number(tmp_path, vlm_cases): assert _rerun(second) == ["attention_knockout"] -def test_mvp0_black_box_gates_off_the_white_box_step(tmp_path, vlm_cases): +def test_triage_black_box_gates_off_the_white_box_step(tmp_path, vlm_cases): model = _BlackBox() report = run_triage(model, vlm_cases, out_dir=tmp_path / "bb", model_identity={"spec": "bb"}, - n_fail=2, progress=None) + n_fail=2, progress=None, scheduler="rules") steps = _steps(report) assert steps["attention_knockout"]["status"] == UNSUPPORTED assert steps["attention_knockout"]["cost"]["calls"] == {} @@ -803,7 +803,7 @@ def test_api_run_meters_tokens_and_dollars_and_runs_its_behavioural_follow_up(tm model = _FakeAPI() report = run_triage( model, vlm_cases, out_dir=tmp_path / "api", model_identity={"spec": "fake-api"}, n_fail=2, - min_route_fail=1, task_kind="yes_no", n_needs_counterfactual=True, progress=None, + min_route_fail=1, task_kind="yes_no", n_needs_counterfactual=True, progress=None, scheduler="rules", analyzer_kwargs={"self_consistency": {"gen_kwargs": {"temperature": 1.0}}}, price_fn=lambda u: usd("gemini-3.1-flash-lite", u), stage0_cost={"wall_sec": 1.0, "calls": {"generate": 8}, "api_usage": {"requests": 8}, "usd": 0.001}) diff --git a/tests/test_eval_agent/test_triage_scoring.py b/tests/test_eval_agent/test_triage_scoring.py index 691957cb..3ad9d652 100644 --- a/tests/test_eval_agent/test_triage_scoring.py +++ b/tests/test_eval_agent/test_triage_scoring.py @@ -1,4 +1,4 @@ -"""MVP-3 scored scheduler: U(a) = q·[D + T + C − R]₊ / (c + ε), against the rules. +"""The scored scheduler: U(a) = q·[D + T + C − R]₊ / (c + ε), against the rules. * q counts distinct observations (a read-back once), a refusal as a failure; * c comes from the step's own cost per case, else measured per-call rates; @@ -11,11 +11,8 @@ from __future__ import annotations -import json - from evalrx.eval_agent.triage import BATTERY, LAYERS, run_triage from evalrx.eval_agent.triage.actions import OK, UNFAITHFUL, UNSUPPORTED, Observation -from evalrx.eval_agent.triage.compare import compare from evalrx.eval_agent.triage.evidence import StepEvidence from evalrx.eval_agent.triage.rules import candidate_steps from evalrx.eval_agent.triage.scoring import ( @@ -69,32 +66,6 @@ def test_costs_come_from_the_steps_own_measurement_else_the_runs_typical_or_wors assert step_cost(_step("causal_trace"), 2, {}, "wall_sec") == (None, "none") -def test_the_random_and_cheapest_controls_pick_among_the_same_candidates_without_exploring(): - import pytest - - def s(key, U, gain, order, cost=10.0): - return Scored(kind="follow_up", key=key, U=U, gain=gain, order=order, cost=cost) - - pool = [s("late", 0.5, 0.2, (1, 2), cost=10.0), s("early", 0.5, 0.2, (1, 0), cost=30.0), - s("cheap", 0.1, 0.3, (0, 0), cost=1.0), s("zero", 0.0, 0.0, (0, 1), cost=0.5)] - # exploration would fit here (90 spent, share 0.5): the controls still never explore - kw = dict(seed=0, explore_share=0.5, min_gain=0.01, explored=0.0, spent=90.0) - assert choose(pool, decision_no=0, **kw)[1] == "explore" - draws = [choose(pool, decision_no=n, policy="random", **kw) for n in range(30)] - assert {why for _, why in draws} == {"random"} and {p.key for p, _ in draws} == {"late", "early", "cheap"} - assert choose(pool, decision_no=3, policy="random", **kw) == choose(pool, decision_no=3, policy="random", **kw) - assert choose(pool, decision_no=0, policy="cheapest", **kw) == (pool[2], "cheapest") # not "zero": below the floor - # cheapest: ties by soft order, an unpriced candidate last - tie = [s("b", 0.5, 0.2, (1, 1), cost=5.0), s("a", 0.5, 0.2, (1, 0), cost=5.0), s("u", 0.9, 0.9, (0, 0), cost=None)] - assert choose(tie, decision_no=0, policy="cheapest", **kw)[0].key == "a" - assert choose([tie[2]], decision_no=0, policy="cheapest", **kw)[0].key == "u" - # the same stops as the scored scheduler - assert choose([pool[3]], decision_no=0, policy="random", **kw) == (None, "below_threshold") - assert choose([], decision_no=0, policy="cheapest", **kw) == (None, "none") - with pytest.raises(ValueError): - choose(pool, decision_no=0, policy="greedy", **kw) - - def test_coverage_gain_is_the_gap_removed_over_all_units(): units = {"S1:yes": {"rule_id": "S1", "stratum": "yes", "need": 2, "measured": 0, "gap": 1.0, "_ids": ["a", "b"]}, "S1:no": {"rule_id": "S1", "stratum": "no", "need": 2, "measured": 1, "gap": 0.5, "_ids": ["c", "d"]}, @@ -110,31 +81,31 @@ def s(key, U, gain, order, cost=10.0): return Scored(kind="follow_up", key=key, U=U, gain=gain, order=order, cost=cost) pool = [s("late", 0.5, 0.2, (1, 2)), s("early", 0.5, 0.2, (1, 0)), s("cheap", 0.1, 0.3, (0, 0))] + targets = [s("t1", 0.0, 0.0, (2, 98)), s("t2", 0.0, 0.0, (2, 99))] kw = dict(seed=0, explore_share=0.1, min_gain=0.01) # 10 s of exploration would be 10/(50+10) of the spending: over the share, so the best runs - best, why = choose(pool, decision_no=0, explored=0.0, spent=50.0, **kw) + best, why = choose(pool, decision_no=0, explored=0.0, spent=50.0, targets=targets, **kw) assert (best.key, why) == ("early", "best") - # at 90 s spent it fits (10 <= 0.1 * 100): a seeded draw among the others runs instead - picked, why = choose(pool, decision_no=3, explored=0.0, spent=90.0, **kw) - assert why == "explore" and picked.key != "early" - assert choose(pool, decision_no=3, explored=0.0, spent=90.0, **kw)[0].key == picked.key # seeded - assert choose(pool, decision_no=3, explored=10.0, spent=100.0, **kw)[1] == "best" # share used up - assert choose(pool, decision_no=3, explored=0.0, spent=1e6, **{**kw, "explore_share": 0.0})[1] == "best" - # below the gain floor every candidate is an exploration candidate; once none fits, the run stops + # at 90 s spent it fits (10 <= 0.1 * 100): a seeded draw among the targets runs instead + picked, why = choose(pool, decision_no=3, explored=0.0, spent=90.0, targets=targets, **kw) + assert why == "explore" and picked in targets + assert choose(pool, decision_no=3, explored=0.0, spent=90.0, targets=targets, **kw)[0].key == picked.key # seeded + assert choose(pool, decision_no=3, explored=10.0, spent=100.0, targets=targets, **kw)[1] == "best" # share used up + assert choose(pool, decision_no=3, explored=0.0, spent=1e6, targets=targets, + **{**kw, "explore_share": 0.0})[1] == "best" + # exploration draws only from its targets: without one the best runs, and below the gain floor the run stops low = [s("x", 0.0, 0.0, (0, 0)), s("y", 0.0, 0.0, (0, 1), cost=100.0)] - assert choose(low, decision_no=0, explored=0.0, spent=90.0, **kw) == (low[0], "explore") - assert choose(low, decision_no=0, explored=0.0, spent=50.0, **kw) == (None, "below_threshold") - assert choose([], decision_no=0, explored=0.0, spent=0.0, **kw) == (None, "none") - # with targets, exploration draws only from them, even with no candidate left - target = s("t", 0.0, 0.0, (2, 99), cost=5.0) - assert choose(pool, decision_no=3, explored=0.0, spent=90.0, targets=[target], **kw) == (target, "explore") - assert choose(pool, decision_no=3, explored=0.0, spent=10.0, targets=[target], **kw)[1] == "best" # no fit assert choose(pool, decision_no=3, explored=0.0, spent=90.0, targets=[], **kw)[1] == "best" - assert choose([], decision_no=0, explored=0.0, spent=90.0, targets=[target], **kw) == (target, "explore") assert choose(low, decision_no=0, explored=0.0, spent=90.0, targets=[], **kw) == (None, "below_threshold") + assert choose([], decision_no=0, explored=0.0, spent=0.0, targets=[], **kw) == (None, "none") + # a target that fits runs even with no candidate left; one that does not fit leaves the best + target = s("t", 0.0, 0.0, (2, 99), cost=5.0) + assert choose([], decision_no=0, explored=0.0, spent=90.0, targets=[target], **kw) == (target, "explore") + assert choose(low, decision_no=0, explored=0.0, spent=90.0, targets=[target], **kw) == (target, "explore") + assert choose(pool, decision_no=3, explored=0.0, spent=10.0, targets=[target], **kw)[1] == "best" -def test_scored_run_is_traceable_deterministic_on_resume_and_comparable_with_the_rules(tmp_path): +def test_scored_run_is_traceable_deterministic_on_resume_and_shares_the_sample_with_the_rules(tmp_path): cases, table = _pope_like() out = tmp_path / "p" rules = run_triage(_Table(table), cases, **_kw(out, max_fail=8, min_route_fail=1)) @@ -152,9 +123,8 @@ def test_scored_run_is_traceable_deterministic_on_resume_and_comparable_with_the again = run_triage(_Table(table), cases, **_kw(out, max_fail=8, min_route_fail=1, scheduler="scored")) assert [(d["kind"], d.get("key")) for d in again["decisions"]] == [(d["kind"], d.get("key")) for d in scored["decisions"]] - diff = compare(rules, scored) - assert diff["same_sample"] and diff["schedulers"] == ["rules", "scored"] - json.dumps(diff) + assert rules["sample"]["case_ids"] == scored["sample"]["case_ids"] # the same nested sample, one ledger + assert (rules["scheduler"], scored["scheduler"]) == ("rules", "scored") def test_scored_runs_a_batch_dependent_step_once_after_the_last_expansion(tmp_path): diff --git a/tests/test_eval_agent/test_triage_validation.py b/tests/test_eval_agent/test_triage_validation.py index 78355c20..0e2d1c95 100644 --- a/tests/test_eval_agent/test_triage_validation.py +++ b/tests/test_eval_agent/test_triage_validation.py @@ -1,4 +1,4 @@ -"""MVP-4: issues frozen from a diagnosis and validated once on cases it never saw. +"""Issues frozen from a diagnosis and validated once on cases it never saw. * the partition keeps every validation case off the media DISCOVERY saw; * freezing keeps route signals and readings whose discovery interval clears the @@ -35,8 +35,8 @@ source_key, supported_curve, validate, - within_group_rho, ) +from evalrx.stats.intervals import within_group_spearman from tests.test_eval_agent.test_triage_alternatives import FIRST, _Flipper from tests.test_eval_agent.test_triage_expansion import _kw, _pope_like, _yes_no @@ -255,7 +255,7 @@ def test_the_validator_refuses_a_report_from_another_rules_version(tmp_path): _, _, explore, confirm = _split(16) _, validation = partition_bundle(explore, confirm, seed=SEED, confirm_split=0.5) with pytest.raises(ValueError, match="another rules version"): - validate(None, explore, validation, {"old": []}, {"old": {"rules_version": "mvp2-rules-1"}}, + validate(None, explore, validation, {"old": []}, {"old": {"rules_version": "rules-1"}}, out_dir=tmp_path, model_identity={}, progress=None) @@ -276,8 +276,8 @@ def test_readings_that_go_together_within_groups_are_one_phenomenon_and_a_shift_ check="U") per_case = {a.issue_id: (base, fail, ctrl), b.issue_id: (same, fail, ctrl), c.issue_id: (shifted, fail, ctrl), d.issue_id: (base, fail, ctrl)} - assert within_group_rho(base, same, [fail, ctrl]) == pytest.approx(1.0) - assert within_group_rho(base, shifted, [fail, ctrl]) == pytest.approx(-3 / 35) + assert within_group_spearman(base, same, [fail, ctrl]) == pytest.approx(1.0) + assert within_group_spearman(base, shifted, [fail, ctrl]) == pytest.approx(-3 / 35) results = {signal.issue_id: {"verdict": "inconclusive"}, a.issue_id: {"verdict": "supported"}, b.issue_id: {"verdict": "inconclusive"}, c.issue_id: {"verdict": "supported"}, d.issue_id: {"verdict": "refuted"}} diff --git a/tests/test_stats/test_intervals.py b/tests/test_stats/test_intervals.py new file mode 100644 index 00000000..1b7605b6 --- /dev/null +++ b/tests/test_stats/test_intervals.py @@ -0,0 +1,50 @@ +"""Closed-form quantiles and intervals (``evalrx.stats.intervals``) against known values.""" + +from __future__ import annotations + +import pytest + +from evalrx.stats.intervals import ( + average_ranks, + newcombe_interval, + t_quantile, + wilson_interval, + within_group_spearman, + z_quantile, +) + + +def test_normal_and_t_quantiles_match_the_tables(): + assert z_quantile(0.95) == pytest.approx(1.95996, abs=1e-4) + assert z_quantile(0.99) == pytest.approx(2.57583, abs=1e-4) + assert t_quantile(0.95, 10) == pytest.approx(2.228, abs=1e-3) # the 95% table + assert t_quantile(0.99, 10) == pytest.approx(3.1693, abs=1e-3) # the inverted CDF + assert t_quantile(0.999, 4) == pytest.approx(8.6103, abs=1e-3) + assert t_quantile(0.99, 10.9) == t_quantile(0.99, 10) # floor of the degrees of freedom + assert t_quantile(0.99, 5) > t_quantile(0.99, 50) > z_quantile(0.99) + + +def test_wilson_and_newcombe_intervals(): + lo, hi = wilson_interval(5, 52) + assert (lo, hi) == pytest.approx((0.0418, 0.2062), abs=1e-3) + assert wilson_interval(0, 10)[0] == 0.0 and wilson_interval(10, 10)[1] == pytest.approx(1.0) + lo, hi = newcombe_interval(3, 8, 0, 8) + assert lo < 0 < hi and newcombe_interval(13, 32, 1, 32)[0] > 0 + assert newcombe_interval(1, 0, 0, 4) is None # an empty side has no rate + wide, narrow = newcombe_interval(13, 32, 1, 32, z=z_quantile(0.99)), newcombe_interval(13, 32, 1, 32) + assert wide[0] < narrow[0] and wide[1] > narrow[1] + + +def test_ranks_average_ties_and_the_correlation_ignores_a_shift_between_groups(): + assert average_ranks([3.0, 1.0, 3.0, 2.0]) == [2.5, 0.0, 2.5, 1.0] + a = {f"f{i}": float(i) for i in range(6)} | {f"c{i}": 100.0 + i for i in range(6)} + same = {k: v * 2 for k, v in a.items()} + flipped = {k: -v for k, v in a.items()} + groups = [[f"f{i}" for i in range(6)], [f"c{i}" for i in range(6)]] + assert within_group_spearman(a, same, groups) == pytest.approx(1.0) + assert within_group_spearman(a, flipped, groups) == pytest.approx(-1.0) + # the two groups sit 100 apart in a and at the same level in b: pooled ranks would correlate, these do not + b = {**{f"f{i}": float(5 - i) for i in range(6)}, **{f"c{i}": float(5 - i) for i in range(6)}} + assert within_group_spearman(a, b, groups) == pytest.approx(-1.0) + assert within_group_spearman(a, same, groups, min_pairs=7) is None # no group has seven pairs + assert within_group_spearman(a, {k: 1.0 for k in a}, groups) is None # a constant reading From 8f20772973e8976c2e05981b72a344d117cfc352 Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:11:12 -0700 Subject: [PATCH 25/26] Update the triage docs and condense its changelog entries docs/agentic_benchmark.md describes the package under its new path, the scored default and the remaining switches. The Unreleased section of the changelog had one entry per development step of the triage (33); they are now 11 entries that describe what the branch adds. --- CHANGELOG.md | 562 ++++++-------------------------------- docs/agentic_benchmark.md | 18 +- 2 files changed, 91 insertions(+), 489 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42ed20a4..8868eea2 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -526,83 +526,72 @@ never fired and M1 read every case as fully consistent. A call that names a temp temperature alone (`backends.base.call_sampling`, used by `hf_local`, `jax_local` and `vllm_offline`); a call that names neither keeps the deployed decoding. -### Changed — probing after the 0.2.0 reorganisation and the batch calls - -The triage follows the package's new layout (`loop.partition.split_cases` for the -EXPLORE/CONFIRM split, `runlog.instrumentation` for per-call logs; the triage entry -sits beside the steps `runner.run` was split into, and its validation source is -labelled by the same Stage 0 step as the pool). `prompt_contrast` and -`modality_ablation` ask in batches like the other generation analyzers; a -counterfactual swap asks the unablated questions first, since the donor depends on -their answers. `self_consistency` keeps one `generate` call per sample: under its -seed a case's samples are then the same draws whatever the backend's batch size. -The triage's call meter counts `generate_batch` / `try_generate_batch` / -`logprobs_batch` per input, under `generate` and `logprobs`; unmetered, a batched -step would have read as one that ran without calling the model. The probing -package and the analyzers it extended now pass the package's type check. - -### Changed — probing: dead code removed, `compare` has a CLI - -Removed what later code had superseded: `Ledger.spent` / `spent_wall_sec` (the budget -is charged by `_Run.charged`), `StepEvidence.sec_per_case` (costs come from -`scoring.step_cost`), the `run_triage_mvp0` alias (tests call `run_triage`) and the -sampler's `_rank` alias. `python -m evalrx.eval_agent.probing.compare ` -prints two arms' reports side by side (`--json` for the diff). A layer that narrows its -route's cases (X1) states its filter in its state (`case_filter`), where only the rule's -source had carried it. Stale strings updated: the package and controller docstrings no -longer describe MVP-2, `--m1-policy` says when a judge is built and that CONFIRM reaches -only the validator, and `evalsmith/probing/probing_design_mix.md` has a current status -header and a list of the remaining gaps between the design and the implementation. -`POLICY_VERSION` stays `mvp2-0`: it is part of every action identity, and a bump would -re-execute every stored observation. - -### Changed — the triage compares answers under the task's tolerance - -The U and S checks and the follow-up readings compared answers by key equality, -while the grader holds a numeric answer to ChartQA's relaxed 5 % rule: two -samples of 12.5 and 12.8 were two answers for the triage and one verdict for the -scorer, so the re-sampling part of U fired on rounding jitter (ChartQA -`triage17`: 287 of 450 validation FAILs were on U). The host now passes an -agreement rule next to the answer key (`tasks.same_answer`, built on -`scoring.same_answer`: equal keys, or two numbers with the candidate within the -case's `numeric_tolerance` of the reference; `run_triage` / `validate` / -`triage_cases(agree_fn=)`, default: equal keys). The re-sampling check counts -the samples agreeing with the Stage-0 answer as that answer and clusters the -rest the same way (`rivals`), so nearby roundings neither split the base nor -pile up as rivals; the rewording, threshold and `prompt_contrast` "changed" -readings use the rule too. `answer_key` also applies the grader's yes/true -aliases on `exact_or_numeric`. Rules version `mvp4-rules-5`; `agree_fn` is -recorded in the report settings. - -### Fixed — a budget check priced a step that ran without model calls at the run's worst case - -`step_cost` took a step's own measurement only from observations that called -the model, so the two audits of stored outputs (`answer_extraction_audit`, -`termination_audit`: no calls, next to no time) counted as never measured and a -budget check priced them at the run's most expensive case per case. An -expansion's estimate carried both over every new case: on ChartQA `triage18` -the 32 → 64 FAIL expansion (912 s when run) was estimated at 3205 s after -`patchscope` had run and at 22215 s after an exploring arm had fitted -`tuned_lens` on 4 cases (167.7 s per case), so every budget-tier arm stopped on -"expand over budget" with budget to spare, the exploring arms at 32 FAIL cases -whatever the tier (4000, 5500 or 7100 s). A step's own cost now covers every -observation that called the model or completed without calling it; the typical -and worst-case prices of a step that never ran still come from model-calling -observations only (scoring `mvp3-score-5`). - -### Fixed — an expansion's battery ran past the budget - -The decision to expand was checked once, on the sum of the battery steps' -estimates over the new cases, and the battery then ran unchecked: on ChartQA -`triage18` the 64 → 128 FAIL expansion was estimated at 1668 s from the cases -measured so far and cost 2413 s (the later cases were dearer), so the 4000 s -arms that expanded charged 4220–4548 s. The battery now runs chunk by chunk, -every immediate step on one chunk of the new cases before any step moves to the -next, with the budget checked before each chunk on the cost measured so far, -like every other action; a refusal stops the run (`stop: budget`, pending -`expansion`) with the chunks measured so far routed and a check that never ran -on the remaining new cases untested (a case with no fired check is X), so an -expansion overshoots by at most one chunk of one step. +### Added — a triage controller as an opt-in M1 (`--m1-policy triage_active`) + +An alternative to the judge-selected M1, in `evalrx/eval_agent/triage/` (not +`evalrx/probing/`, the probe catalog the judge-driven M1 calls). The default +`--m1-policy judge` is unchanged; `docs/agentic_benchmark.md` describes a run. + +After Stage 0 and the loop's own EXPLORE/CONFIRM split, a host-side controller +draws a matched, nested sample of FAIL cases and PASS controls from EXPLORE and +runs a fixed battery on it exactly as written (no backfill, no case cap, no +generated probes). Each FAIL case is put on routes by label-free checks: H (the +output or its grading is suspect), N (the answer ignores the media, tested with a +counterfactual swap), U (the answer moves under re-sampling and rewording), S (a +stable error: every check ran and none fired) and X (a check is missing). Answers +are compared under the task's own tolerance (`tasks.same_answer`), not graded +against gold, and every reading on a card compares FAIL with matched PASS cases +on the model's own answer. + +The controller then decides one action at a time between doubling the sample +(up to `--triage-max-fail`, while a route's signal is uncertain or a cohort is +small) and the routes' follow-ups. `--triage-scheduler scored` (default) takes +the candidate with the highest value per cost, `U = q·[D + T + C − R]₊ / (c + ε)`, +and gives a share of the spending (`--triage-explore-share`) to steps the value +never takes; `rules` runs fixed rounds over the routes' layers instead. Steps +run in chunks (`--triage-chunk`) and are priced at their own measured cost, so +`--triage-budget-sec` / `--triage-budget-usd` are overshot by at most one chunk. +With `--triage-explanations judge` the chain's judge proposes competing +explanations per route, each with predictions code checks against the readings; +the conflicts between live explanations give the value its D. + +Every action is recorded with why it ran, what it cost and whether its +measurement can be trusted (`/probing/`: `selection_trace.jsonl`, +`cost_ledger.jsonl`, `observations/`, `triage_report*.{json,md}`). Outcomes are +typed (`ok`, `unsupported`, `failed`, `unfaithful`), never zeros; a rerun reads +finished actions back by content identity, which includes a hash of the +analyzer's code. M2–M5 do not run and the controller never sees CONFIRM. + +`--triage-validate` freezes the issues a report supports (a route signal, or a +reading that differs between a route's FAIL cases and their controls) and +validates them once on cases the controller never saw: CONFIRM cases on media +EXPLORE does not contain, plus a validation-only pool +(`--triage-validation-source`, labelled by its own Stage 0 pass). Each issue is +tested on its claimed side at a Bonferroni-adjusted level and comes back +`supported`, `refuted`, `inconclusive` or `unavailable`; readings that go +together case by case are counted as one phenomenon. `--confirm-split-by media` +keeps all questions on one image on one side of the split, and +`python -m evalrx.benchmark.tasks.chartqa --exclude ` freezes +the ChartQA rows a pool left as such a validation pool. + +### Added — closed-form intervals in `evalrx.stats.intervals` + +`z_quantile` and `t_quantile` (two-sided, at any level; the t quantile inverts +the CDF, so a family-wise adjusted interval needs no table), `wilson_interval`, +`newcombe_interval` (a difference of two rates) and `within_group_spearman` (a +rank correlation taken inside groups, so a shift between the groups does not +count). Standard library only; the triage controller's verdicts use them. + +### Added — provider usage and listed-price cost on API models + +The gemini runtime sums the token counts every response reports, and +`APIModel.usage_counters()` exposes them with the request and retry counts. +`baseline.json` gains `api_usage` and `usd` for the Stage 0 pass; `usd` comes +from a dated price table (`models/backends/api/prices.py`: only prices read off +the provider's page; an unlisted model's cost is `None`, never a guess, and the +input part is an upper bound because implicit cache hits are not reported). The +gemini runtime merges per-call kwargs over its own sampling, so a re-sampling +probe gets its `temperature` there (the endpoint backend drops per-call kwargs). ### Fixed — a gradient pass keeps no graph through the media encoders; a case that does not fit is skipped @@ -617,215 +606,7 @@ without a graph (`media_encoders_without_grad`, found by the towers' names and the spec's audio hint; `CaptureSpec(media_grad=True)` keeps the old behaviour). Readings are unchanged; the pixel cap is the model's own and stays. `gradcam` and `generic_attention` also skip a case whose graph still does not fit -(`skip_reasons: out_of_memory`) instead of failing the chunk: in the ChartQA -validation (`triage17`) the failed chunk stopped both steps on the S route at -12 of 135 cases. - -### Added — random and cheapest-first controls for the scored scheduler - -`--triage-scheduler random` and `--triage-scheduler cheapest` (reports -`triage_report.random.*` / `triage_report.cheapest.*`) take the scored -scheduler's candidate pool, budget, gain floor and stop rules and differ in the -pick only: a seeded uniform draw among the candidates at or above the gain -floor, or the lowest-cost one (an unpriced candidate last, ties by soft order). -Neither explores nor takes an explainer, so the scored scheduler without -exploration is their nearest value arm and the comparison isolates the value -ordering. Decisions record `choice: random | cheapest` and a rationale; -`scoring.choose(policy=)` carries the rule. - -### Added — the pool can be split into EXPLORE and CONFIRM by media content - -`--confirm-split-by media` (default `case`) draws the explore/confirm split over -media groups: cases on the same image (by content) go to one side, stratified by -the labels the group holds, so DISCOVERY and CONFIRM never share an image and -the diagnostic validation leaves nothing out. Under the per-case split 207 of -ChartQA's 500 CONFIRM cases shared a chart with DISCOVERY and were dropped, not -at random (charts with two questions). The bundle records `split_by`; the -per-case split stays the default because a judge-driven run splits by case and -the two policies are compared case for case. - -### Added — a validation-only source for the diagnostic validation - -`--triage-validation-source MANIFEST` (with `--triage-validate`) adds cases used -only for DIAGNOSTIC_VALIDATION: labelled by their own Stage 0 pass -(`/baseline_validation_source.json`), never seen by the controller or the -judge, and joining the CONFIRM cases under the same rule (a case on media -DISCOVERY contains is left out; a source row repeating an id of the pool is -left out too). The partition bundle records where the validation cases came -from and the source manifest's hash. On ChartQA (1000-case pool) the validation -cases were 293 with 100 FAILs, 7 of them on the N route: nothing there could be -decided. `python -m evalrx.benchmark.tasks.chartqa --exclude -/manifest.json` freezes the human-authored rows the pool left (the rest -of the test split, then the val split) as such a source. - -### Changed — the judge explains what already ran, and is re-asked only about what it can predict - -A re-ask fired when a route with carded tools left had fewer than two live -explanations. It counted the steps a route is cut on, which are never offered -to the judge, so a route whose only tools left were such steps asked a question -that could not include it (ChartQA, Qwen3.5-2B: the full-budget D arm's second -ask, for U with only `self_consistency_n10` left). The trigger now counts the -steps the request offers. `logprob_entropy` on U joins `DEFINITIONAL`: an -answer another one out-samples has a close-call token, so U's low confidence is -its cut read off the output distribution, neither an issue nor a prediction on -U. - -That left U on ChartQA with no tool the judge could predict: its rule layers -hold only those two (the option rotation is for letter answers), and the judge -was offered only tools still to run on a route. The tools that already ran on -a route's cases (knockout, patchscope, tuned_lens, ...) are now offered too, -under `already_run`, with their readings in view: a prediction on one is -checked against them during the triage (a fit, not a test), tested on new cases -by the validator, and gives no D, as the tool is not run again. The first ask -no longer needs a tool left to run; a re-ask still does, as only such a tool -brings new evidence. Explanations `mvp4-explain-6`, validation -`mvp4-validate-5`. - -### Changed — triage validation: supported phenomena over a grid of thresholds; explanations met on new cases - -Whether two readings are one phenomenon was decided at one threshold (|rho| >= -0.5), and correlations near it decided which arm found more. The main metric is -now each arm's supported phenomena at every threshold of `RHO_GRID` (0.3 to 0.7 -by 0.05, `validation.supported_curve`, report `phenomenon_curve`). An arm found -more than another only where it has more at every threshold. The live -explanations at each arm's stop are frozen with the family, and the validator -runs the steps their predictions name that no issue ran on that route, so each -prediction is checked on new cases unless its step cannot run there. A -reading a route is cut on (`DEFINITIONAL`, now in `explanations.py`; e.g. -`self_consistency_n10` on U) is neither offered to the judge for that route -nor measured for an explanation: the validator labels such a prediction -`definitional`, neither support nor contradiction. - -Verdicts are one-sided: every issue claims a direction, so it is tested at -alpha/K on its claimed side (its interval at 1 - 2 alpha/K) rather than at -alpha/2K; a false `supported` anywhere in the family still has probability at -most alpha. Each explanation the judge proposes now names one or two primary -predictions, the readings it stands or falls on; competing explanations of a -route must differ on one, and an explanation without one, or that cannot be told -apart from an earlier one, is dropped when the reply is read. Only primary -predictions keep an explanation live during the triage and enter D. The -validator runs the steps of the frozen explanations' primary predictions, tests -the distinct primary predictions as one family (one-sided Bonferroni), and calls -an explanation `supported` (every primary prediction hits), `refuted` (one -misses), `undecided` or `untestable`; other predictions are reported at 95%. An -explanation from an earlier version, without primaries, stands on all its -predictions. A re-ask of the judge keeps the explanations still live and adds -the new ones that compete with them (`explanations.carry_over`; a new one that -cannot be told apart from a kept one is dropped, a reused id is renumbered), so -an explanation live at the stop is frozen however many asks came after it, and -a failed re-ask loses nothing. Validation version `mvp4-validate-4`, -explanations `mvp4-explain-5`. - -### Changed — the U re-sampling check needs another answer to be the most frequent - -The re-sampling part of U fired when any one of the 5 samples differed from -the Stage-0 answer. At temperature 1.0 that is ordinary noise on open answers -(ChartQA, Qwen3.5-0.8B: 16/32 PASS cases fired). It now fires when another -answer was sampled more often than the Stage-0 answer; a tie stays clear. The -check also records `base_is_modal`. The rewording part is unchanged. Rules -version `mvp4-rules-4`. - -### Fixed — triage controls on open-answer tasks - -`triage_cases` gave every record its gold answer as stratum, whatever rule the -sample was drawn with, and controls are matched within a stratum. On an -open-answer task (sampled with `stratum="none"`) almost no PASS case shares a -FAIL case's gold, so route readings had few controls (ChartQA: 5 for 30 U -FAIL cases) and the follow-up steps ran on those few. `triage_cases` takes the -sampler's rule (`stratum=`), passed by `run_triage` and the validator; yes/no -and letter tasks are unchanged. Rules version `mvp4-rules-3`; the judge -context's `fail_by_gold` is now `fail_by_stratum`. - -### Added — triage diagnostic validation (MVP-4, first version) - -The triage run fixes its data roles before the controller sees a case -(`/partition_bundle.json`): DISCOVERY = EXPLORE, DIAGNOSTIC_VALIDATION = -the CONFIRM cases on media DISCOVERY does not contain. `--triage-validate` -freezes the issues the report supports (route signals and reading differences -on routes, `probing/validation.py`), writes the family and a power plan from -DISCOVERY to `/validation/frozen.json`, then validates every issue once -at a Bonferroni-adjusted level: supported / refuted / inconclusive / -unavailable. Readings that go together case by case within FAIL and within the -controls (pooled within-group Spearman |rho| >= 0.5, same route) are grouped -into one phenomenon, and each arm is credited with its own issues' verdicts -grouped that way (supported phenomena is the main count). Interval helpers -take a level (`explanations.t_quantile` inverts the t distribution exactly; -`triage.difference_interval(z=...)`); `controller.analyzer_extras` gives the -validator DISCOVERY's frozen lens references and fit set; the validator -refuses a report from another rules version. - -### Changed — triage readings use the model's own answer, not gold - -Card readings compare FAIL cases with PASS controls, and a FAIL output is not -gold by definition, so a gold margin lower on FAIL restated the label. The -triage steps with a target (`attention_knockout`, `causal_trace`, -`attention_temperature`, `attention_sensitivity`, `gradcam`, -`generic_attention`, `patchscope`) now use `target="prediction"`; the -"wrong before, right after" readings (`fixed_*`) stay in the step output but -are off the cards; `run_triage` and the validator refuse a carded step whose -target, in its config or the host's analyzer kwargs, is gold -(`explanations.label_bound`). Rules version `mvp4-rules-2`, explanations -`mvp4-explain-3`. - -### Changed — triage exploration draws from its own targets, on the evidence spending - -Exploration's share (`--triage-explore-share`) is now of the evidence spending, -not including the judge's calls, and it draws only from targets the value never -takes: the next candidate of a route too small to be active, and on each active -route the representative of every other route's layer it does not own (steps -with readings to compare with the controls), priced at a budget check's -conservative estimate. Completing a target on its route is paid from the share -until its readings so far show a difference outside the band; from then on it -is completed on value (T, an incomplete step). Alternatives run only on -their D; `--triage-explore-from candidates` keeps the previous draw (the other -candidates, alternatives included) for ablations. - -### Changed — triage scored scheduler: decidable D, alternatives priced by R, exploration share (MVP-3) - -D counts each conflicting pair of live explanations by how decidable the -conflict is on the route's cases (`explanations.decidability`, version -`mvp3-explain-2`): taking each prediction as true at a reference difference (0 -for `same`, one standard deviation of the reading past the band for -`up`/`down`), the cases a side the verdict's interval needs to contradict the -other; each side scores `min(1, n / needed)` and the conflict the mean. The -spread comes from the step's own measurements in this run, else the least -favourable value, so three FAIL cases settle an unmeasured up-versus-same -conflict to 1/6 where they counted in full before. An answered layer offers its -other candidates as alternatives with R = 0.5 when they give the same kind of -evidence as the tool that answered it (`PlanStep.evidence`) and 0 otherwise; -they close no gap and cover no unit, so they run only on a D above their R, and -the judge is offered them (`alternative_to`) from the first ask. Exploration -takes a share of the spending (`--triage-explore-share`, default 0.1) instead -of every 10th decision, and below the gain floor the run explores until no -candidate fits the share. `--triage-weights` sets the weights of D, T, C and R -for ablations (scoring `mvp3-score-4`). A judge call is asked only while the -largest call so far fits the budget, so a run overshoots by at most its first -call; a run whose remaining candidates are over budget stops for `budget` -even when cheaper zero-gain alternatives are left. On Qwen3.5-0.8B POPE -decidability cut D on the 3-case N route from 0.67-1.0 to 0.11-0.22 and the -unbudgeted D arm's evidence from 1603 s to 1350 s; of 19 alternatives the D arms -ran, 7 were chosen on value and 12 by exploration, so the extra evidence -mostly comes from exploration, and whether D pays for its judge (about 30% of -the evidence cost) still needs MVP-4's validated metric. - -### Changed — triage spends by measurement: chunked steps, no per-analyzer cost prior - -Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS -alternating); the budget is checked before every chunk on the cost measured -so far, so a step whose cost nobody knew overshoots by at most one chunk, and -a chunk that raises stops the rest of the step. Cost estimates no longer use -per-call rates or `calls_per_case` (kept for reservations only): a step that -has run is priced at its own measured cost per case, one that has not at the -run's median case (ranking) or its most expensive case (budget checks). A -calibration on Qwen3.5-0.8B showed why: tools' cost ratios hold within a -family on one model (generate tools ~ the number of generate calls, forward -tools within ~15% against `embed_lens`) but not across input sizes -(`patchscope` 3.9-16.7x `embed_lens` between 72 and 985 media tokens), and -per-case cost also grows with batch size for several tools. The scored -scheduler decides one chunk at a time (scoring `mvp3-score-3`): T and D are -earned in proportion to the share of the route's remaining FAIL cases a chunk -covers, and further chunks of a step it already took do not count against -`--triage-max-actions`. +(`skip_reasons: out_of_memory`) instead of failing the batch. ### Changed — the batch-dependent analyzers run per case; seeded self-consistency @@ -842,142 +623,20 @@ under torch's random state seeded from the seed and the case's content every case's samples at temperature 1.0 are identical whether the cases run in chunks, in one batch or in reverse order, where before 7 of 64 route labels changed between two runs that executed in a different order. A model that -samples on the provider's side is not affected. The triage passes EXPLORE in the sampler's rank -order (the first 32 cases as the tuned lens's fit set), so all four steps are -`reuse` steps: they run on new cases only and in chunks. `PlanStep.deferred` -marks the battery steps no route reads (`embed_lens`, `patchscope`). - -### Added — triage competing explanations: D for the scored scheduler (MVP-3, second part) - -`--triage-explanations judge` (with `--triage-scheduler scored`) has the -chain's judge propose, per active route, up to three competing local -explanations of the route's FAIL cases, each predicting `up` / `down` / -`same` / `unknown` for the readings of every tool still to run there (FAIL mean -minus PASS control mean against a band fixed per reading in -`probing/explanations.py`, version `mvp3-explain-1`). The judge is asked once -the sample has settled and again, at most three asks, when the evidence has -decided a prediction and a route with tools left has fewer than two live -explanations. Code checks each prediction on the 95% interval of the difference -(hit inside the predicted region, miss outside, else undetermined); a miss -contradicts the explanation. A candidate's D is the share of pairs of its -route's live explanations whose predictions for it conflict (scoring version -`mvp3-score-2`). The judge sees route summaries and readings only, never a -case or CONFIRM; each call's prompt, reply and cost is stored under -`probing/explanations/`, so a resumed run reads it back. The report is -`triage_report.scored_d.*`; every report now carries `outcomes` (each card -reading's FAIL-vs-control difference per route), and `compare.py` counts the -pairs of the explaining run's explanations each run's evidence tells apart. -Only each open layer's current candidate is offered for prediction. On -Qwen3.5-0.8B POPE (claude-opus-5 judge, two asks, 169 s) D reorders the -follow-ups but changes neither the set that runs nor the pairs of explanations -the final evidence tells apart (4/7 for every scheduler); under a tight budget -the judge's time costs coverage. The re-ask after the first S explanations were -all contradicted proposed one that patchscope then confirmed out of sample -(gold readable at no depth: peak probability FAIL - control -0.85). D does not -yet discount predictions the route's case count cannot decide. - -### Changed — triage budgets charge the evidence read - -`--triage-budget-sec` / `--triage-budget-usd` are checked against the evidence -the run reads, each observation at its first execution's cost, plus judge -calls (`cost.charged` in the report), not against everything the ledger has -recorded across invocations: a resumed run or a second scheduler on the same -ledger now decides as the first run did. - -### Added — triage scored scheduler (MVP-3, first part) - -`--triage-scheduler scored` replaces the rules' rounds with one decision at a -time: every feasible candidate (each active route's open or stale layer, the -expansion, the deferred battery steps) gets -`U = q·[D + T + C − R]₊ / (c + ε)` (`probing/scoring.py`, version -`mvp3-score-1`) and the highest wins, ties going to the soft order; taking a -later layer first is recorded as a soft-order exception. D is 0 until -competing explanations with predictions exist; T is 1 for extending a -`reuse` step to a route's new cases or a contradiction, 0.5 for an expansion -that may close a recorded gap; C is the coverage gap over `layer × gold -stratum` units the action removes; R filters an observation that already -exists; q is `(successes+1)/(attempts+2)` over the analyzer's distinct -observations (unsupported is not an attempt); c is the step's own cost per -case, else measured per-call rates, on the primary axis (USD when every -action is priced, else wall seconds). Every 10th decision explores with a -seed; no candidate above the gain floor (0.01) stops the run. While an -expansion can still follow, no batch-dependent candidate is taken (its reading -would be superseded; its layer waits rather than falling back). On -Qwen3.5-0.8B POPE it reaches the rules' follow-ups, readings and call counts -exactly, with twice the decisions (each expansion makes it extend what it ran -on the smaller sample): with D = 0 it only reorders. Decisions read -only the scheduler's own evidence and price candidates as if fresh, so a -shared ledger saves compute without changing choices; the report -(`triage_report.scored.*`) lists every candidate's components per decision. -Both schedulers' reports now carry `cost.evidence` (the first-execution cost -of every observation read), `cost.controller_sec` and `coverage`; -`probing/compare.py` compares two reports. `--triage-budget-usd` caps USD the -way `--triage-budget-sec` caps seconds. Adoption of earlier chunks is limited -to chunks inside the target, so no case enters the evidence without a -decision that asked for it. - -### Added — `prompt_contrast(gen_kwargs=...)`; describe-first gets its own output room +samples on the provider's side is not affected. `self_consistency` asks one +`generate` call per sample rather than one batch, so a seeded case draws the +same samples whatever the backend's batch size. + +### Added — `prompt_contrast(gen_kwargs=...)` `prompt_contrast` takes per-call generation settings for every re-ask (baseline included); without them it behaves as before (Qwen3.5-0.8B: every -reworded and threshold answer identical to the earlier run). The triage's -describe-first candidates ask for `max_new_tokens=256`, so they run under -POPE's 16-token cap where the backend honours per-call settings; on a -backend that drops them (OpenAI-compatible endpoint) the step runs without -them and is gated on the host's cap. Follow-up readings of a strategy that -asks for text before the answer add `extra_words_*` and `complied_*` (at -least 5 more words than the re-asked question), and the report warns when -most route cases did not comply: Qwen3.5-0.8B answers "No" straight away -(0/17 complied), so its unchanged answers do not test the question; -gemini-3.1-flash-lite describes first (15/15, about 21 extra words). - -### Added — triage expansion and rule-chosen follow-ups (MVP-2) - -`--m1-policy triage_active` (policy `mvp2-0`) keeps the nine-step battery and -then lets fixed rules decide what runs next (`probing/rules.py`, version -`mvp2-rules-1`). **Expansion** is a controller action: while a gap holds that -more cases can close — a positive FAIL-minus-PASS routing difference whose 95% -Newcombe interval still includes zero, or a gold stratum with fewer than 8 S -or stable PASS cases — the nested sample doubles up to `--triage-max-fail` -(default 32). A step's observations are now chunks over disjoint case sets -(`probing/evidence.py`): steps whose per-case rows do not depend on the batch -(`PlanStep.reuse`; audits, counterfactual swap with partition donors, -knockout, re-sampling, wrappers) run on the new cases only; `embed_lens` -and `patchscope` (question words inferred from the batch) are not read by any -route, so they run once, on the sample the expansions settle on. An observation index by step identity without the cases lets a -later invocation with a larger cap reuse earlier chunks. **Follow-ups**: each -route with at least 3 FAIL cases proposes, per round, the next candidate of -its first open layer (default representative, then fallbacks), on its FAIL -cases plus gold-matched PASS controls; a failed or refused candidate falls -back within its layer, a valid one advances, candidates the model cannot run -are passed over at no cost, and a layer done on fewer cases is extended -first. `--triage-max-actions` (default 12) caps the decisions; `--triage-budget-sec` -also skips an action whose estimate exceeds what is left. Every decision is a -trace event naming its rule, condition and what it passed over; the report -adds sample revisions, decisions, descriptive follow-up readings (route FAIL -vs controls) and every route's layer states. Report keys changed: `steps` is -now `executions`; `next_candidates` and `probing/proposals.py` are gone (the -rules run the candidates instead of listing them). An edit refused on any -chunk refuses the step on every case. The MVP-0 entry point -`run_triage_mvp0` is the same controller. - -### Added — triage on API models: provider usage, dollars, next experiments (MVP-1) - -The gemini runtime now sums the token counts every response reports -(`state["usage"]`: prompt, completion and thought tokens, plus responses that -reported none), and `APIModel.usage_counters()` exposes them with the request -and retry counts. The triage executor differences two reads around each -action (`cost["api_usage"]`), the runner does the same around Stage 0 -(`baseline.json` gains `api_usage` and `usd`), and `usd` comes from a dated -price table (`models/backends/api/prices.py`: only prices read off the -provider's page, checked 2026-10-17; an unlisted model's cost is `None`, never -a guess, and the input part is an upper bound because implicit cache hits are -not reported). The report adds a cost summary for the invocation. On the -gemini backend the U sampling check now runs: the runtime merges per-call -kwargs over its own sampling, so `self_consistency` gets `temperature=1.0` -(the endpoint backend drops per-call kwargs and stays untested). The report -also listed rule-based next candidates for every route with FAIL cases, each -gated on the actual model (superseded in MVP-2, which runs them). +reworded and threshold answer identical to the earlier run). A strategy +that asks for text before the answer adds `extra_words_*` and `complied_*` +readings (at least 5 more words than the re-asked question): Qwen3.5-0.8B +answers "No" straight away under a describe-first instruction (0/17 complied), +so its unchanged answers do not test the question; gemini-3.1-flash-lite +describes first (15/15). ### Fixed — logit margins compared an answer with its own other spelling @@ -999,32 +658,6 @@ forms and counts a layer as reading the answer when any form ranks first. Knockout and other margins measured with a decoder-backed tokenizer before this change are not comparable with new ones. -### Added — triage U and S routes (policy `mvp0-2`) - -The triage plan now runs five more actions after the knockout. U (an answer -that moves) has two required parts: `self_consistency`, run once per case -(the executor's new `per_case` mode, since the analyzer reads only -`cases[0]`) at the host's sampling settings (`temperature=1.0` plus the run's -`top_p`/`top_k` on local backends; greedy settings leave it untested), and -`prompt_contrast` with the question kept verbatim inside two neutral wrappers -(a wrapper whose answer is unreadable is an invalid control). Answers are -compared with the task's new label-blind `answer_key` (`benchmark.scoring`, -`tasks.answer_key`), never graded. S is a FAIL case on which H, N (cases with -media; N is now `not_applicable` without media) and both U parts ran and none -fired; a missing check leaves it in X, and a PASS case with every check clear -has no route. The S readings on every case are descriptive: a threshold -instruction (`prompt_contrast` "sensitive", yes/no tasks only; others record -the step as `not_applicable`), `embed_lens(layer=0.9)` and -`patchscope(target="gold", media_layers=3)`. Both lenses gain a question-word -reading — prompt words found in at most half of the batch's distinct prompts -(`_internals/words.py`), so template words never count: `el_query_sim`, and -`ps_media_query_hits`/`_share` (media tokens decoded as the case's question -word). Patchscope's patch self-check now raises `FidelityError` (still a -`RuntimeError`) and reports `patch_fidelity`, so the triage records an -unfaithful patch as `unfaithful`. `prompt_contrast` also keeps untruncated -outputs as an `outputs` artifact, and the executor keeps a step's named -result artifacts with its findings (`keep_artifacts`). - ### Added — counterfactual swap donors (`modality_ablation(donor_rule="counterfactual")`) An unchanged answer after a media swap is only evidence when the donor's @@ -1038,14 +671,9 @@ a donor whose gold equals the wrong answer makes "unchanged" correct); that gold is what a correct answer must become, recorded as `ablation__donor_expected`. Otherwise it falls back to the content rule and records `ablation__donor_kind="content"`. `n_counterfactual_` -counts the former. The default `donor_rule="content"` is unchanged. The triage -controller uses the counterfactual rule with the whole EXPLORE partition as -the pool; on yes/no and letter tasks, N is tested only on counterfactual swaps -(content-only swaps leave it untested with the reason), and the report adds -donor kinds and how often a counterfactual swap moved the answer to the -donor's gold. +counts the former. The default `donor_rule="content"` is unchanged. -### Changed — edit-free self-checks run on every analysed case +### Changed — edit-free self-checks run on every analysed case and raise `FidelityError` `attention_knockout`, `attention_sensitivity`, `attention_temperature` and `generic_attention` used to check the attention tap (and, on hybrid stacks, the @@ -1061,25 +689,10 @@ case per mechanism, the number of argmax changes and every per-case check. `check_fidelity` accepts the caller's native logits (`base=`) to save a forward. Cost: one extra tapped forward per case (plus one linear re-run on a hybrid stack). Under `sdpa` these analyzers will now usually refuse on -Qwen3.5; use `--attn-impl eager`, where the tap is exact. The triage -controller's action identity now includes a content hash of the analyzer's -module and `analyzers/_internals`, so a code change re-runs the action instead -of reading back an old observation. - -### Added — triage probing controller, MVP-0 (`--m1-policy triage_active`) - -An opt-in alternative to the judge-selected M1 (`evalrx/eval_agent/probing/`). -After Stage 0 and the usual EXPLORE/CONFIRM split, a host-side controller runs -a fixed plan — `answer_extraction_audit`, `termination_audit` (no -continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="gold")` -— on a matched, nested FAIL/PASS sample of EXPLORE, exactly as planned (no -backfill, cap or generated probes), and writes `selection_trace.jsonl`, -`cost_ledger.jsonl`, per-action observations and a triage report (H/N/X route -labels traced to case, field, action and fidelity verdict) under -`/probing/`. Outcomes are typed (`ok` / `unsupported` / `failed` / -`unfaithful`) and never written as zeros; a rerun reads finished actions back -instead of re-running them. No judge is called and M2–M5 do not run. The -default `--m1-policy judge` path is unchanged. +Qwen3.5; use `--attn-impl eager`, where the tap is exact. The refusal is a +`FidelityError` (a `RuntimeError` subclass carrying the check's `verdict`), also +raised by `require_fidelity` and `require_edit_fidelity`, so callers can tell an +untrustworthy edit from an ordinary failure without parsing the message. ### Fixed — `modality_ablation(mode="swap")` could swap in the same media @@ -1091,13 +704,6 @@ pixels), each row records `ablation__donor` and the compared answers, and `n_drop_fallback_` counts cases that had to fall back to drop. `drop` mode output is unchanged. -### Changed — fidelity refusals raise `FidelityError` - -`require_fidelity` and `require_edit_fidelity` raise -`evalrx.analyzers._internals.attn_tap.FidelityError` (a `RuntimeError` -subclass carrying the check's `verdict`), so callers can tell an untrustworthy -edit from an ordinary failure without parsing the message. - ## [0.2.0] — 2026-11-14 ### Changed — the run logger and its readers lose their "V2" names diff --git a/docs/agentic_benchmark.md b/docs/agentic_benchmark.md index 65116f8b..2db5bb77 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -21,7 +21,7 @@ Agentic repair does not inject built-in floor candidates. The agent can still pr ## Triage policy (opt-in) -`--m1-policy triage_active` replaces the diagnosis with a host-side triage controller (`evalrx/eval_agent/probing/`, design in `evalsmith/probing/probing_design_mix.md`). The default `--m1-policy judge` is unchanged. +`--m1-policy triage_active` replaces the diagnosis with a host-side triage controller (`evalrx/eval_agent/triage/`; not `evalrx/probing/`, the probe catalog the judge-driven M1 calls). The default `--m1-policy judge` is unchanged. ```bash python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend hf_local \ @@ -29,21 +29,17 @@ python -m evalrx.benchmark.run --modality vlm --model qwen3.5-0.8b-vl --backend --m1-policy triage_active --run-tag triage0 ``` -After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="prediction")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="prediction", media_layers=3)` — with no backfill, case cap or generated probes. After the battery, fixed rules choose what runs next (see below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.{json,md}` with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. +After Stage 0 and the same EXPLORE/CONFIRM split as the loop, it draws `--triage-n-fail` FAIL cases (default 8) and gold-matched PASS controls from EXPLORE with a nested sampler, then runs a fixed battery exactly as written — `answer_extraction_audit`, `termination_audit` (no continuation), `modality_ablation(mode="swap")`, `attention_knockout(target="prediction")`, `self_consistency` (5 samples per case), `prompt_contrast` with two neutral wrappers around the verbatim question, `prompt_contrast` with an instruction not to default to a negative answer (yes/no tasks only), `embed_lens(layer=0.9)` and `patchscope(target="prediction", media_layers=3)` — with no backfill, case cap or generated probes. After the battery the scored scheduler chooses what runs next, one action at a time (`--triage-scheduler rules` takes fixed rounds instead; both below). No judge is called (unless `--triage-explanations judge`, below), M2–M5 do not run, and CONFIRM never reaches the controller. Outputs go to `/probing/`: `selection_trace.jsonl` (every action and every decision with its rule, condition and the candidates it passed over), `cost_ledger.jsonl` (each Stage 0 invocation separate from the actions' new calls), `observations/.json` with an `index.jsonl`, `split_manifest.json` (every sample revision), and `triage_report.scored.{json,md}` (`triage_report.{json,md}` under `--triage-scheduler rules`) with H/N/U/S/X route labels traced to case, field, action and fidelity verdict. Outcomes are typed (`ok`, `unsupported`, `failed`, `unfaithful`) and never written as zeros. Rerunning the same command reads finished actions back by content identity instead of re-running them; `--triage-budget-sec` skips an action once the budget is spent or once the estimate of its next chunk exceeds what is left: the step's own measured seconds per case in this run, else the most expensive case measured so far (no per-analyzer cost prior: costs measured across input sizes do not keep their ratios, see below). The budget is charged with the evidence the run reads, each observation at the cost of its first execution, plus its judge calls, so a resumed run, or a second scheduler on the same ledger, is charged what its evidence cost rather than what this invocation happened to execute. -**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 32; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Every step's per-case rows are independent of the batch, so steps run on the new cases alone and keep the old rows: `embed_lens` and `patchscope` tell question words (and `embed_lens` recurring media words, from the first 16 distinct images) from a fixed reference — EXPLORE in the sampler's rank order — instead of the batch, `tuned_lens` is fit once on the first 32 of those cases (cached on the model), and `causal_trace` seeds its noise from each case's content instead of its position; `self_consistency` draws each case's samples under a seed of its content too, so the U sampling check is the same in every run. No route reads `embed_lens` or `patchscope`, so they still wait until the sample stops growing. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. An expansion's battery runs chunk by chunk too, every immediate step on one chunk of the new cases before any step moves to the next, each chunk checked against the budget (the decision to expand is checked on an estimate from the cases measured so far, which undershot by 30 % on ChartQA where the later cases were dearer); a refusal stops the run there, the chunks measured so far are routed, and a check that never ran on the remaining new cases is untested (a case with no fired check is X). Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_probing_mvp2.py`). +**Expansion.** At the start of each round the sample doubles along the sampler's rank prefixes, up to `--triage-max-fail` FAIL cases (default 128; at or below `--triage-n-fail` disables it), while a gap holds that more cases can close: a route whose FAIL-minus-PASS difference is positive while its 95% interval (Newcombe) still includes zero, or a gold stratum whose S cohort or stable PASS controls has fewer than 8 cases. The battery then runs again only where it must. Every step's per-case rows are independent of the batch, so steps run on the new cases alone and keep the old rows: `embed_lens` and `patchscope` tell question words (and `embed_lens` recurring media words, from the first 16 distinct images) from a fixed reference — EXPLORE in the sampler's rank order — instead of the batch, `tuned_lens` is fit once on the first 32 of those cases (cached on the model), and `causal_trace` seeds its noise from each case's content instead of its position; `self_consistency` draws each case's samples under a seed of its content too, so the U sampling check is the same in every run. No route reads `embed_lens` or `patchscope`, so they still wait until the sample stops growing. Each step's observations are chunks over disjoint case sets, indexed by the step's identity without its cases, so a later invocation with a larger cap also reads earlier chunks back and runs only uncovered cases. An edit whose self-check refuses on any chunk is refused on every case. Steps run in chunks of `--triage-chunk` cases (default 8, FAIL and PASS alternating), with the budget checked before each chunk, so an action whose cost nobody knew overshoots by at most one chunk; a chunk that raises stops the rest of the step. An expansion's battery runs chunk by chunk too, every immediate step on one chunk of the new cases before any step moves to the next, each chunk checked against the budget (the decision to expand is checked on an estimate from the cases measured so far, which undershot by 30 % on ChartQA where the later cases were dearer); a refusal stops the run there, the chunks measured so far are routed, and a check that never ran on the remaining new cases is untested (a case with no fired check is X). Drawing 8 FAIL cases at once and expanding from 4 give every case the same record for the same calls (`tests/test_eval_agent/test_triage_expansion.py`). -**Rule-chosen follow-ups.** Each route has ordered layers (`evalrx/eval_agent/probing/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 12), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. +**Layers and the fixed rounds.** Each route has ordered layers (`evalrx/eval_agent/triage/rules.py`), each a question with a default representative and fallbacks: H1 stricter re-ask, H2 continuation; N1 the knockout (fallback `causal_trace`), N2 `attention_temperature` → `attention_sensitivity`, N3 describe-the-media-first; U1 `logprob_entropy` → `self_consistency(n=10)`, U2 `format_sensitivity` (letter tasks); Sb describe-first, S1 `gradcam` → `generic_attention`, S2 `embed_lens`, S3 `patchscope` → `tuned_lens` → `layer_contrast`; X1 media removed instead of swapped. A layer is done once a candidate (or the battery step serving it) gave a valid observation on the route's FAIL cases, and exhausted once every candidate is gated off, failed or refused; a failure moves to the next fallback of the same layer, a valid result to the next layer. Under `--triage-scheduler rules` each round every route with at least 3 FAIL cases proposes one candidate — H first, then by FAIL count — which runs on the route's FAIL cases and as many gold-matched PASS cases; candidates the model cannot run are passed over at no cost, so an API run goes straight to the behavioural ones. A layer done on a smaller sample is extended to the route's new cases first. The run stops when no route has a candidate, after `--triage-max-actions` decisions (default 30), or on the budget. Follow-up readings are means per route FAIL cohort and PASS controls, with the number of cases behind each: descriptive, no test, no mechanism named. Describe-first asks for 256 output tokens per call (POPE's own cap is 16); a backend that drops per-call settings is gated on the host's cap instead. Its readings include whether the model actually wrote a description first (`complied_*`, at least 5 more words than the plain re-ask), and the report warns when most cases did not: an unchanged answer from a model that never described does not test the question. -**Scored scheduler.** `--triage-scheduler scored` (report `triage_report.scored.{json,md}` next to the rules' report, sharing the ledger) makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/probing/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet (a budget check prices such a step at the run's most expensive case per case instead, so an unknown tool cannot look cheap; a step that ran without calling the model, like the audits of stored outputs, is priced at what it measured); one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the evidence spending, `--triage-explore-share` (default 0.1; the judge's calls are not counted), not of the decisions, and draws from its own targets — actions the value never takes: the next candidate of a route with too few FAIL cases to be active, and on each active route the representative of every other route's layer it does not own, when that step has readings to compare with the controls. Whenever a target fits — exploration's spending plus its conservative estimate (a budget check's) within the share — a seeded draw among them runs instead of the best candidate. Completing a target on its route is exploration too, paid from the share, until the cases measured so far show a reading outside its band (the verdicts' 95% interval): the step has then found something, and its completion is an incomplete step that T values like any other. The run stops once no candidate's gain reaches 0.01 and no target fits. `--triage-explore-from candidates` (an ablation) draws from the candidates other than the best instead, alternatives included. `--triage-weights` (e.g. `c=0`) sets the weights of D, T, C and R for ablations. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units, which `evalrx/eval_agent/probing/compare.py` puts side by side. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. +**Scored scheduler.** `--triage-scheduler scored`, the default (report `triage_report.scored.{json,md}`; a run under the rules writes its own report beside it and shares the ledger), makes one decision at a time: every feasible candidate — the next chunk of each active route's open or unfinished layer, the alternatives of its answered layers, the expansion, and the deferred battery steps not yet run on the current sample — gets `U = q·[D + T + C − R]₊ / (c + ε)` (`evalrx/eval_agent/triage/scoring.py`) and the highest wins, ties going to the soft order. D (prediction disagreement) is 0 until competing explanations with predictions exist; T is 1 for completing a step measured on part of a route (spread over its chunks by the share of the remaining FAIL cases each covers, as are D and R) or resolving a contradiction, and 0.5 for an expansion that may close a recorded gap; C is the coverage gap over layer × gold-stratum units the action removes; R filters observations that already exist (R = 1), and prices an answered layer's other candidates, its *alternatives*: 0.5 when one gives the kind of evidence the tool that answered the layer gave (`PlanStep.evidence`: a second attention rescaling, relevance map or layer readout), 0 when it gives another kind (a different intervention, e.g. `causal_trace` after the knockout). An alternative closes no gap and covers no unit, so it runs only on a D above its R; q is the analyzer's smoothed success rate in this run; c is the step's own measured cost on the primary axis (USD when every action is priced, else seconds), or the run's median cost per case for a step that has not run yet (a budget check prices such a step at the run's most expensive case per case instead, so an unknown tool cannot look cheap; a step that ran without calling the model, like the audits of stored outputs, is priced at what it measured); one chunk of it shows the real cost before the next decision. Further chunks of a step already taken do not count against `--triage-max-actions`. Exploration has a share of the evidence spending, `--triage-explore-share` (default 0.1; the judge's calls are not counted), not of the decisions, and draws from its own targets — actions the value never takes: the next candidate of a route with too few FAIL cases to be active, and on each active route the representative of every other route's layer it does not own, when that step has readings to compare with the controls. Whenever a target fits — exploration's spending plus its conservative estimate (a budget check's) within the share — a seeded draw among them runs instead of the best candidate. Completing a target on its route is exploration too, paid from the share, until the cases measured so far show a reading outside its band (the verdicts' 95% interval): the step has then found something, and its completion is an incomplete step that T values like any other. The run stops once no candidate's gain reaches 0.01 and no target fits. While an expansion can still follow, batch-dependent candidates wait (any expansion would supersede them). With D = 0 the value of a candidate does not depend on what earlier actions found, so the scored scheduler only reorders: on Qwen3.5-0.8B POPE it reaches the rules' follow-ups and readings exactly, with twice the decisions. Decisions read only the scheduler's own evidence and price candidates as if they ran fresh, so a shared ledger saves compute without changing choices. Each decision lists every candidate's components; both schedulers' reports carry the evidence cost at first execution, the controller's own time and the coverage units. `--triage-budget-usd` caps API spend like `--triage-budget-sec` caps seconds. -**Controls.** `--triage-scheduler random` and `--triage-scheduler cheapest` (reports `triage_report.random.*` / `triage_report.cheapest.*`) decide over the scored scheduler's candidates with its budget, gain floor and stop rules, and differ in the pick only: a seeded uniform draw among the candidates at or above the gain floor, or the lowest-cost one (ties by soft order). They never explore and take no explainer, so the scored scheduler without exploration is their nearest value arm; the comparison isolates the value ordering from the candidate set. +**Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/triage/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample). Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. -**Competing explanations (D).** With `--triage-scheduler scored --triage-explanations judge`, the chain's judge (`--judge-provider` / `--judge-model`, built without the coder checks since triage runs no coding stage; it must not be the model under test) proposes, per active route, up to three competing local explanations of why the route's FAIL cases fail, each predicting `up` / `down` / `same` / `unknown` for the readings of every tool still to run there: the direction of FAIL mean − PASS control mean against a band fixed per reading (`CARDS` in `evalrx/eval_agent/probing/explanations.py`; the judge picks directions, never the reading, comparison or threshold). It is asked once the sample has settled (an expansion revises the routes), and again, at most three asks in all, when the evidence has decided a prediction and a route with tools left has fewer than two live explanations; each ask sees the previous verdicts. Code checks every prediction: a hit when the 95% interval of the difference lies inside the predicted region, a miss outside it, else undetermined; an explanation with a miss is contradicted and leaves the live set at the next decision. A candidate's D sums, over the pairs of its route's live explanations whose predictions for it conflict, how decidable the conflict is on the route's cases, and divides by the number of pairs (a pair with `unknown` counts only in the denominator). Decidability takes each prediction in turn as true at a reference difference (0 for `same`, one standard deviation of the reading beyond the band for `up`/`down`) and asks how many cases a side the verdict's interval needs to contradict the other: each side scores `min(1, n / needed)` with the route's n FAIL cases, and the conflict the mean of the two sides. The spread comes from every case the step measured in this run; before that a share's spread is taken at its largest and a mean's band as negligible next to its spread, so an unmeasured "same" can never be contradicted and an up-versus-same conflict counts at most half. Three FAIL cases settle an unmeasured up-versus-same conflict to 1/6, sixteen to 1/2. The judge sees route summaries and readings of EXPLORE, never a case's content, media or CONFIRM; prompts, replies and costs are stored under `explanations/.json`, so a resumed run reads replies back. A CLI judge reports no tokens, so its calls are charged in seconds; the judge's availability probe at start-up is not counted. A call is charged like an action: the judge is asked only while the largest call so far still fits the budget, so a run overshoots by at most its first call, whose cost nobody knows yet. The report is `triage_report.scored_d.{json,md}`, with each explanation's predictions and verdicts on the final evidence and whether the judge had already seen part of a reading when it predicted (such a hit is not out of sample); `compare.py` applies the explaining run's last explanations to both runs' final readings and counts the pairs each run's evidence tells apart. Each open layer's current candidate is offered for prediction, and every layer's other candidates as alternatives (`alternative_to`: the tool that answered the layer, or its current candidate), so their predictions exist once the layer is answered. On Qwen3.5-0.8B POPE decidability cuts D on the three-case N route from 0.67-1.0 to 0.11-0.22; of the 19 alternatives five D arms ran, 7 were chosen on value (mostly `self_consistency_n10` after `logprob_entropy`, another kind of evidence) and 12 by exploration, and the judge's three asks (about 130 s each) cost about 30% of the evidence time. - -**Diagnostic validation (MVP-4).** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); `--confirm-split-by media` instead draws the explore/confirm split over media groups, whole images on one side, so nothing is left out (default `case`: the judge-driven loop's split, which a triage run must share to be compared case for case); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/probing/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. - -**Multi-arm protocol.** The scheduler comparison (rules, scored, scored without exploration, scored with D, random, cheapest; each at the full budget and at budget tiers) runs every arm into one run directory on a shared ledger, copies each arm's report aside as `triage_report...json`, then validates the union of the arms' frozen families once. The drivers of that comparison are experiment scripts kept outside the package; `python -m evalrx.eval_agent.probing.compare a.json b.json` puts two arms' reports side by side. +**Diagnostic validation.** The data roles are fixed before the controller sees a case and written to `/partition_bundle.json`: DISCOVERY is EXPLORE; DIAGNOSTIC_VALIDATION is the CONFIRM partition minus every case whose media content also appears in DISCOVERY (on POPE, where each image carries a yes and a no question, the other question about a seen image is not a new image); `--confirm-split-by media` instead draws the explore/confirm split over media groups, whole images on one side, so nothing is left out (default `case`: the judge-driven loop's split, which a triage run must share to be compared case for case); repair CONFIRM is not part of this protocol. `--triage-validation-source MANIFEST` adds a validation-only source: cases the controller and the judge never see, labelled by their own Stage 0 pass (`/baseline_validation_source.json`) and joining DIAGNOSTIC_VALIDATION under the same media rule, the bundle recording where its cases came from (ChartQA: `python -m evalrx.benchmark.tasks.chartqa --exclude /manifest.json` freezes the human-authored rows the discovery pool left, the rest of the test split and the val split). With `--triage-validate` the issues the triage report supports on DISCOVERY are frozen (`evalrx/eval_agent/triage/validation.py`): a route signal (a label-free H/N/U check firing more on FAIL than on matched PASS by more than 0.1, its whole 95% interval above that), or a reading difference on a route's FAIL cases against its matched controls beyond the reading's band (one issue per route and step, the reading furthest outside its band; a step re-measuring the check its route is cut on, or reading what it implies (the output's close calls on U), is left out). The family, a power plan from DISCOVERY only (the validation cases each issue should have and those it needs at the discovery effect) and the partition are written to `/validation/frozen.json` before any validation case is read; then the route checks run on all validation FAIL cases and their matched PASS controls, each reading issue's step runs on its route, and every issue is judged on its interval at `1 - 2·0.05/K`, a one-sided test at 0.05/K on the side its direction claims (Bonferroni over the K issues): `supported`, `refuted`, `inconclusive` or `unavailable`. Several readings can say one thing, so two reading issues of a route whose per-case values go together on the validation cases, within the FAIL cases and within the controls (pooled within-group Spearman |rho| >= 0.5; a FAIL-vs-control shift alone does not count), are one phenomenon; each arm is credited with its own issues grouped that way. Where a correlation lies near the threshold the count depends on it, so the main metric is the number of supported phenomena over a grid of thresholds (0.3 to 0.7 in steps of 0.05), and an arm found more than another only where it has more at every threshold of the grid. No card reading reads the label: steps with a target read the model's own answer (`target="prediction"`), since a gold margin lower on FAIL cases restates that they are wrong, and a carded step targeting gold is refused. The validator uses the DISCOVERY-fixed artefacts (lens references, the tuned lens's fit set), draws swap donors from the validation cases, and writes its own ledger and `validation_report.{json,md}`; the judge's explanations live at the stop are frozen with the family (a re-ask keeps the live ones and adds competing new ones, so none is lost to a later ask); each names one or two primary predictions (the readings it stands or falls on; competing explanations must differ on one), on tools still to run on the route or already run there (with their readings in view: a fit during the triage, tested on new cases, no D), only those keep it live during the triage and enter D, and the validator runs their steps on the route's validation cases, tests the distinct primary predictions as one one-sided Bonferroni family and calls each explanation `supported`, `refuted`, `undecided` or `untestable` (other predictions reported at 95%; reported apart, not counted); a prediction on a reading the route is cut on or that it implies (re-sampling or the output's close calls on U) is never asked of the judge, and a route with only such steps left does not trigger a re-ask, and one met in an older report is labelled `definitional`, neither support nor contradiction. `--triage-validation-budget-sec` caps the validation's evidence. The swap uses counterfactual donors drawn from the whole EXPLORE partition: a case asking the identical prompt about different media whose gold differs from the model's own answer, so a correct answer has to change (relative to the model's answer, not the case's gold, because on a failed case the two differ). On yes/no and letter tasks only such swaps test N; cases without one are reported as untested, so a larger `--limit` raises coverage (on POPE adversarial the questions repeat per object across images). Open-answer tasks also accept content-only swaps, recorded with that assumption. From 6ec8bc956710aff0ead9d987b9a1cc7017014fbd Mon Sep 17 00:00:00 2001 From: Jiaqi Liu <32996169+jiaq-liu@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:54:24 -0700 Subject: [PATCH 26/26] Read the encoder's output as a ModelOutput in the no-grad test Under transformers 5 the vision tower returns a BaseModelOutputWithPooling, not a tensor, so the test's forward hook read requires_grad off the wrapper and saw False on a plain forward. The probe now looks at the tensors inside a tensor, ModelOutput or tuple. media_encoders_without_grad is unchanged. --- tests/test_models/test_media_encoders_no_grad.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/test_models/test_media_encoders_no_grad.py b/tests/test_models/test_media_encoders_no_grad.py index 1c499787..e92dae0b 100644 --- a/tests/test_models/test_media_encoders_no_grad.py +++ b/tests/test_models/test_media_encoders_no_grad.py @@ -42,11 +42,18 @@ def _inputs(): return enc +def _requires_grad(out) -> bool: + """Whether an encoder's output carries a graph: a tensor (transformers 4) or a + ``ModelOutput`` / tuple of tensors (transformers 5).""" + parts = [out] if torch.is_tensor(out) else list(out.values() if hasattr(out, "values") else out) + return any(t.requires_grad for t in parts if torch.is_tensor(t)) + + def _visual_output_requires_grad(module, enc) -> "tuple[bool, bool]": """``(the vision tower's output requires grad, the logits do)`` for one forward.""" seen = [] (name, visual), = media_encoders(module) - handle = visual.register_forward_hook(lambda m, i, out: seen.append(bool(getattr(out, "requires_grad", False)))) + handle = visual.register_forward_hook(lambda m, i, out: seen.append(_requires_grad(out))) try: with torch.set_grad_enabled(True): out = module(**enc)