diff --git a/CHANGELOG.md b/CHANGELOG.md index 631cf8a4..8868eea2 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -514,6 +514,196 @@ 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. + +### 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 + +`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 batch. + +### 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. `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). 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 + +`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 — 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. + +### 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 +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 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 + +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. + ## [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 8e0add01..2db5bb77 100644 --- a/docs/agentic_benchmark.md +++ b/docs/agentic_benchmark.md @@ -19,6 +19,42 @@ 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) + +`--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 \ + --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 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 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`). + +**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`, 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. + +**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. + +**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. + +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. + +```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 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/docs/analyzers.md b/docs/analyzers.md index fc1cf1e1..230b8446 100644 --- a/docs/analyzers.md +++ b/docs/analyzers.md @@ -118,9 +118,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/_internals/attn_tap.py b/evalrx/analyzers/_internals/attn_tap.py index dbab76f6..087fa5d1 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: @@ -317,41 +320,56 @@ 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): + """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, @@ -359,11 +377,12 @@ def require_fidelity(model: "Model", inputs: Any, *, rtol: float = 1e-2, """: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..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 @@ -19,7 +20,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: @@ -58,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: @@ -69,11 +172,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/_internals/linear_mix.py b/evalrx/analyzers/_internals/linear_mix.py index a5aa4614..8c33715a 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/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/targets.py b/evalrx/analyzers/_internals/targets.py index e993f21a..b34d7037 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 tid is not None and 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..15121540 --- /dev/null +++ b/evalrx/analyzers/_internals/words.py @@ -0,0 +1,104 @@ +"""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 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 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 +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 + + +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/attribution/generic_attn.py b/evalrx/analyzers/attribution/generic_attn.py index dea6e168..eba44926 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" @@ -102,7 +104,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, @@ -121,13 +124,12 @@ 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) + def measure(case: Any) -> None: + nonlocal first + gate.check(case.id, case.inputs) abar: dict[int, Any] = {} recorded: dict[int, Any] = {} @@ -154,7 +156,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 — " @@ -203,6 +205,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) @@ -213,7 +227,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/attribution/gradcam.py b/evalrx/analyzers/attribution/gradcam.py index 68c7850d..ed269054 100755 --- a/evalrx/analyzers/attribution/gradcam.py +++ b/evalrx/analyzers/attribution/gradcam.py @@ -105,19 +105,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( @@ -146,6 +147,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/analyzers/lens/embed_lens.py b/evalrx/analyzers/lens/embed_lens.py index 515d92cf..3bd945d4 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 @@ -23,7 +25,15 @@ 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 (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 @@ -46,6 +56,12 @@ from collections import Counter from typing import TYPE_CHECKING, Any +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 @@ -56,17 +72,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. @@ -81,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" @@ -102,6 +113,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."), } layer: 'int | float' @@ -110,18 +122,23 @@ class EmbedLensAnalyzer(Analyzer): min_images: int norm_ratio: float vocab_chunk: int + reference: 'CaseBatch | None' + reference_media: int max_cases: int 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 @@ -134,7 +151,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) @@ -167,13 +183,51 @@ 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.""" + reference = list(self.reference or []) + key = (layer, self.recurring_frac, self.min_images, self.reference_media, + tuple(str(c.id) for c in reference)) + cache = module.__dict__.setdefault("_evalrx_embed_lens_reference", {}) + if key not in cache: + counts: Counter = Counter() + seen: set = set() + for ref in 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]] = {} + 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() 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) @@ -201,12 +255,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] = { @@ -216,6 +267,9 @@ 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)) + texts[case.id] = str(case.inputs.prompt) row: dict[str, Any] = { "sample_id": case.id, "el_n_media_tokens": len(media), @@ -232,10 +286,24 @@ 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) + 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=lambda w: sims[w]) + 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() + 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 for row in rows: @@ -252,10 +320,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 @@ -267,7 +335,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)} @@ -277,17 +347,20 @@ 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 " - 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." ), } 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 9ed09da7..c3532b38 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,17 @@ * ``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 (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 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 +46,13 @@ from collections import Counter from typing import TYPE_CHECKING, Any +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 @@ -48,17 +63,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") @@ -73,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). @@ -88,12 +95,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."), } target: str @@ -101,13 +110,15 @@ class PatchscopeAnalyzer(Analyzer): n_points: int media_layers: int batch_rows: int + reference: 'CaseBatch | None' max_cases: int 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 @@ -120,7 +131,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) @@ -172,14 +183,23 @@ 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]]] = {} + 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)), @@ -187,6 +207,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: @@ -194,31 +215,40 @@ 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}) + 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] = {} @@ -233,6 +263,21 @@ def grab(mod, args, kwargs): if not per_case: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") + 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: + read = media_words.get(row["sample_id"]) + asked = query.get(row["sample_id"]) or set() + if read is None or not query_inferred: + continue + decoded = [(w or "").strip().lower() for layer_words in read.values() for w in layer_words] + found = sorted({w for w in decoded if w in asked}) + row["ps_media_query_hits"] = sum(1 for w in decoded if w in asked) + 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": @@ -251,6 +296,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") @@ -266,6 +312,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/lens/tuned_lens.py b/evalrx/analyzers/lens/tuned_lens.py index 66717f83..fc02567d 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. @@ -24,7 +27,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability @@ -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. @@ -104,13 +109,15 @@ class TunedLensAnalyzer(Analyzer): lr: float seed: int translators_path: 'str | None' + fit_cases: 'CaseBatch | None' max_cases: int 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 @@ -124,17 +131,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}) @@ -142,13 +155,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 cast("list[list]", train)] # rows is non-empty - 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 = [] @@ -187,35 +211,45 @@ 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: + if data is None: + raise ValueError("tuned_lens: no training states and no key of a cached fit") + 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 @@ -227,6 +261,8 @@ def _translators(self, model: Any, data: list, W: Any, apply_norm: Any, n_layers cache[key] = fitted return fitted + if data is None: + raise ValueError("tuned_lens: no training states for a fit that is not cached") gen = torch.Generator().manual_seed(self.seed) final = data[n_layers] translators, fit_kl = [], [] diff --git a/evalrx/analyzers/patching/attention_knockout.py b/evalrx/analyzers/patching/attention_knockout.py index 66e8c383..8846a5d7 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" @@ -107,7 +109,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 @@ -123,7 +125,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) @@ -135,9 +137,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]) @@ -176,7 +176,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 4ef3504a..04ec5b03 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" @@ -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.analyzers.patching.attention_knockout import layer_bands from evalrx.core.model import CaptureSpec @@ -115,7 +117,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) @@ -127,9 +129,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()) @@ -165,7 +165,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 206f58c7..092692ff 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" @@ -112,11 +113,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 @@ -133,7 +131,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) @@ -141,13 +140,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] = [] @@ -205,7 +205,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/patching/attribution_patching.py b/evalrx/analyzers/patching/attribution_patching.py index ed8443c6..a891f497 100644 --- a/evalrx/analyzers/patching/attribution_patching.py +++ b/evalrx/analyzers/patching/attribution_patching.py @@ -231,6 +231,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, @@ -295,7 +296,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: tuple[Any, dict, tuple[Any, Any]] = (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 @@ -321,7 +322,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 a22ca544..8244ddfc 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. """ @@ -267,7 +269,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) @@ -290,7 +292,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/perturbation/modality_ablation.py b/evalrx/analyzers/perturbation/modality_ablation.py index 16b9c4e2..c2887f64 100644 --- a/evalrx/analyzers/perturbation/modality_ablation.py +++ b/evalrx/analyzers/perturbation/modality_ablation.py @@ -20,7 +20,22 @@ 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. + +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 @@ -31,6 +46,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 @@ -45,6 +62,49 @@ 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: + """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") @@ -59,11 +119,28 @@ 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_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).", '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 +150,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.'), @@ -86,6 +166,8 @@ class ModalityAblationAnalyzer(Analyzer): slots: 'tuple[str, ...] | None' score_fn: Optional[Callable[['FailureCase', str], Optional[bool]]] max_cases: int + donor_rule: str + donor_pool: 'CaseBatch | None' def __init__( self, @@ -93,22 +175,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]": @@ -119,16 +214,51 @@ 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. + + 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. + """ + own = key_of(getattr(case.inputs, slot)) + 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*. - 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 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. """ - for other in cases: - if other.id != case.id and getattr(other.inputs, slot, None) is not None: - return getattr(other.inputs, slot) + 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: @@ -141,35 +271,59 @@ 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] = {} + 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 - # One batch: each case as asked (the control, asked again rather than - # read from ``case.observed``) and once per ablated slot. - plan: list[tuple[Any, list[tuple[str, str]]]] = [] + # Two batches. First each case as asked (the control, asked again rather + # than read from ``case.observed``); then once per ablated slot, as a + # counterfactual donor is chosen by the answer the control gave. + base_answers = [str(out) for out in model.generate_batch([case.inputs for case in selected])] + plan: list[tuple[Any, str, list[tuple[str, str, Any]]]] = [] asked: list[Any] = [] - for case in selected: - asked.append(case.inputs) - ablations: list[tuple[str, str]] = [] + for case, base_answer in zip(selected, base_answers): + ablations: list[tuple[str, str, Any]] = [] for slot in self._slots_of(case): - donor: Any = self._donor(selected, slot, case) if self.mode == "swap" else None + found = find_donor(slot, case, _norm_answer(base_answer)) if swap else None + donor: Any = 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. - ablations.append((slot, "swap" if donor is not None else "drop")) + ablations.append((slot, "swap" if donor is not None else "drop", found)) asked.append(dataclasses.replace(case.inputs, **{slot: donor})) - plan.append((case, ablations)) + plan.append((case, base_answer, ablations)) answers = iter(str(out) for out in model.generate_batch(asked)) - for case, ablations in plan: - base_answer = next(answers) + for case, base_answer, ablations in plan: base_key = _norm_answer(base_answer) base_verdict = score(case, base_answer) if base_verdict is not None: by_strategy[BASELINE][case.id] = float(bool(base_verdict)) row: dict[str, Any] = {"sample_id": case.id} - for slot, effective in ablations: - modes_used[slot] = effective + if swap: + row["ablation_base_answer"] = base_answer[:120] + for slot, effective, found in ablations: + modes_used.setdefault(slot, set()).add(effective) answer = next(answers) changed = _norm_answer(answer) != base_key @@ -180,6 +334,11 @@ 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}_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}" verdict = score(case, answer) @@ -203,7 +362,19 @@ 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 + ) + 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 03f261d8..085451ca 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" @@ -157,6 +162,7 @@ class PromptContrastAnalyzer(Analyzer): strategies: dict[str, str] score_fn: Callable[[Any, str], Optional[bool]] | None max_cases: int + gen_kwargs: 'dict[str, Any] | None' def __init__( self, @@ -167,16 +173,19 @@ 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 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 @@ -196,11 +205,12 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: asked = [(case, strat, dataclasses.replace( case.inputs, prompt=template.format(prompt=str(getattr(case.inputs, "prompt", ""))))) for case in selected for strat, template in self.strategies.items()] - outputs = model.generate_batch([inputs for _, _, inputs in asked]) - for (case, strat, _), out in zip(asked, outputs): + replies = model.generate_batch([inputs for _, _, inputs in asked], **dict(self.gen_kwargs or {})) + for (case, strat, _), out in zip(asked, replies): out = str(out) verdict = score(case, out) answers[strat][case.id] = out[:200] + outputs[strat][case.id] = out if verdict is None: n_unscored += 1 continue @@ -268,5 +278,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/analyzers/uncertainty/self_consistency.py b/evalrx/analyzers/uncertainty/self_consistency.py index 78cf9b99..f13a154d 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 @@ -119,6 +124,7 @@ class SelfConsistencyAnalyzer(Analyzer): n: int gen_kwargs: dict[str, Any] semantic: bool + seed: 'int | None' def __init__( self, @@ -127,15 +133,24 @@ 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_batch([case.inputs] * self.n, **self.gen_kwargs) + # One generate call per sample, not one batch: under a seed a case's samples are + # then the same draws whatever the backend's batch size, and the same as before + # the backends batched. + 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/benchmark/run.py b/evalrx/benchmark/run.py index 41de6de2..0bbbb189 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -141,12 +141,70 @@ 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)") 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 = triage controller: after Stage 0, run the triage battery " + "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=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=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=["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") + 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 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-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-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-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, + 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, help="coder-written M2 statistics tools (default: on)") @@ -214,6 +272,16 @@ 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") + if triage and args.triage_max_actions < 0: + raise ValueError("--triage-max-actions must be non-negative") + if triage: + 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: diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 21a4d1e6..add5f508 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 @@ -22,6 +23,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 @@ -168,13 +173,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.triage.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)), @@ -647,6 +679,162 @@ def _run_fix(loop, run_dir: Path, ctx, report, cases, args, fix_tier: str) -> di "attempted": attempted} +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 _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.triage.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 _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.""" + 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) + found, elapsed = _discover(model, candidates, protocol, gen_kwargs, args, task) + source = found.cases + _mark_short_answers_stopped(task, source) + (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), + "label_samples": label_samples(task, args), "n_split": _split_votes(source), + "cases": _case_labels(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, source=None) -> int: + """``--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 + ``--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, 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.triage import explore_confirm_split, run_triage + from evalrx.eval_agent.triage.validation import freeze_issues, partition_bundle, validate + + 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, + 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") + 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, + "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) + 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) + 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} + # 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, 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, + n_fail=args.triage_n_fail, max_fail=args.triage_max_fail, max_actions=args.triage_max_actions, + 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}}, + scheduler=args.triage_scheduler, budget_usd=float(args.triage_budget_usd), explainer=explainer, + 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, + "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, + ) + from evalrx.eval_agent.triage.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, + "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 ("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 {}), + } + (run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n", encoding="utf-8") + print(f"Done (triage). {run_dir / 'probing' / (name + '.md')}" + + (f"; validation: {run_dir / 'validation' / 'validation_report.md'}" if checked else "")) + return 0 + + def run(args, task: T.Task, resolved: Resolved) -> int: """Run one cell: Stage 0 baseline, the diagnosis loop, then M5 and the fix ladder. @@ -665,11 +853,12 @@ 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 = None coder_provider: Any = None coder_model: Any = None coder_extra: Any = None - if not args.baseline_only: + if not args.baseline_only and not triage: # the triage builds its own judge, and only for explanations judge, coder_provider, coder_model, coder_extra = build_judge(args) model, gen_kwargs, spec = _load_target(resolved, args, task, run_dir) @@ -699,6 +888,9 @@ def run(args, task: T.Task, resolved: Resolved) -> int: batch_case_ids=[c.id for c in candidates], ) + 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) cases = discovery.cases if ctx is not None: @@ -712,6 +904,8 @@ def run(args, task: T.Task, resolved: Resolved) -> int: "generation_kwargs": gen_kwargs, "enable_thinking": bool(args.enable_thinking), "manifest": str(manifest), "limit": limit, "label_samples": label_samples(task, args), "n_split": _split_votes(cases), + # what the provider counted for the discovery pass (API models only) + **_usage_cost(model, usage_before), "cases": _case_labels(cases), } version = _api_model_version(model) @@ -734,6 +928,12 @@ 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: + 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) val_cases = None if val_manifest is not None: @@ -768,7 +968,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: hypothesis_tester=HypothesisTester(judge=judge, min_effect=0.05), fix_agent=_fix_agent(args, task, judge, coder_cfg, gen_kwargs, ctx, raw_model, deployed_spec), 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/benchmark/scoring.py b/evalrx/benchmark/scoring.py index 68bc78b2..c1e5d5c9 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 @@ -161,6 +175,55 @@ 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)) + 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 01dd58ab..a6619f1c 100644 --- a/evalrx/benchmark/tasks/__init__.py +++ b/evalrx/benchmark/tasks/__init__.py @@ -17,10 +17,12 @@ ) from .base import ( # noqa: F401 Task, + answer_key, build_cases, 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 ed265e14..b20ed7d8 100644 --- a/evalrx/benchmark/tasks/base.py +++ b/evalrx/benchmark/tasks/base.py @@ -118,6 +118,26 @@ 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 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/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 76992aed..40a4120e 100755 --- a/evalrx/core/model.py +++ b/evalrx/core/model.py @@ -47,6 +47,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/triage/__init__.py b/evalrx/eval_agent/triage/__init__.py new file mode 100644 index 00000000..5f77ecbd --- /dev/null +++ b/evalrx/eval_agent/triage/__init__.py @@ -0,0 +1,55 @@ +"""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 (``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 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 ...) + 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 + evidence.py one step's observations over a growing sample (per-case reuse) + 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 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 + +Nothing here is imported by the default ``judge`` path. +""" + +from __future__ import annotations + +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", + "LAYERS", + "POLICY_VERSION", + "RULES_VERSION", + "Observation", + "PlanStep", + "ProbeAction", + "SampleDraw", + "explore_confirm_split", + "matched_sample", + "run_triage", +] diff --git a/evalrx/eval_agent/triage/actions.py b/evalrx/eval_agent/triage/actions.py new file mode 100644 index 00000000..f0f275f8 --- /dev/null +++ b/evalrx/eval_agent/triage/actions.py @@ -0,0 +1,211 @@ +"""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. +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 + +import hashlib +import json +from dataclasses import asdict, dataclass, field, fields +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); 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)): + 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 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. + + ``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. + + ``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 + 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 + needs_answer: bool = False + 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: + """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 = "battery" + 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 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)}) + 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/triage/controller.py b/evalrx/eval_agent/triage/controller.py new file mode 100644 index 00000000..66e7ed9f --- /dev/null +++ b/evalrx/eval_agent/triage/controller.py @@ -0,0 +1,1988 @@ +"""The triage controller: the battery, nested expansion and follow-ups, chosen by rules or by value. + +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="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 + media tokens late in the stack (S2). + 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: + + * 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. 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.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, +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 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). + +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[.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) +""" + +from __future__ import annotations + +import hashlib +import inspect +import json +import os +import random +import time +from collections import Counter +from functools import lru_cache, partial +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, cast + +from evalrx.analyzers.perturbation.prompt_contrast import _DEFAULT_STRATEGIES as _PROMPT_STRATEGIES +from evalrx.eval_agent.triage.actions import ( + FAILED, + OK, + SKIPPED, + PlanStep, + ProbeAction, + canonical, +) +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, + ExplanationSet, + Hypothesis, + Metric, + carry_over, + check, + decidability, + disagreement, + label_bound, + outcome, + restates_route, +) +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, + ROUTE_ORDER, + RULES_VERSION, + Layer, + Proposal, + active_routes, + candidate_steps, + expansion_gaps, + matched_controls, + next_for_route, + next_size, + public, + route_fail_ids, + route_states, +) +from evalrx.eval_agent.triage.sampler import matched_sample, rank +from evalrx.eval_agent.triage.scoring import ( + SCORING_VERSION, + Scored, + Weights, + availability, + axis_of, + choose, + coverage_gain, + coverage_units, + public_units, + step_cost, + value, +) + +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. +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 +#: 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"]} + +#: 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 = { + "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": "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", +} + +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", + "classify how each Stage-0 output ended, without continuing it"), + 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": "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; 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",), 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",), + 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",), 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", + calls_per_case={"forward": 1}, deferred=True), + PlanStep("patchscope", {"target": "prediction", "media_layers": 3}, "S3", + "decode the answer position at every layer and the media tokens at three depths: " + "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), +) + + +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 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``. + + 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] + + +@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/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 + 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 {}): + 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], + 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) + 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] = {} + self.judge_cost: dict[str, float] = {} + + 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]: + """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 + + 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.""" + 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} " + 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": + """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": + 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 + 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.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.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: + 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]: + """``(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)) + 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}) + 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) 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) + # 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} + 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) -> "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. + + 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} + 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 {why}" + self.ledger.trace({**base, "event": "not_applicable", "reason": reason}) + skipped = {**base, "status": "not_applicable", "reused": False, "reason": reason} + self._log(skipped) + self.say(f"[triage] {step.name}: not applicable ({self.task_kind})") + return skipped + 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 + failed = {**base, "status": "failed", "reused": False, "error": str(exc)} + self._log(failed) + return failed + todo = ev.todo(target) + if not todo: + return None + record: "dict[str, Any] | None" = 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) + 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") -> "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 + # 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 = 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 + skipped = {**base, "status": SKIPPED, "reused": False, "reason": why, "n_cases": len(todo)} + self._log(skipped) + self.say(f"[triage] {step.name}: skipped ({why})") + return skipped + 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)) + 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, + "code": code_version()["tree"], + "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 = 30, + min_route_fail: int = 3, + min_cohort: int = 8, + 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: "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, + layers: "tuple[Layer, ...]" = LAYERS, + 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 = "scored", + weights: "Weights | None" = None, + explore_share: float = 0.1, + 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, +) -> dict[str, Any]: + """Run the battery, the rule-chosen expansions and follow-ups on *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 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); 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. + 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. + 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. 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 + 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). + 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). + 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: ``"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. + 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 + (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 RunLogger 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 other schedulers do not read them") + 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) + out = Path(out_dir) + ledger = Ledger(out) + 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}, + 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, 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, + common=common_answers(explore, answer_fn), + stratum=stratum) + + sample, draw = matched_sample(explore, n_fail, seed=seed, stratum=stratum) + 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. + 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, + "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'})") + + # 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 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: + 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, + "scheduler": scheduler, "rules_version": RULES_VERSION, **record} + ledger.trace(record) + decisions.append(record) + + 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.""" + 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 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 + + 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]) -> "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), + "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}) + 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: + 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] = {} + for x in layers: + for name in (*x.served_by, *(c.name for c in x.candidates)): + step_layers.setdefault((x.route, name), x) + + 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 __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, agree_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"} + 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) + + 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 + + explored_on: set[tuple[str | None, 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 + expansion can still follow.""" + 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.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) + # save compute when the chosen step runs, never change what is chosen. + 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]], 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, 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. 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"]] + # 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]]}) + measured: dict[str, Any] = {} + for key in sorted(CARDS): + read = {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 read: + measured[key] = read + 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_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] + 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 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(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). + + 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), 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 + # 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 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] + 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]], options: dict[str, list[Any]], + outcome_of: Callable[[str, str, Metric], dict[str, Any]], reason: str) -> ExplanationSet: + 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") + 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 + 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}) + 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]]], 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 + # 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) + by_id = {r["case_id"]: r for r in records} + pool: list[Scored] = [] + filtered: list[dict[str, Any]] = [] + 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 + 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 + continue + # 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 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 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, + 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}) + 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 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] + 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 + + explored: dict[str, float] = {} # what exploration decisions spent, per cost 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)) + 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(offer, growing, verdicts, current) + if reason is not None: + 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, options, growing, live, outcome_of) + 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) + 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 + 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, + "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 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, 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 {}), + **({"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": + 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 + 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) + account() + 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 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 + if step_done not in followed: + followed.append(step_done) + round_no += 1 + + 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)) + if gaps and expansion_note is None: + plan = expansion_plan() + if plan is not None: + if n_actions() >= max_actions: + stop = {"reason": "max_actions", "max_actions": max_actions, "pending": "expansion"} + break + refused = run.over_budget(plan[3]) + if refused is not None: + expansion_note = {"state": "skipped", "reason": refused, "gaps": gaps} + decide({"kind": "expand_skipped", "rule_id": "E1", "reason": refused, "gaps": gaps, + "estimate_sec": plan[3]}) + continue + 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}) + + 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, "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)) + 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, + **({"scoring_version": SCORING_VERSION, "weights": weights.__dict__, "explore_share": 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, + "code": code_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, + "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, + "min_cohort": min_cohort, "per_call_generation": per_call_generation, "chunk": chunk}, + "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), "evidence": _evidence_cost(run), + "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, agree_fn), + "routes": _route_report(records, run, rank_of, layers, min_route_fail), + "checks": _acceptance(battery, layers, run, draw, ledger), + "cases": records, + } + 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 _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": + 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}" + + +def report_name(scheduler: str, explained: bool = False) -> str: + """``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 "") + + +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 _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(cast("list[float]", usd)), 6) if all(v is not None for v in usd) else None + return out + + +def _decided(verdicts: dict[str, Any]) -> set[tuple[str, str, str]]: + """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") and p.get("primary", True)} + + +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(cast("list[float]", 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: list[dict[str, Any]] = [] + tally: Counter = 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 = [] + 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, 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 = [] + 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, agree_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 + 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(cast("list[float]", usd)), 6) if all(v is not None for v in usd) else None + return out + + 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(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")} + 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) + 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 { + "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(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: + 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 "") + + +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"{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']}" + + (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 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 ({by_kind or 'none'}), {run.get('calls', {})}" + + (f", {run['api_usage']}, USD {run.get('usd')}" if run.get("api_usage") else "") + "."] + 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']} | {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']} | - | - |", "", + "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."] + 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):", "", + "| 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)", ""] + 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 | answer 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']}._"] + 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] + 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}."] + 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 + 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(("**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" + 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 |", "|---|---:|---|---|---|---|---|"] + 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, held in report["checks"].items(): + lines.append(f"- `{name}`: {held}") + lines.append("") + return "\n".join(lines) diff --git a/evalrx/eval_agent/triage/evidence.py b/evalrx/eval_agent/triage/evidence.py new file mode 100644 index 00000000..62c30ba0 --- /dev/null +++ b/evalrx/eval_agent/triage/evidence.py @@ -0,0 +1,83 @@ +"""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 collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any, Iterable + +from evalrx.eval_agent.triage.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 pick(evidence: "Mapping[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/triage/executor.py b/evalrx/eval_agent/triage/executor.py new file mode 100644 index 00000000..b2d82d61 --- /dev/null +++ b/evalrx/eval_agent/triage/executor.py @@ -0,0 +1,172 @@ +"""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 +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. + +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 + +import time +from typing import TYPE_CHECKING, Any, cast + +from evalrx.eval_agent.triage.actions import ( + FAILED, + OK, + UNFAITHFUL, + UNSUPPORTED, + Observation, + ProbeAction, + canonical, +) +from evalrx.eval_agent.triage.metering import ( + MeteredModel, + gpu_peak_mb, + gpu_peak_reset, + usage_counters, + usage_delta, +) + +if TYPE_CHECKING: + from evalrx.core.analyzer import Analyzer + from evalrx.core.case import CaseBatch + from evalrx.core.model import Model + + +def gate(analyzer: "Analyzer", model: Any, cases: "CaseBatch") -> "str | None": + """Why *analyzer* cannot run here, or ``None`` when its preconditions hold.""" + have: frozenset = 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 + + +#: 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(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. + + 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 + + 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.runlog.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() + usage_before = usage_counters(model) + t0 = time.monotonic() + try: + if per_case: + raw = _run_per_case(analyzer, metered, cases, tuple(keep_artifacts)) + else: + result = analyzer.run(cast("Model", metered), cases) # a proxy, not a subclass + 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: + 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(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 {} + 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, + # 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/triage/explanations.py b/evalrx/eval_agent/triage/explanations.py new file mode 100644 index 00000000..31043ae4 --- /dev/null +++ b/evalrx/eval_agent/triage/explanations.py @@ -0,0 +1,700 @@ +"""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 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; +* ``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. 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"``), +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. 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 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 +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 +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, replace +from itertools import combinations +from pathlib import Path +from typing import Any, Callable, Iterable + +from evalrx.eval_agent.triage.metering import usage_counters, usage_delta +from evalrx.stats.intervals import newcombe_interval, t_quantile, z_quantile + +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"} +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"} + + +#: 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]: + """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 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 +#: 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 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 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 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 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 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"),), + # 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"),), + "gradcam": ( + Metric("gc_media_grad_share", "share of gradient x activation on the media tokens (at mid depth) of " + "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 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)), + "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 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 " + "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 -------------------------------------------------------------------- + +def _mean(xs: list[float]) -> float: + return sum(xs) / len(xs) + + +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 = 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) + 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 = t_quantile(level, 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, 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"]] + + 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, level) + 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 + + +# -- 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 t_quantile(0.95, 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": + rates = [(len(g), (sum(1 for x in g if x >= 0.5) + 2) / (len(g) + 4)) for g in groups if g] + if not rates: + return None + return math.sqrt(sum(m * p * (1 - p) for m, p in rates) / sum(m for m, _ in rates)) + 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 ------------------------------------------------------------------------------- + + +@dataclass +class Hypothesis: + id: str + route: str + 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, "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 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 +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 + 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, "carried": self.carried, + "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. 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)}) + 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 + + +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: 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 + 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": [], "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, {}) + 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: + 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 --------------------------------------------------------------------------------- + +_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. 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 +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. + +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" 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. 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"}}}}, + "primary": [["", ""]]}}]}}}} + +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), 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: + 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 + 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 step is None or reading is None or 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(), 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"}) + continue + kept.append(h) + out += kept + 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. + + *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 + failed = {"wall_sec": round(time.monotonic() - started, 3), "calls": {"judge": 1}} + return ExplanationSet(revision, key, offered=offered, source="failed", cost=failed, + 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/triage/ledger.py b/evalrx/eval_agent/triage/ledger.py new file mode 100644 index 00000000..19f8b999 --- /dev/null +++ b/evalrx/eval_agent/triage/ledger.py @@ -0,0 +1,99 @@ +"""Append-only run records and resume. + +Layout under the run's ``probing/`` directory:: + + 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 + +import json +import os +from pathlib import Path +from typing import Any + +from evalrx.eval_agent.triage.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, 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(): + 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) diff --git a/evalrx/eval_agent/triage/metering.py b/evalrx/eval_agent/triage/metering.py new file mode 100644 index 00000000..129816ff --- /dev/null +++ b/evalrx/eval_agent/triage/metering.py @@ -0,0 +1,123 @@ +"""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. + +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 + +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) + + # The batch calls are counted per input under the single call's name, so a + # step's call counts read the same whether its analyzer batches or not. + def _timed_batch(self, method: str, fn: Any, inputs: Any, **kwargs: Any) -> Any: + items = list(inputs) + t0 = time.monotonic() + failed = len(items) + try: + outs = fn(items, **kwargs) + failed = sum(1 for out in outs if isinstance(out, Exception)) + return outs + finally: + with self._lock: + self.calls[method] += len(items) + if failed: + self.errors[method] += failed + self.model_sec += time.monotonic() - t0 + + def generate_batch(self, inputs: Any, **kwargs: Any) -> Any: + return self._timed_batch("generate", self._metered.generate_batch, inputs, **kwargs) + + def try_generate_batch(self, inputs: Any, **kwargs: Any) -> Any: + return self._timed_batch("generate", self._metered.try_generate_batch, inputs, **kwargs) + + def logprobs_batch(self, inputs: Any, **kwargs: Any) -> Any: + return self._timed_batch("logprobs", self._metered.logprobs_batch, inputs, **kwargs) + + +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 + 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/triage/partition.py b/evalrx/eval_agent/triage/partition.py new file mode 100644 index 00000000..6d2b5a5a --- /dev/null +++ b/evalrx/eval_agent/triage/partition.py @@ -0,0 +1,69 @@ +"""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. + +``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.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. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +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, *, + 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.partition import split_cases + + explore, confirm, _test = split_cases(data, confirm_split=float(confirm_split), test_split=0.0, seed=int(seed)) + 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.partition import _strat_key + from evalrx.eval_agent.triage.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(_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/triage/routes.py b/evalrx/eval_agent/triage/routes.py new file mode 100644 index 00000000..427acaa1 --- /dev/null +++ b/evalrx/eval_agent/triage/routes.py @@ -0,0 +1,787 @@ +"""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** (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. + 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 + ``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 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. 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 (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. +* **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. +""" + +from __future__ import annotations + +import math +from collections import Counter +from collections.abc import Mapping +from typing import Any, Callable, cast + +from evalrx.analyzers.perturbation.prompt_contrast import _norm_answer +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" + +#: (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") +_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"] +#: ``(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. +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.""" + 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) + + +#: 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 + + +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) + + +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": + """Why *obs* cannot be read, or ``None``: then it exists and ran (callers narrow it with ``_ran``).""" + 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 _ran(obs: "Observation | None") -> Observation: + """*obs* after :func:`_unavailable` returned ``None`` for it.""" + return cast(Observation, obs) + + +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} + obs = _ran(obs) + 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", 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"} + why = _unavailable(obs, "modality_ablation") + if why is not None: + return {"state": UNTESTED, "reason": why} + obs = _ran(obs) + 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"} + common = common or {} + agree = agree_fn or exact_answer + base_key = answer_fn(case, str(out["base_answer"])) if common and answer_fn else None + hit = next((g for g in common if base_key and agree(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_"): + 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") + 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") + 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") + 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 _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, 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. 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: + return {"part": "sampling", "state": UNTESTED, "reason": why} + obs = _ran(obs) + 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"} + 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} + + +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, agree_fn: AgreeFn) -> dict[str, Any]: + why = _unavailable(obs, "prompt_contrast (rewording)") + if why is not None: + return {"part": "reword", "state": UNTESTED, "reason": why} + obs = _ran(obs) + 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} + 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=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 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, 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 + 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, 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"} + why = _unavailable(obs, "prompt_contrast (threshold)") + if why is not None: + return {"state": UNTESTED, "reason": why} + obs = _ran(obs) + 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=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"} + + +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} + obs = _ran(obs) + 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": + obs = _ran(obs) + 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: "Mapping[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", 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 + ``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 + media differs from the model's answer — because a content-only swap there often leaves the + 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 + :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"``; + a gold stratum there leaves almost no PASS case with a FAIL case's gold to serve as its control. + """ + from evalrx.eval_agent.triage.sampler import STRATA + + answer, agree = answer_fn or default_answer, agree_fn or exact_answer + stratum_of = STRATA[stratum] + records = [] + for case in cases: + cid = str(case.id) + provenance = finish_reason_source(case, host_assumed_finish) + h_fields = [ + _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] + 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(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) + 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 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": label, + "stratum": stratum_of(case), + "routes": routes, + "stable": stable, + "x_reasons": x_reasons, + "H": h, + "N": n, + "U": u, + "knockout": _knockout(pick(observations, "attention_knockout", cid), cid), + "S_readings": { + "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), + }, + }) + 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. + + 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). + """ + 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 _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, 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 + 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 (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 + + +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. ``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"], + "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(): + 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, + "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") + } + 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"] + 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 model's own first answer 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 + + +#: 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, 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, 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``: + 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 {}): + 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(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) + 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) + 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, + 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) + 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, 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")} + 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, 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 + 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, 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"] + 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/evalrx/eval_agent/triage/rules.py b/evalrx/eval_agent/triage/rules.py new file mode 100644 index 00000000..28a2faec --- /dev/null +++ b/evalrx/eval_agent/triage/rules.py @@ -0,0 +1,336 @@ +"""The rules: what each route runs next, and when the sample is expanded. + +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 +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.triage.actions import PlanStep +from evalrx.eval_agent.triage.evidence import StepEvidence + +RULES_VERSION = "rules-5" +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, 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 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 +#: 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, + "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, needs_answer=True) + + +@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, and + ``filter_note`` says so in the layer's state (the trace and the report). + """ + + 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 = "cold-start prior (rules.LAYERS)" + + +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 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 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": "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"),)), + 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, 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, 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",), 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: " + "concentration only, not 'mislocalised')", ( + 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": "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", "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), + PlanStep("layer_contrast", {}, "S3", "early-vs-late layer contrast at the answer position", + 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)", ( + 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 + + target_override: "list[str] | None" = None # a battery step runs on the whole sample + + @property + def target_ids(self) -> list[str]: + 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, + 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 {} + pending = pending or {} + if not fail_ids: + return {"rule_id": layer.rule_id, "state": "no_cases"} + for name in layer.served_by: + if name in pending 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): + 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 ev is not None and 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, + 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, pending) + out.append({**state, "question": layer.question, "n_fail": len(fail_ids), "n_controls": len(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 + + +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 not in ("step", "target")} + 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/triage/sampler.py b/evalrx/eval_agent/triage/sampler.py new file mode 100644 index 00000000..02fbf404 --- /dev/null +++ b/evalrx/eval_agent/triage/sampler.py @@ -0,0 +1,112 @@ +"""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: + """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() + + + +@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/triage/scoring.py b/evalrx/eval_agent/triage/scoring.py new file mode 100644 index 00000000..446103d2 --- /dev/null +++ b/evalrx/eval_agent/triage/scoring.py @@ -0,0 +1,277 @@ +"""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): 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, + ``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, 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). + 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 + 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 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 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 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). +""" + +from __future__ import annotations + +import random +from dataclasses import dataclass, field +from typing import Any + +from evalrx.eval_agent.triage.actions import OK, UNSUPPORTED, PlanStep +from evalrx.eval_agent.triage.evidence import StepEvidence + +SCORING_VERSION = "score-5" + + +@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 + 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 + 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 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: + 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[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``) 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") 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) + 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 ------------------------------------------------------------------- + + +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_share: float, explored: float, + 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: 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 + 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/evalrx/eval_agent/triage/validation.py b/evalrx/eval_agent/triage/validation.py new file mode 100644 index 00000000..3f733477 --- /dev/null +++ b/evalrx/eval_agent/triage/validation.py @@ -0,0 +1,791 @@ +"""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), 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: + +* ``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, 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: 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 +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 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 +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 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 + +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.triage.actions import PlanStep +from evalrx.eval_agent.triage.explanations import ( + CARDS, + MIN_N, + Metric, + label_bound, + outcome, + primary_readings, + restates_route, + verdict, +) +from evalrx.eval_agent.triage.ledger import Ledger +from evalrx.eval_agent.triage.routes import ( + ROUTE_STEPS, + commits_to_answers, + common_answers, + 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 +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 = "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"} +#: 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") + + +# -- 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" (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] + 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) + 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}) + + 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 _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, source: "CaseBatch | None" = None, + 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. + *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} + 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" 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=excluded, + n_sources={"discovery": len(seen), "validation": len({source_key(c) for c in kept})}, + 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), split_by=str(split_by)) + 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 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()) + 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 = 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)} + + +# -- phenomena ------------------------------------------------------------------------------------------ + + +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).""" + links: list[dict[str, Any]] = [] + 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_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) + 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 _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 + 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, 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, + 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.triage.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) + 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 - 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: dict[str, Any] = {"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, + "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}") + + # -- 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, + 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: + 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, 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))} + 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)} + issue_step = steps.get(issue.step) + if issue_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(issue_step, [*fail_ids, *controls], kind="validation", revision=0, route=issue.route) + ev = run.evidence.get(issue_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, issue_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, 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() + 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()))}") + + # 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, + "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), + "validation": results[i.issue_id], "phenomenon": phenomenon_of[i.issue_id]} for i in family], + "phenomena": phenomena, + "phenomenon_links": links, + "arms": credit, + "phenomenon_curve": curve, + "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 " + "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 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, 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). + + 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 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({**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, 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)}) + 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: + 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'))})", "", + 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 " + 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 |", "|---|---|---|---|---|---|---|"] + 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']} |") + 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 = [("**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/api/backend.py b/evalrx/models/backends/api/backend.py index 6f5badfa..e4ebd5b0 100755 --- a/evalrx/models/backends/api/backend.py +++ b/evalrx/models/backends/api/backend.py @@ -116,6 +116,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 407aab0a..c019ff5e 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/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/_util.py b/evalrx/models/backends/hf/_util.py index 75619963..ffe95f34 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 675941f7..614e4f3a 100755 --- a/evalrx/models/backends/hf/model.py +++ b/evalrx/models/backends/hf/model.py @@ -20,6 +20,7 @@ import logging from collections.abc import Sequence +from contextlib import nullcontext from typing import Any, Callable, TypeVar from evalrx.core.capability import Capability, CapabilityError @@ -28,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, @@ -37,6 +38,7 @@ _populate_vision_extras, _read_nested_attr, collate_encodings, + media_encoders_without_grad, ) from evalrx.models.backends.hf.decoding import ContrastiveDecodingMixin from evalrx.models.backends.hf.specialists import SpecialistRepairsMixin @@ -456,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 @@ -717,8 +719,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/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/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 04ff7051..0a6a00cd 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -165,3 +165,39 @@ def run(loop, data): monkeypatch.setattr(VLDiagnoseLoop, '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.triage.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': 'medium'} + 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', + '--triage-scheduler', 'scored', '--triage-explanations', 'judge']) + with pytest.raises(SystemExit, match='model under test'): + runner._triage_explainer(same, spec) + + +def test_triage_defaults_are_the_scored_scheduler_and_the_exploration_share_is_checked(): + from evalrx.benchmark.run import main as run_main + + args = build_parser().parse_args([]) + 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_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..8c083d81 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: @@ -340,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 @@ -753,6 +865,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 +1102,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 new file mode 100644 index 00000000..68198e0f --- /dev/null +++ b/tests/test_analyzers/test_modality_ablation_swap.py @@ -0,0 +1,185 @@ +"""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) + + +# ── 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_analyzers/test_prompt_contrast.py b/tests/test_analyzers/test_prompt_contrast.py index 9422571e..1fbda803 100755 --- a/tests/test_analyzers/test_prompt_contrast.py +++ b/tests/test_analyzers/test_prompt_contrast.py @@ -186,3 +186,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_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_triage_alternatives.py b/tests/test_eval_agent/test_triage_alternatives.py new file mode 100644 index 00000000..a168e7db --- /dev/null +++ b/tests/test_eval_agent/test_triage_alternatives.py @@ -0,0 +1,185 @@ +"""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 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). +""" + +from __future__ import annotations + +import json + +import pytest + +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): + 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(): + 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)] + return json.dumps({"routes": routes}) + + +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(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): + 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_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 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 + 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"]) diff --git a/tests/test_eval_agent/test_triage_chunks.py b/tests/test_eval_agent/test_triage_chunks.py new file mode 100644 index 00000000..260c3ac4 --- /dev/null +++ b/tests/test_eval_agent/test_triage_chunks.py @@ -0,0 +1,178 @@ +"""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 json + +import pytest + +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 + + +@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 + + +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"] diff --git a/tests/test_eval_agent/test_triage_expansion.py b/tests/test_eval_agent/test_triage_expansion.py new file mode 100644 index 00000000..99890c09 --- /dev/null +++ b/tests/test_eval_agent/test_triage_expansion.py @@ -0,0 +1,464 @@ +"""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.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.rules import ( + active_routes, + candidate_steps, + expansion_gaps, + next_for_route, + next_size, +) +from evalrx.stats.intervals import newcombe_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, + 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} + + +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 + # the descriptive steps no route reads wait for the settled sample, then run on it once (in chunks) + for key in ("embed_lens", "patchscope"): + 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 + 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_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}} + + 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.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")): + 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): + 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"] + 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"])]) + assert batchy.todo(["a", "b"]) == [] and batchy.todo(["a", "b", "c"]) == ["a", "b", "c"] + + +def test_expansion_gaps_and_sizes(): + 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 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": 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}} + + 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_and_charge_the_evidence(tmp_path): + 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") + 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]) + 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 + # 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 -------------------------------------------------------- + +#: 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", + "embed_lens", "patchscope", "tuned_lens", "causal_trace"} + + +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.triage.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) + + +REF = "" + + +@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", {}), + # 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 + + +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 + + +def test_a_layer_that_narrows_its_route_states_its_filter(): + 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)] + 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_triage_explanations.py b/tests/test_eval_agent/test_triage_explanations.py new file mode 100644 index 00000000..1d5cbde1 --- /dev/null +++ b/tests/test_eval_agent/test_triage_explanations.py @@ -0,0 +1,456 @@ +"""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.triage import run_triage +from evalrx.eval_agent.triage.explanations import ( + CARDS, + Explainer, + Hypothesis, + Metric, + check, + difference, + disagreement, + observed, + outcome, + parse, + verdict, +) +from tests.test_eval_agent.test_triage_expansion 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 + # 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.triage.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(): + 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_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", "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, 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 "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 + 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; 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, primary=()): + self.prompts, self.fail, self.primary = [], fail, set(primary) + + 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(): + 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}) + + +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"] > 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() + 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 _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.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", + "re-ask inside a wrapper", key="wrapped") + 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", (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" + 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" + # 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.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 + # 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): + 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={}))) + + +@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 + + 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"] + + +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.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),)) + 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(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)) + + 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 + + +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.triage.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.triage.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.triage.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_triage_routes.py b/tests/test_eval_agent/test_triage_routes.py new file mode 100644 index 00000000..4063372e --- /dev/null +++ b/tests/test_eval_agent/test_triage_routes.py @@ -0,0 +1,888 @@ +"""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; +* 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.triage import explore_confirm_split, matched_sample, run_triage +from evalrx.eval_agent.triage.actions import ( + FAILED, + OK, + UNFAITHFUL, + UNSUPPORTED, + Observation, + ProbeAction, +) +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"): + 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 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] + 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 -------------------------------------------------------------------- + + +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", 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}, + {"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_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 _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.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 + _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_common_answers_are_the_golds_a_share_of_discovery_has(): + 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) + 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.triage.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"})]) + 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" + + +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"), # 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 + ]) + 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": ["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.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"] + 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": 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={})) + 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 _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.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] + 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"), + _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 --------------------------------------------------------------- + + +@pytest.fixture() +def vlm_cases(): + pytest.importorskip("torch") + 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, (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 {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) + + +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_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, 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) + 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 + 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_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 + expected_donor = {"pope-1": "pope-3", "pope-5": "pope-7", "pope-2": "pope-4", "pope-6": "pope-0"} + for rec in report["cases"]: + 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"] == "prediction" + 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"] * 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() + + # 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(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 + events = [json.loads(line) for line in (out / "selection_trace.jsonl").read_text().splitlines()] + assert [e["event"] for e in events].count("reused") == 9 + + # a different model identity is a different action: nothing is reused + other = run_triage(model, vlm_cases, **{**kw, "model_identity": {**ident, "dtype": "fp32"}}) + 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["executions"] if s["status"] != "not_applicable" and not s["reused"]] + + +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, scheduler="rules") + 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(model, vlm_cases, **kw) + assert _rerun(second) == ["attention_knockout"] + assert _steps(second)["attention_knockout"]["action_id"] != _steps(first)["attention_knockout"]["action_id"] + + +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, scheduler="rules", + 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/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] + 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_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, scheduler="rules", + 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.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/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/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/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_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, scheduler="rules") + 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(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 _rerun(second) == ["attention_knockout"] + + +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, scheduler="rules") + steps = _steps(report) + 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_runs_its_behavioural_follow_up(tmp_path, vlm_cases): + from evalrx.models.backends.api.prices import usd + + 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, 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}) + 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"] + 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["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. 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 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 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 + + +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) + + +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 + + +def test_metered_model_counts_batch_calls_per_input(): + from evalrx.eval_agent.triage.metering import MeteredModel + + class Batched: + def generate_batch(self, inputs, **kwargs): + return [str(i) for i in inputs] + + def try_generate_batch(self, inputs, **kwargs): + return ["a", ValueError("no answer")] + + def logprobs_batch(self, inputs, **kwargs): + return [[] for _ in inputs] + + metered = MeteredModel(Batched()) + assert metered.generate_batch([1, 2, 3]) == ["1", "2", "3"] + metered.try_generate_batch([1, 2]) + metered.logprobs_batch([1]) + assert dict(metered.calls) == {"generate": 5, "logprobs": 1} + assert dict(metered.errors) == {"generate": 1} diff --git a/tests/test_eval_agent/test_triage_scoring.py b/tests/test_eval_agent/test_triage_scoring.py new file mode 100644 index 00000000..3ad9d652 --- /dev/null +++ b/tests/test_eval_agent/test_triage_scoring.py @@ -0,0 +1,152 @@ +"""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; +* 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 + +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.evidence import StepEvidence +from evalrx.eval_agent.triage.rules import candidate_steps +from evalrx.eval_agent.triage.scoring import ( + Scored, + availability, + choose, + coverage_gain, + per_case_costs, + step_cost, +) +from tests.test_eval_agent.test_triage_expansion 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_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(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 + # 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_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_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))] + 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, targets=targets, **kw) + assert (best.key, why) == ("early", "best") + # 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(pool, decision_no=3, explored=0.0, spent=90.0, targets=[], **kw)[1] == "best" + 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_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)) + 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"]] + 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): + 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", + "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) diff --git a/tests/test_eval_agent/test_triage_validation.py b/tests/test_eval_agent/test_triage_validation.py new file mode 100644 index 00000000..0e2d1c95 --- /dev/null +++ b/tests/test_eval_agent/test_triage_validation.py @@ -0,0 +1,307 @@ +"""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.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, + freeze_issues, + group_phenomena, + partition_bundle, + source_key, + supported_curve, + validate, +) +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 + +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"] + 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 + + 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): + 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])}, + "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", "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"]) + 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" + # 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 + 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() + # both reports and every planned action say which code ran + 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) + 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): + 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_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) + 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": "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_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"}} + 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) + + +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 4f600a2e..2ec7884d 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -166,6 +166,50 @@ 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 + # 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): """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 @@ -277,6 +321,8 @@ def test_cli_no_model_paths(common, capsys): "claude", None, "medium" ) 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([ @@ -635,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_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 # ---------------------------------------------------------------------- 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_media_encoders_no_grad.py b/tests/test_models/test_media_encoders_no_grad.py new file mode 100644 index 00000000..e92dae0b --- /dev/null +++ b/tests/test_models/test_media_encoders_no_grad.py @@ -0,0 +1,102 @@ +"""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 _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(_requires_grad(out))) + 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/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 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 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)